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 296 def self.arity(name, environment = Puppet.lookup(:current_environment)) 297 func = get_function(name, environment) 298 func ? func[:arity] : -1 299 end
Accessor for singleton autoloader
@api private
# File lib/puppet/parser/functions.rb 69 def self.autoloader 70 @autoloader ||= AutoloaderDelegate.new 71 end
Get the module that functions are mixed into corresponding to an environment
@api private
# File lib/puppet/parser/functions.rb 108 def self.environment_module(env) 109 @environment_module_lock.synchronize do 110 AnonymousModuleAdapter.adapt(env).module 111 end 112 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 241 def self.function(name, environment = Puppet.lookup(:current_environment)) 242 name = name.intern 243 244 func = get_function(name, environment) 245 unless func 246 autoloader.delegatee.load(name, environment) 247 func = get_function(name, environment) 248 end 249 250 if func 251 func[:name] 252 else 253 false 254 end 255 end
# File lib/puppet/parser/functions.rb 257 def self.functiondocs(environment = Puppet.lookup(:current_environment)) 258 autoloader.delegatee.loadall(environment) 259 260 ret = "" 261 262 merged_functions(environment).sort { |a,b| a[0].to_s <=> b[0].to_s }.each do |name, hash| 263 ret << "#{name}\n#{"-" * name.to_s.length}\n" 264 if hash[:doc] 265 ret << Puppet::Util::Docs.scrub(hash[:doc]) 266 else 267 ret << "Undocumented.\n" 268 end 269 270 ret << "\n\n- *Type*: #{hash[:type]}\n\n" 271 end 272 273 ret 274 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 186 def self.newfunction(name, options = {}, &block) 187 name = name.intern 188 environment = options[:environment] || Puppet.lookup(:current_environment) 189 190 Puppet.warning _("Overwriting previous definition for function %{name}") % { name: name } if get_function(name, environment) 191 192 arity = options[:arity] || -1 193 ftype = options[:type] || :statement 194 195 unless ftype == :statement or ftype == :rvalue 196 raise Puppet::DevError, _("Invalid statement type %{type}") % { type: ftype.inspect } 197 end 198 199 # the block must be installed as a method because it may use "return", 200 # which is not allowed from procs. 201 real_fname = "real_function_#{name}" 202 environment_module(environment).send(:define_method, real_fname, &block) 203 204 fname = "function_#{name}" 205 env_module = environment_module(environment) 206 207 env_module.send(:define_method, fname) do |*args| 208 Puppet::Util::Profiler.profile(_("Called %{name}") % { name: name }, [:functions, name]) do 209 if args[0].is_a? Array 210 if arity >= 0 and args[0].size != arity 211 raise ArgumentError, _("%{name}(): Wrong number of arguments given (%{arg_count} for %{arity})") % { name: name, arg_count: args[0].size, arity: arity } 212 elsif arity < 0 and args[0].size < (arity+1).abs 213 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 } 214 end 215 r = Puppet::Pops::Evaluator::Runtime3FunctionArgumentConverter.convert_return(self.send(real_fname, args[0])) 216 # avoid leaking aribtrary value if not being an rvalue function 217 options[:type] == :rvalue ? r : nil 218 else 219 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)") 220 end 221 end 222 end 223 224 func = {:arity => arity, :type => ftype, :name => fname} 225 func[:doc] = options[:doc] if options[:doc] 226 227 env_module.add_function_info(name, func) 228 229 func 230 end
Reset the list of loaded functions.
@api private
# File lib/puppet/parser/functions.rb 21 def self.reset 22 # Runs a newfunction to create a function for each of the log levels 23 root_env = Puppet.lookup(:root_environment) 24 AnonymousModuleAdapter.clear(root_env) 25 Puppet::Util::Log.levels.each do |level| 26 newfunction(level, 27 :environment => root_env, 28 :doc => "Log a message on the server at level #{level}.") do |vals| 29 send(level, vals.join(" ")) 30 end 31 end 32 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 283 def self.rvalue?(name, environment = Puppet.lookup(:current_environment)) 284 func = get_function(name, environment) 285 func ? func[:type] == :rvalue : false 286 end
Private Class Methods
# File lib/puppet/parser/functions.rb 311 def get_function(name, environment) 312 environment_module(environment).get_function_info(name.intern) || environment_module(Puppet.lookup(:root_environment)).get_function_info(name.intern) 313 end
# File lib/puppet/parser/functions.rb 304 def merged_functions(environment) 305 root = environment_module(Puppet.lookup(:root_environment)) 306 env = environment_module(environment) 307 308 root.all_function_info.merge(env.all_function_info) 309 end