module Puppet::Parser::Functions
A module for managing parser functions. Each specified function is added to a central module that then gets included into the Scope class.
@api public
Copyright (C) 2009 Thomas Bellman
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THOMAS BELLMAN BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Thomas Bellman shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Thomas Bellman.
Constants
- Environment
Public Class Methods
Return the number of arguments a function expects.
@param [Symbol] name the function @param [Puppet::Node::Environment] environment The environment to find the function in @return [Integer] The arity of the function. See {newfunction} for
the meaning of negative values.
@api public
# File lib/puppet/parser/functions.rb 297 def self.arity(name, environment = Puppet.lookup(:current_environment)) 298 func = get_function(name, environment) 299 func ? func[:arity] : -1 300 end
Accessor for singleton autoloader
@api private
# File lib/puppet/parser/functions.rb 70 def self.autoloader 71 @autoloader ||= AutoloaderDelegate.new 72 end
Get the module that functions are mixed into corresponding to an environment
@api private
# File lib/puppet/parser/functions.rb 109 def self.environment_module(env) 110 @environment_module_lock.synchronize do 111 AnonymousModuleAdapter.adapt(env).module 112 end 113 end
Determine if a function is defined
@param [Symbol] name the function @param [Puppet::Node::Environment] environment the environment to find the function in
@return [Symbol, false] The name of the function if it's defined,
otherwise false.
@api public
# File lib/puppet/parser/functions.rb 242 def self.function(name, environment = Puppet.lookup(:current_environment)) 243 name = name.intern 244 245 func = get_function(name, environment) 246 unless func 247 autoloader.delegatee.load(name, environment) 248 func = get_function(name, environment) 249 end 250 251 if func 252 func[:name] 253 else 254 false 255 end 256 end
# File lib/puppet/parser/functions.rb 258 def self.functiondocs(environment = Puppet.lookup(:current_environment)) 259 autoloader.delegatee.loadall(environment) 260 261 ret = String.new 262 263 merged_functions(environment).sort { |a,b| a[0].to_s <=> b[0].to_s }.each do |name, hash| 264 ret << "#{name}\n#{"-" * name.to_s.length}\n" 265 if hash[:doc] 266 ret << Puppet::Util::Docs.scrub(hash[:doc]) 267 else 268 ret << "Undocumented.\n" 269 end 270 271 ret << "\n\n- *Type*: #{hash[:type]}\n\n" 272 end 273 274 ret 275 end
Create a new Puppet DSL function.
**The {newfunction} method provides a public API.**
This method is used both internally inside of Puppet to define parser functions. For example, template() is defined in {file:lib/puppet/parser/functions/template.rb template.rb} using the {newfunction} method. Third party Puppet modules such as [stdlib](forge.puppetlabs.com/puppetlabs/stdlib) use this method to extend the behavior and functionality of Puppet.
See also [Docs: Custom Functions](puppet.com/docs/puppet/5.5/lang_write_functions_in_puppet.html)
@example Define a new Puppet DSL Function
>> Puppet::Parser::Functions.newfunction(:double, :arity => 1,
:doc => "Doubles an object, typically a number or string.",
:type => :rvalue) {|i| i[0]*2 }
=> {:arity=>1, :type=>:rvalue,
:name=>"function_double",
:doc=>"Doubles an object, typically a number or string."}
@example Invoke the double function from irb as is done in RSpec examples:
>> require 'puppet_spec/scope'
>> scope = PuppetSpec::Scope.create_test_scope_for_node('example')
=> Scope()
>> scope.function_double([2])
=> 4
>> scope.function_double([4])
=> 8
>> scope.function_double([])
ArgumentError: double(): Wrong number of arguments given (0 for 1)
>> scope.function_double([4,8])
ArgumentError: double(): Wrong number of arguments given (2 for 1)
>> scope.function_double(["hello"])
=> "hellohello"
@param [Symbol] name the name of the function represented as a ruby Symbol.
The {newfunction} method will define a Ruby method based on this name on
the parser scope instance.
@param [Proc] block the block provided to the {newfunction} method will be
executed when the Puppet DSL function is evaluated during catalog compilation. The arguments to the function will be passed as an array to the first argument of the block. The return value of the block will be the return value of the Puppet DSL function for `:rvalue` functions.
@option options [:rvalue, :statement] :type (:statement) the type of function.
Either `:rvalue` for functions that return a value, or `:statement` for functions that do not return a value.
@option options [String] :doc ('') the documentation for the function.
This string will be extracted by documentation generation tools.
@option options [Integer] :arity (-1) the
[arity](https://en.wikipedia.org/wiki/Arity) of the function. When specified as a positive integer the function is expected to receive _exactly_ the specified number of arguments. When specified as a negative number, the function is expected to receive _at least_ the absolute value of the specified number of arguments incremented by one. For example, a function with an arity of `-4` is expected to receive at minimum 3 arguments. A function with the default arity of `-1` accepts zero or more arguments. A function with an arity of 2 must be provided with exactly two arguments, no more and no less. Added in Puppet 3.1.0.
@option options [Puppet::Node::Environment] :environment (nil) can
explicitly pass the environment we wanted the function added to. Only used to set logging functions in root environment
@return [Hash] describing the function.
@api public
# File lib/puppet/parser/functions.rb 187 def self.newfunction(name, options = {}, &block) 188 name = name.intern 189 environment = options[:environment] || Puppet.lookup(:current_environment) 190 191 Puppet.warning _("Overwriting previous definition for function %{name}") % { name: name } if get_function(name, environment) 192 193 arity = options[:arity] || -1 194 ftype = options[:type] || :statement 195 196 unless ftype == :statement or ftype == :rvalue 197 raise Puppet::DevError, _("Invalid statement type %{type}") % { type: ftype.inspect } 198 end 199 200 # the block must be installed as a method because it may use "return", 201 # which is not allowed from procs. 202 real_fname = "real_function_#{name}" 203 environment_module(environment).send(:define_method, real_fname, &block) 204 205 fname = "function_#{name}" 206 env_module = environment_module(environment) 207 208 env_module.send(:define_method, fname) do |*args| 209 Puppet::Util::Profiler.profile(_("Called %{name}") % { name: name }, [:functions, name]) do 210 if args[0].is_a? Array 211 if arity >= 0 and args[0].size != arity 212 raise ArgumentError, _("%{name}(): Wrong number of arguments given (%{arg_count} for %{arity})") % { name: name, arg_count: args[0].size, arity: arity } 213 elsif arity < 0 and args[0].size < (arity+1).abs 214 raise ArgumentError, _("%{name}(): Wrong number of arguments given (%{arg_count} for minimum %{min_arg_count})") % { name: name, arg_count: args[0].size, min_arg_count: (arity+1).abs } 215 end 216 r = Puppet::Pops::Evaluator::Runtime3FunctionArgumentConverter.convert_return(self.send(real_fname, args[0])) 217 # avoid leaking aribtrary value if not being an rvalue function 218 options[:type] == :rvalue ? r : nil 219 else 220 raise ArgumentError, _("custom functions must be called with a single array that contains the arguments. For example, function_example([1]) instead of function_example(1)") 221 end 222 end 223 end 224 225 func = {:arity => arity, :type => ftype, :name => fname} 226 func[:doc] = options[:doc] if options[:doc] 227 228 env_module.add_function_info(name, func) 229 230 func 231 end
Reset the list of loaded functions.
@api private
# File lib/puppet/parser/functions.rb 22 def self.reset 23 # Runs a newfunction to create a function for each of the log levels 24 root_env = Puppet.lookup(:root_environment) 25 AnonymousModuleAdapter.clear(root_env) 26 Puppet::Util::Log.levels.each do |level| 27 newfunction(level, 28 :environment => root_env, 29 :doc => "Log a message on the server at level #{level}.") do |vals| 30 send(level, vals.join(" ")) 31 end 32 end 33 end
Determine whether a given function returns a value.
@param [Symbol] name the function @param [Puppet::Node::Environment] environment The environment to find the function in @return [Boolean] whether it is an rvalue function
@api public
# File lib/puppet/parser/functions.rb 284 def self.rvalue?(name, environment = Puppet.lookup(:current_environment)) 285 func = get_function(name, environment) 286 func ? func[:type] == :rvalue : false 287 end
Private Class Methods
# File lib/puppet/parser/functions.rb 312 def get_function(name, environment) 313 environment_module(environment).get_function_info(name.intern) || environment_module(Puppet.lookup(:root_environment)).get_function_info(name.intern) 314 end
# File lib/puppet/parser/functions.rb 305 def merged_functions(environment) 306 root = environment_module(Puppet.lookup(:root_environment)) 307 env = environment_module(environment) 308 309 root.all_function_info.merge(env.all_function_info) 310 end