From 87568da152fa27ecd6e467e235945416185464d8 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Mon, 9 Nov 2026 23:10:27 +1100 Subject: [PATCH] Run block-setter class methods and guarded raises A class method called with a block runs when its parameters are optional literals and its body only branches on them and stores ivars puppet never reads. A top-level raise runs only when its if/unless condition holds, nil? is evaluated, and a statement guarded by block_given? outside a method never runs. Generates shellvar. --- internal/gentypes/eval.go | 181 ++++++++++- internal/gentypes/fidelity_test.go | 33 ++ internal/gentypes/generate.go | 2 +- internal/gentypes/load.go | 26 ++ internal/gentypes/parse.go | 17 + .../augeasproviders_shellvar/LICENSE | 201 ++++++++++++ .../lib/puppet/provider/shellvar/augeas.rb | 306 ++++++++++++++++++ .../lib/puppet/type/shellvar.rb | 222 +++++++++++++ internal/gentypes/testdata/golden/shellvar.pp | 73 +++++ 9 files changed, 1052 insertions(+), 9 deletions(-) create mode 100644 internal/gentypes/testdata/env/external_modules/augeasproviders_shellvar/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/augeasproviders_shellvar/lib/puppet/provider/shellvar/augeas.rb create mode 100644 internal/gentypes/testdata/env/external_modules/augeasproviders_shellvar/lib/puppet/type/shellvar.rb create mode 100644 internal/gentypes/testdata/golden/shellvar.pp diff --git a/internal/gentypes/eval.go b/internal/gentypes/eval.go index db4253d..53e3552 100644 --- a/internal/gentypes/eval.go +++ b/internal/gentypes/eval.go @@ -28,6 +28,14 @@ type sdef struct { mod, dir string file, src string param string + // optional parameters with their one-token literal defaults, and the &block parameter + opts []sparam + block string +} + +type sparam struct { + name string + tok int } var errNext = errors.New("next") @@ -68,16 +76,38 @@ func (c *classCtx) defSingleton(p *parser, name string, off int) *sdef { } // newSdef starts the body of the method whose name is at p.i+off, or returns nil when the method takes parameters. +// newSdef starts the body of the method whose name is at p.i+off, or returns nil when a call without arguments would +// not bind its parameters: only optional ones with literal defaults and a &block parameter are allowed. func (p *parser) newSdef(off int) *sdef { - start := p.i + off + 1 - switch t := p.at(off + 1); { - case t.kind == tNL || t.text == ";": - case t.text == "(" && !t.space && p.at(off+2).text == ")": - start += 2 - default: + sd := &sdef{toks: p.toks, consts: p.consts, cref: slices.Clone(p.cref), mod: p.mod, dir: p.dir, file: p.file, src: p.src} + j := off + 1 + if t := p.at(j); t.text == "(" && !t.space { + for j++; p.at(j).text != ")"; j++ { + t, eq, def := p.at(j), p.at(j+1), p.at(j+2) + switch { + case t.text == "&" && isLocal(eq) && sd.block == "": + sd.block = eq.text + j++ + case isLocal(t) && eq.text == "=" && (def.kind == tStr && len(def.parts) <= 1 && (len(def.parts) == 0 || !def.parts[0].code) && def.flags != "`" || def.kind == tSym && def.parts == nil || + def.kind == tNum || def.kind == tIdent && (def.text == "nil" || def.text == "true" || def.text == "false")): + sd.opts = append(sd.opts, sparam{t.text, p.i + j + 2}) + j += 2 + default: + return nil + } + if p.at(j+1).text == "," { + j++ + } else if p.at(j+1).text != ")" { + return nil + } + } + j++ + } + if t := p.at(j); t.kind != tNL && t.text != ";" { return nil } - return &sdef{toks: p.toks, start: start, consts: p.consts, cref: slices.Clone(p.cref), mod: p.mod, dir: p.dir, file: p.file, src: p.src} + sd.start = p.i + j + return sd } // opaque marks singleton methods w10k does not evaluate, such as accessors and command methods. @@ -170,6 +200,18 @@ func (p *parser) sub(sd *sdef, name string) (*parser, error) { if len(sd.cref) > 0 { q.scope = sd.cref[len(sd.cref)-1] } + for _, o := range sd.opts { + q.i = o.tok + v, err := q.primary() + if err != nil { + return nil, err + } + q.locals[o.name] = v + } + if sd.block != "" { + q.locals[sd.block] = rval{k: vNil} + } + q.i = sd.start return q, nil } @@ -281,6 +323,8 @@ func (p *parser) method(v rval, m string) (rval, error) { switch { case m == "freeze" && v.k != vType: return v, nil + case m == "nil?" && v.k != vUndet: + return rval{k: map[bool]vkind{true: vTrue, false: vFalse}[v.k == vNil]}, nil case m == "to_s" && (v.k == vStr || v.k == vSym): return rval{k: vStr, s: v.s}, nil case (m == "to_sym" || m == "intern") && (v.k == vStr || v.k == vSym): @@ -539,6 +583,9 @@ func (p *parser) evalStmt(c *classCtx) (bool, error) { if p.is(tIdent, "define_method") { return true, p.defineMethod(c) } + if isLocal(p.cur()) && (p.at(1).text == "{" || p.at(1).text == "do") && (c.kind == kProv || c.kind == kParsed) { + return true, p.blockCall(c) + } if !p.eachAhead() { return false, nil } @@ -744,7 +791,7 @@ func (p *parser) extend(c *classCtx) error { // superWrapper checks that provider method body sd calls super first and then only sets ivars puppet never reads, so // calling it does what the method it shadows does. func (p *parser) superWrapper(c *classCtx, sd *sdef) error { - if sd == nil || c.kind != kProv && c.kind != kParsed { + if sd == nil || len(sd.opts) > 0 || sd.block != "" || c.kind != kProv && c.kind != kParsed { return fmt.Errorf("not a super wrapper") } q, err := p.sub(sd, "super wrapper") @@ -1165,6 +1212,124 @@ func (p *parser) regexpNew() (rval, error) { return rval{}, fmt.Errorf("unsupported Regexp.new arguments") } +// blockCall runs class method name with a block and no arguments: its body may only branch on its parameters and +// store values in ivars puppet never reads; the block itself runs only when called later. +func (p *parser) blockCall(c *classCtx) error { + name := p.take().text + sd, found, err := p.singleton(c, name) + switch { + case err != nil: + return err + case !found: + return fmt.Errorf("undefined method %s", name) + case sd == nil: + return fmt.Errorf("singleton method %s is not evaluable", name) + } + if err := p.skipBlock(); err != nil { + return err + } + q, err := p.sub(sd, name) + if err != nil { + return err + } + if sd.block != "" { + q.locals[sd.block] = rval{k: vBlock} + } + if err := q.branches(c, true); err != nil { + return fmt.Errorf("%s: %w", name, err) + } + if !q.is(tIdent, "end") || q.i != sd.end { + return fmt.Errorf("%s: unsupported %s", name, q.construct()) + } + return nil +} + +// branches runs, or with run false skips, the statements before the next end, elsif or else: if/unless statements +// and assignments to ivars puppet never reads. +func (p *parser) branches(c *classCtx, run bool) error { + for p.skipNL(); !p.is(tIdent, "end") && !p.is(tIdent, "elsif") && !p.is(tIdent, "else"); p.skipNL() { + t := p.cur() + switch { + case t.kind == tEOF: + return fmt.Errorf("unexpected end of file") + case !run: + if err := p.skipStatement(); err != nil { + return err + } + continue + case t.kind == tIdent && (t.text == "if" || t.text == "unless"): + if err := p.ifStmt(c); err != nil { + return err + } + case t.kind == tIVar && !strings.HasPrefix(t.text, "@@") && p.assigns() && !puppetReads(c.kind, t.text[1:]): + p.i += 2 + if _, err := p.eval(); err != nil { + return err + } + default: + return fmt.Errorf("unsupported %s", p.construct()) + } + if t := p.cur(); t.kind != tNL && t.text != ";" && !p.is(tIdent, "end") { + return fmt.Errorf("unsupported %s", describe(t)) + } + } + return nil +} + +// ifStmt runs the first branch of an if or unless statement whose condition holds; Ruby evaluates no condition +// after it and runs no other branch. +func (p *parser) ifStmt(c *classCtx) error { + defer func() { p.depth-- }() + if err := p.enter(); err != nil { + return err + } + unless, taken := p.take().text == "unless", false + for { + run := false + if taken { + if err := p.skipStatement(); err != nil { + return err + } + } else { + cond, err := p.eval() + if err != nil { + return err + } + run = truthy(cond) != unless + taken = run + } + if p.is(tIdent, "then") { + p.take() + } + if err := p.branches(c, run); err != nil { + return err + } + switch { + case p.is(tIdent, "end"): + p.take() + return nil + case p.is(tIdent, "elsif") && !unless: + p.take() + case p.is(tIdent, "else"): + p.take() + if err := p.branches(c, !taken); err != nil { + return err + } + return p.expectEnd() + default: + return fmt.Errorf("unsupported %s", p.construct()) + } + } +} + +func (p *parser) expectEnd() error { + if !p.is(tIdent, "end") { + return fmt.Errorf("expected end, found %s", describe(p.cur())) + } + p.take() + return nil +} + func capitalize(s string) string { return strings.ToUpper(s[:1]) + s[1:] } // loadType ports Puppet::Type.type(name): a loaded type, or the first puppet/type/.rb the typeloader finds in diff --git a/internal/gentypes/fidelity_test.go b/internal/gentypes/fidelity_test.go index a42bdac..e38d341 100644 --- a/internal/gentypes/fidelity_test.go +++ b/internal/gentypes/fidelity_test.go @@ -336,3 +336,36 @@ func TestFeatureSkips(t *testing.T) { }) } } + +const blockParent = "Puppet::Type.type(:u).provide(:base) do\n def self.lens(resource = nil, &block)\n if block\n @lens_block = block\n else\n" + + " raise(Puppet::Error, 'Lens is not provided') unless @lens_block\n @lens_block.call(resource)\n end\n end\n" + + " def self.path(resource = nil, &block)\n if block\n @path_block = block\n elsif @path_block\n @path_block.call(resource)\n else\n" + + " \"#{resource[:name]}\"\n end\n end\n def self.label(a = 'lbl', b = :s, &blk)\n a\n end\n def self.ivdoc(&block)\n @doc = block\n end\nend\n" + +func blockEnv(prov string) map[string]string { + return map[string]string{"m/lib/puppet/type/u.rb": typeWith("u", ""), "m/lib/puppet/provider/u/base.rb": blockParent, + "m/lib/puppet/type/t.rb": typeWith("t", " newparam(:zz) if block_given?\n ensurable do\n defaultvalues\n newvalue(:extra) if block_given?\n block if block_given?\n end\n"), + "m/lib/puppet/provider/t/x.rb": prov} +} + +// Class methods called with a block store it, block_given? is false outside methods, and a guarded raise does not +// run, so openvox 9.3.0 writes t.pp with want. +func TestFidelityBlockCalls(t *testing.T) { + env := fidelityEnv(t, blockEnv("raise('Missing u') if Puppet::Type.type(:u).nil?\nPuppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:u).provider(:base)) do\n"+ + " lens { 'Shellvars.lns' }\n path do |resource|\n if resource\n 'a'\n else\n 'b'\n end\n end\n NAME = label\n desc NAME\nend\n")) + b := readFile(t, filepath.Join(env, OutDir, "t.pp")) + if !strings.Contains(b, " # x\n # : lbl\n") || strings.Contains(b, "zz") || strings.Contains(b, "extra") { + t.Fatalf("t.pp differs from puppet's:\n%s", b) + } + for name, prov := range map[string]string{ + "guarded raise runs": "raise('Missing nope') if Puppet::Type.type(:nope).nil?\nPuppet::Type.type(:t).provide(:x) do\nend\n", + "block stored in @doc": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:u).provider(:base)) do\n ivdoc { 'x' }\nend\n", + "block call without block": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:u).provider(:base)) do\n lens\nend\n", + } { + t.Run(name, func(t *testing.T) { + if exists(filepath.Join(fidelityEnv(t, blockEnv(prov)), OutDir, "t.pp")) { + t.Fatal("t.pp written; real puppet writes none") + } + }) + } +} diff --git a/internal/gentypes/generate.go b/internal/gentypes/generate.go index 2cf5a68..579d637 100644 --- a/internal/gentypes/generate.go +++ b/internal/gentypes/generate.go @@ -18,7 +18,7 @@ import ( const OutDir = ".resource_types" // Version changes whenever generated output can change, so deploys rebuild typed environments. -const Version = "12" +const Version = "13" var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) diff --git a/internal/gentypes/load.go b/internal/gentypes/load.go index 8a8b00b..31f4a7c 100644 --- a/internal/gentypes/load.go +++ b/internal/gentypes/load.go @@ -233,6 +233,8 @@ func (p *parser) fileStmt(prov func() (bool, error)) func() (bool, error) { return true, p.unshift() case p.featuresCall("add"): return true, p.featureAdd() + case t.kind == tIdent && (t.text == "raise" || t.text == "fail"): + return true, p.guardedRaise() case prov != nil: if ok, err := prov(); ok || err != nil { return true, err @@ -242,6 +244,30 @@ func (p *parser) fileStmt(prov func() (bool, error)) func() (bool, error) { } } +// guardedRaise runs raise ... if/unless cond, which raises when the condition holds; Ruby evaluates the raise +// arguments only then. +func (p *parser) guardedRaise() error { + start := p.i + depth := 0 + for ; p.cur().kind != tEOF && (depth > 0 || p.cur().kind != tNL && !p.op(";")); p.i++ { + t := p.cur() + switch { + case t.kind == tOp && strings.Contains("([{", t.text): + depth++ + case t.kind == tOp && strings.Contains(")]}", t.text): + depth-- + case depth == 0 && t.kind == tIdent && (t.text == "if" || t.text == "unless") && p.i > start+1: + unless := p.take().text == "unless" + cond, err := p.eval() + if err == nil && truthy(cond) != unless { + err = fmt.Errorf("%s raises", p.toks[start].text) + } + return err + } + } + return fmt.Errorf("unsupported top-level %s", p.toks[start].text) +} + // lexical resolves constant path c as Ruby does from the current lexical scope, or returns "" when it is undefined. func (p *parser) lexical(c string) string { for i := len(p.cref) - 1; i >= 0; i-- { diff --git a/internal/gentypes/parse.go b/internal/gentypes/parse.go index 243d7ab..652046b 100644 --- a/internal/gentypes/parse.go +++ b/internal/gentypes/parse.go @@ -852,6 +852,9 @@ func (p *parser) assigns() bool { return p.at(1).kind == tOp && p.at(1).text == // inert consumes a statement that cannot change generated output; t is set in a type body, a in an attribute body. func (p *parser) inert(t *rtype, a *attr) (bool, error) { c := p.cur() + if p.blockGivenGuard() { + return true, nil + } switch { case isLocal(c) && p.assigns(): p.i += 2 @@ -921,6 +924,20 @@ func (p *parser) inert(t *rtype, a *attr) (bool, error) { return false, nil } +// blockGivenGuard consumes a statement with an if block_given? modifier: blocks a file's top level defines see no +// block, so it never runs. +func (p *parser) blockGivenGuard() bool { + start := p.i + if p.skipStatement() == nil && p.i-start >= 3 && p.toks[p.i-2].text == "if" && p.toks[p.i-1].kind == tIdent && p.toks[p.i-1].text == "block_given?" { + for j := start; j < p.i; j++ { + p.used[j] = true + } + return true + } + p.i = start + return false +} + // feature records Puppet::Util::ProviderFeatures#feature, which raises on a repeated symbol name or any option but methods. func (p *parser) feature(t *rtype) error { p.take() diff --git a/internal/gentypes/testdata/env/external_modules/augeasproviders_shellvar/LICENSE b/internal/gentypes/testdata/env/external_modules/augeasproviders_shellvar/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/augeasproviders_shellvar/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/gentypes/testdata/env/external_modules/augeasproviders_shellvar/lib/puppet/provider/shellvar/augeas.rb b/internal/gentypes/testdata/env/external_modules/augeasproviders_shellvar/lib/puppet/provider/shellvar/augeas.rb new file mode 100644 index 0000000..520281f --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/augeasproviders_shellvar/lib/puppet/provider/shellvar/augeas.rb @@ -0,0 +1,306 @@ +# Alternative Augeas-based provider for shellvar type +# +# Copyright (c) 2012 Dominic Cleal +# Licensed under the Apache License, Version 2.0 + +raise('Missing augeasproviders_core dependency') if Puppet::Type.type(:augeasprovider).nil? +Puppet::Type.type(:shellvar).provide(:augeas, parent: Puppet::Type.type(:augeasprovider).provider(:default)) do + desc 'Uses Augeas API to update shell script variables' + + confine feature: :augeas + + lens { 'Shellvars.lns' } + + resource_path do |resource| + if resource.provider.unset_seq? + "$target/#{resource[:variable]}|$target/@unset/*[.='#{resource[:variable]}']" + else + "$target/#{resource[:variable]}|$target/@unset[.='#{resource[:variable]}']" + end + end + + def unset_seq? + return @unset_seq unless @unset_seq.nil? + @unset_seq = Puppet::Util::Package.versioncmp(aug_version, '1.2.0') >= 0 + @unset_seq ||= parsed_as?("unset FOO\n", '@unset/1') + end + + def unset_path + if unset_seq? + "$target/@unset/*[.='#{resource[:variable]}']" + else + "$target/@unset[.='#{resource[:variable]}']" + end + end + + def unset_ins_path + if unset_seq? + "$target/@unset[*='#{resource[:variable]}']" + else + "$target/@unset[.='#{resource[:variable]}']" + end + end + + def unset_empty + if unset_seq? + '$target/@unset[count(*)=0]/1' + else + "$target/@unset[.='']" + end + end + + def unset_purge(aug) + aug.rm('$target/@unset[count(*)=0]') if unset_seq? + end + + def array?(path = nil, aug = nil) + if aug.nil? || path.nil? + augopen do |a| + !a.match("$target/#{resource[:variable]}/1").empty? + end + else + !aug.match("$target/#{resource[:variable]}/1").empty? + end + end + + def exported? + augopen do |aug| + !aug.match("$target/#{resource[:variable]}/export").empty? + end + end + + def unset? + augopen do |aug| + if unset_seq? + !aug.match("$target/@unset/*[.='#{resource[:variable]}']").empty? + else + !aug.match("$target/@unset[.='#{resource[:variable]}']").empty? + end + end + end + + def export + augopen! do |aug| + unless aug.match(unset_ins_path).empty? + aug.insert(unset_ins_path, resource[:variable], false) + set_values('$target', aug, resource[:value]) + aug.rm(unset_path) + unset_purge(aug) + end + if array?("$target/#{resource[:variable]}", aug) + aug.insert("$target/#{resource[:variable]}/1", 'export', true) + else + aug.clear("$target/#{resource[:variable]}/export") + end + end + end + + def unset + augopen! do |aug| + aug.insert("$target/#{resource[:variable]}", '@unset', false) + aug.set(unset_empty, resource[:variable]) + aug.rm("$target/#{resource[:variable]}") + end + end + + def unexport + augopen! do |aug| + aug.rm("$target/#{resource[:variable]}/export") + # Values may have changed, too + set_values('$target', aug, resource[:value]) + end + end + + def ununset + augopen! do |aug| + aug.insert(unset_ins_path, resource[:variable], false) + set_values('$target', aug, resource[:value]) + aug.rm(unset_path) + unset_purge(aug) + end + end + + def array_type(path = nil, aug = nil) + if resource[:array_type] == :auto + if array?(path, aug) + :array + else + :string + end + else + resource[:array_type] + end + end + + def get_values(path, aug) + if array?(path, aug) + aug.match('$resource/*').map { |p| aug.get(p) } + else + value = aug.get('$resource') + if value =~ %r{^(["'])(.*)(\1)$}m + value = Regexp.last_match(2) + end + [value] + end + end + + def set_values(path, aug, values) + oldvalue = nil + + # Detect array type *before* removing subnodes + my_array_type = array_type(path, aug) + # Remove because we might convert an array to a string + # Only remove seq entries, not unless/export + aug.rm("#{path}/#{resource[:variable]}/*[label()=~regexp('^[0-9]+$')]") + case my_array_type + when :string + oldvalue = aug.get("#{path}/#{resource[:variable]}") + + # When dealing with array entries + # try hard to keep spacing by using Shellvars_list + aug.rm('/parsed') + aug.set('/input', "#{resource[:variable]}=#{oldvalue}\n") + if values.size > 1 \ + && aug.respond_to?(:text_store) \ + && aug.text_store('Shellvars_list.lns', '/input', '/parsed') + + # Replace all values + aug.rm("/parsed/#{resource[:variable]}/value") + # Set automatic quoting + aug.set("/parsed/#{resource[:variable]}/quote", whichquote(values.join(' '), oldvalue)) + values.each do |v| + aug.set("/parsed/#{resource[:variable]}/value[last()+1]", v) + end + + # Transform back into Shellvars format + aug.text_retrieve('Shellvars_list.lns', '/input', '/parsed', '/newvalue') + newvalue = aug.get('/newvalue').sub("#{resource[:variable]}=", '').chomp + aug.set("#{path}/#{resource[:variable]}", newvalue) + else + aug.set("#{path}/#{resource[:variable]}", quoteit(values.join(' '), oldvalue)) + end + when :array + values.each_with_index do |v, i| + aug.set("#{path}/#{resource[:variable]}/#{i}", quoteit(v)) + end + end + end + + def create + augopen! do |aug| + # Prefer to create the node next to a commented out entry + commented = aug.match("$target/#comment[.=~regexp('#{resource[:variable]}([^a-z.].*)?')]") + + commented_values = [] + unless commented.empty? + commented_values = if aug.get(commented.first).include?('=') + value = aug.get(commented.first).split('=')[1] + return nil if value.nil? + unquoteit(value).split(' ') + else + unquoteit(aug.get(commented.first)).split(' ') + end + end + comment_ins = '$resource' + + if resource[:ensure] == :unset + if unset_seq? + comment_ins = '$resource/..' + end + + unless commented.empty? + aug.insert(commented.first, '@unset', false) + aug.rm(commented.first) if resource[:uncomment] == :true + end + aug.set(unset_empty, resource[:variable]) + else + unless commented.empty? + aug.insert(commented.first, resource[:variable], false) + aug.rm(commented.first) if resource[:uncomment] == :true + end + values = if resource[:uncomment] == :true + if resource[:value].nil? + # value is not provided + commented_values + elsif resource[:array_append] + # value is provided and merge requested + commented_values | resource[:value] + else + # value is provided and replacement requested + resource[:value] + end + else + resource[:value] + end + set_values('$target', aug, values) + aug.clear("$target/#{resource[:variable]}/export") if resource[:ensure] == :exported + end + + setvars(aug) + if resource[:comment] + aug.insert(comment_ins, '#comment', true) + aug.set("$target/#comment[.='']", + "#{resource[:variable]}: #{resource[:comment]}") + end + end + end + + def after_comment_node(resource) + if resource[:ensure] == :unset + if unset_seq? + "@unset[*='#{resource[:variable]}']" + else + "@unset[.='#{resource[:variable]}']" + end + else + resource[:variable] + end + end + + def destroy + augopen! do |aug| + after_comment = after_comment_node(resource) + aug.rm("$target/#comment[following-sibling::*[1][self::#{after_comment}]][. =~ regexp('#{resource[:variable]}:.*')]") + aug.rm("$target/#{resource[:variable]}") + aug.rm(unset_path) + unset_purge(aug) + end + end + + def value + augopen do |aug| + get_values('$target', aug) + end + end + + def value=(value) + augopen! do |aug| + set_values('$target', aug, value) + end + end + + def comment + augopen do |aug| + after_comment = after_comment_node(resource) + comment = aug.get("$target/#comment[following-sibling::*[1][self::#{after_comment}]][. =~ regexp('#{resource[:variable]}:.*')]") + comment.sub!(%r{^#{resource[:variable]}:\s*}, '') if comment + comment || '' + end + end + + def comment=(value) + augopen! do |aug| + after_comment = after_comment_node(resource) + cmtnode = "$target/#comment[following-sibling::*[1][self::#{after_comment}]][. =~ regexp('#{resource[:variable]}:.*')]" + if value.empty? + aug.rm(cmtnode) + else + if aug.match(cmtnode).empty? + aug.insert("$target/#{resource[:variable]}", '#comment', true) + end + aug.set("$target/#comment[following-sibling::*[1][self::#{after_comment}]]", + "#{resource[:variable]}: #{resource[:comment]}") + end + end + end +end diff --git a/internal/gentypes/testdata/env/external_modules/augeasproviders_shellvar/lib/puppet/type/shellvar.rb b/internal/gentypes/testdata/env/external_modules/augeasproviders_shellvar/lib/puppet/type/shellvar.rb new file mode 100644 index 0000000..97378ae --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/augeasproviders_shellvar/lib/puppet/type/shellvar.rb @@ -0,0 +1,222 @@ +# Manages variables in simple shell scripts +# +# Copyright (c) 2012 Dominic Cleal +# Licensed under the Apache License, Version 2.0 + +Puppet::Type.newtype(:shellvar) do + @doc = 'Manages variables in simple shell scripts.' + + ensurable do + desc 'Create or remove the shellvar entry' + defaultvalues + block if block_given? + + newvalue(:unset) do + current = retrieve + if current == :absent + provider.create + elsif !provider.unset? + provider.unset + @resource.property(:value).sync if @resource.property(:value) + end + end + + newvalue(:exported) do + current = retrieve + if current == :absent + provider.create + elsif !provider.exported? + provider.export + @resource.property(:value).sync if @resource.property(:value) + end + end + + def insync?(is) + return true if should == :absent && provider.resource[:array_append] && provider.exists? + return true if should == :unset && is == :present && provider.unset? + return true if should == :exported && is == :present && provider.exported? + return false if should == :present && provider.unset? + return false if should == :present && provider.exported? + super + end + + def sync + if should == :present && provider.unset? + provider.ununset + elsif should == :present && provider.exported? + provider.unexport + elsif should == :absent && provider.resource[:array_append] + @resource.property(:value).sync + else + super + end + end + end + + newparam(:name) do + desc 'The default namevar' + isnamevar + end + + newparam(:variable) do + desc 'The name of the variable, e.g. OPTIONS' + isnamevar + end + + newproperty(:value, array_matching: :all) do + desc 'Value to change the variable to.' + + munge do |v| + v.to_s + end + + def insync?(is) + should_arr = Array(should) + + # Join and split to ensure all elements are parsed + is_str = is.is_a?(Array) ? is.join(' ') : is + is_arr = is_str.split(' ') + + if provider.resource[:array_append] && provider.resource[:ensure] == :absent + (is_arr - (is_arr - should_arr)).empty? + elsif provider.resource[:array_append] + (should_arr - is_arr).empty? + elsif should.size > 1 + should_arr == is_arr + else + should == is + end + end + + def sync + if provider.resource[:array_append] + is = @resource.property(:value).retrieve + + # Join and split to ensure all elements are parsed + is_str = is.is_a?(Array) ? is.join(' ') : is + is_arr = is_str.split(' ') + + provider.value = if provider.resource[:ensure] == :absent + # Remove "should" array from "is" array + is_arr - Array(should) + else + # Merge the two arrays + is_arr | Array(should) + end + else + # Use the should array + provider.value = should + end + end + end + + newparam(:quoted) do + desc "Quoting method to use, defaults to `auto`. + +* `auto` will quote only if necessary, leaving existing quotes as-is +* `double` and `single` will always quotes +* `none` will remove quotes, which may result in save failures" + + newvalues :auto, :double, :single, :none, :false, :true + + defaultto :auto + + munge do |v| + case v + when true, 'true', :true + :auto + when false, 'false', :false + :none + else + v.to_sym + end + end + end + + newparam(:array_type) do + desc "Type of array mapping to use, defaults to `auto`. + +* `auto` will detect the current type, and default to `string` +* `string` will render the array as a string and use space-separated values +* `array` will render the array as a shell array" + + newvalues :auto, :string, :array + + defaultto :auto + end + + newparam(:array_append) do + desc 'Whether to add to existing array values or replace all values.' + + newvalues :false, :true + + defaultto :false + + munge do |v| + case v + when true, 'true', :true + true + when false, 'false', :false + false + end + end + end + + newparam(:target) do + desc 'The file in which to store the variable.' + isnamevar + end + + newproperty(:comment) do + desc 'Text to be stored in a comment immediately above the entry. + It will be automatically prepended with the name of the variable in order + for the provider to know whether it controls the comment or not.' + end + + newparam(:uncomment) do + desc 'Whether to remove commented value when found.' + + newvalues :true, :false + + defaultto :false + + munge do |v| + case v + when true, 'true', :true + :true + when false, 'false', :false + :false + end + end + end + + def self.title_patterns + [ + [ + %r{^((\S+)\s+in\s+(\S+))$}, + [ + [:name], + [:variable], + [:target], + ], + ], + [ + %r{((\S+))}, + [ + [:name], + [:variable], + ], + ], + [ + %r{(.*)}, + [ + [:name], + ], + ], + ] + end + + autorequire(:file) do + self[:target] + end +end diff --git a/internal/gentypes/testdata/golden/shellvar.pp b/internal/gentypes/testdata/golden/shellvar.pp new file mode 100644 index 0000000..298e7f3 --- /dev/null +++ b/internal/gentypes/testdata/golden/shellvar.pp @@ -0,0 +1,73 @@ +# This file was automatically generated on 2026-11-08 22:33:56 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# Manages variables in simple shell scripts. +Puppet::Resource::ResourceType3.new( + 'shellvar', + [ + # Create or remove the shellvar entry + # + # Valid values are `present`, `absent`, `unset`, `exported`. + Puppet::Resource::Param(Enum['present', 'absent', 'unset', 'exported'], 'ensure'), + + # Value to change the variable to. + Puppet::Resource::Param(Any, 'value'), + + # Text to be stored in a comment immediately above the entry. + # It will be automatically prepended with the name of the variable in order + # for the provider to know whether it controls the comment or not. + Puppet::Resource::Param(Any, 'comment') + ], + [ + # The default namevar + Puppet::Resource::Param(Any, 'name', true), + + # The name of the variable, e.g. OPTIONS + Puppet::Resource::Param(Any, 'variable', true), + + # Quoting method to use, defaults to `auto`. + # + # * `auto` will quote only if necessary, leaving existing quotes as-is + # * `double` and `single` will always quotes + # * `none` will remove quotes, which may result in save failures + # + # Valid values are `auto`, `double`, `single`, `none`, `false`, `true`. + Puppet::Resource::Param(Variant[Boolean, Enum['auto', 'double', 'single', 'none', 'false', 'true']], 'quoted'), + + # Type of array mapping to use, defaults to `auto`. + # + # * `auto` will detect the current type, and default to `string` + # * `string` will render the array as a string and use space-separated values + # * `array` will render the array as a shell array + # + # Valid values are `auto`, `string`, `array`. + Puppet::Resource::Param(Enum['auto', 'string', 'array'], 'array_type'), + + # Whether to add to existing array values or replace all values. + # + # Valid values are `false`, `true`. + Puppet::Resource::Param(Variant[Boolean, Enum['false', 'true']], 'array_append'), + + # The file in which to store the variable. + Puppet::Resource::Param(Any, 'target', true), + + # Whether to remove commented value when found. + # + # Valid values are `true`, `false`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'uncomment'), + + # The specific backend to use for this `shellvar` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # augeas + # : Uses Augeas API to update shell script variables + Puppet::Resource::Param(Any, 'provider') + ], + { + /^((\S+)\s+in\s+(\S+))$/ => ['name', 'variable', 'target'], + /((\S+))/ => ['name', 'variable'], + /(.*)/ => ['name'] + }, + true, + false)