repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/index.rb
lib/puppet/functions/index.rb
# frozen_string_literal: true # Returns the index (or key in a hash) to a first-found value in an `Iterable` value. # # When called with a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # the lambda is called repeatedly using each value in a data structure until the lambda returns a "truthy" value which # makes the function return the index or key, or if the end of the iteration is reached, undef is returned. # # This function can be called in two different ways; with a value to be searched for, or with # a lambda that determines if an entry in the iterable matches. # # When called with a lambda the function takes two mandatory arguments, in this order: # # 1. An array, hash, string, or other iterable object that the function will iterate over. # 2. A lambda, which the function calls for each element in the first argument. It can request one (value) or two (index/key, value) parameters. # # @example Using the `index` function # # `$data.index |$parameter| { <PUPPET CODE BLOCK> }` # # or # # `index($data) |$parameter| { <PUPPET CODE BLOCK> }` # # @example Using the `index` function with an Array and a one-parameter lambda # # ```puppet # $data = ["routers", "servers", "workstations"] # notice $data.index |$value| { $value == 'servers' } # notices 1 # notice $data.index |$value| { $value == 'hosts' } # notices undef # ``` # # @example Using the `index` function with a Hash and a one-parameter lambda # # ```puppet # $data = {types => ["routers", "servers", "workstations"], colors => ['red', 'blue', 'green']} # notice $data.index |$value| { 'servers' in $value } # notices 'types' # notice $data.index |$value| { 'red' in $value } # notices 'colors' # ``` # Note that the lambda gets the value and not an array with `[key, value]` as in other # iterative functions. # # Using a lambda that accepts two values works the same way. The lambda gets the index/key # as the first parameter and the value as the second parameter. # # @example Using the `index` function with an Array and a two-parameter lambda # # ```puppet # # Find the first even numbered index that has a non String value # $data = [key1, 1, 3, 5] # notice $data.index |$idx, $value| { $idx % 2 == 0 and $value !~ String } # notices 2 # ``` # # When called on a `String`, the lambda is given each character as a value. What is typically wanted is to # find a sequence of characters which is achieved by calling the function with a value to search for instead # of giving a lambda. # # # @example Using the `index` function with a String, search for first occurrence of a sequence of characters # # ```puppet # # Find first occurrence of 'ah' # $data = "blablahbleh" # notice $data.index('ah') # notices 5 # ``` # # @example Using the `index` function with a String, search for first occurrence of a regular expression # # ```puppet # # Find first occurrence of 'la' or 'le' # $data = "blablahbleh" # notice $data.index(/l(a|e)/ # notices 1 # ``` # # When searching in a `String` with a given value that is neither `String` nor `Regexp` the answer is always `undef`. # When searching in any other iterable, the value is matched against each value in the iteration using strict # Ruby `==` semantics. If Puppet Language semantics are wanted (where string compare is case insensitive) use a # lambda and the `==` operator in Puppet. # # @example Using the `index` function to search for a given value in an Array # # ```puppet # $data = ['routers', 'servers', 'WORKstations'] # notice $data.index('servers') # notices 1 # notice $data.index('workstations') # notices undef (not matching case) # ``` # # For an general examples that demonstrates iteration, see the Puppet # [iteration](https://puppet.com/docs/puppet/latest/lang_iteration.html) # documentation. # # @since 6.3.0 # Puppet::Functions.create_function(:index) do dispatch :index_Hash_2 do param 'Hash[Any, Any]', :hash block_param 'Callable[2,2]', :block end dispatch :index_Hash_1 do param 'Hash[Any, Any]', :hash block_param 'Callable[1,1]', :block end dispatch :index_Enumerable_2 do param 'Iterable', :enumerable block_param 'Callable[2,2]', :block end dispatch :index_Enumerable_1 do param 'Iterable', :enumerable block_param 'Callable[1,1]', :block end dispatch :string_index do param 'String', :str param 'Variant[String,Regexp]', :match end dispatch :index_value do param 'Iterable', :enumerable param 'Any', :match end def index_Hash_1(hash) hash.each_pair { |x, y| return x if yield(y) } nil end def index_Hash_2(hash) hash.each_pair.any? { |x, y| return x if yield(x, y) } nil end def index_Enumerable_1(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? enum.each { |entry| return entry[0] if yield(entry[1]) } else enum.each_with_index { |e, i| return i if yield(e) } end nil end def index_Enumerable_2(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? enum.each { |entry| return entry[0] if yield(*entry) } else enum.each_with_index { |e, i| return i if yield(i, e) } end nil end def string_index(str, match) str.index(match) end def index_value(enumerable, match) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? enum.each { |entry| return entry[0] if entry[1] == match } else enum.each_with_index { |e, i| return i if e == match } end nil end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/new.rb
lib/puppet/functions/new.rb
# frozen_string_literal: true # Creates a new instance/object of a given data type. # # This function makes it possible to create new instances of # concrete data types. If a block is given it is called with the # just created instance as an argument. # # Calling this function is equivalent to directly # calling the data type: # # @example `new` and calling type directly are equivalent # # ```puppet # $a = Integer.new("42") # $b = Integer("42") # ``` # # These would both convert the string `"42"` to the decimal value `42`. # # @example arguments by position or by name # # ```puppet # $a = Integer.new("42", 8) # $b = Integer({from => "42", radix => 8}) # ``` # # This would convert the octal (radix 8) number `"42"` in string form # to the decimal value `34`. # # The new function supports two ways of giving the arguments: # # * by name (using a hash with property to value mapping) # * by position (as regular arguments) # # Note that it is not possible to create new instances of # some abstract data types (for example `Variant`). The data type `Optional[T]` is an # exception as it will create an instance of `T` or `undef` if the # value to convert is `undef`. # # The arguments that can be given is determined by the data type. # # > An assertion is always made that the produced value complies with the given type constraints. # # @example data type constraints are checked # # ```puppet # Integer[0].new("-100") # ``` # # Would fail with an assertion error (since value is less than 0). # # The following sections show the arguments and conversion rules # per data type built into the Puppet Type System. # # ### Conversion to `Optional[T]` and `NotUndef[T]` # # Conversion to these data types is the same as a conversion to the type argument `T`. # In the case of `Optional[T]` it is accepted that the argument to convert may be `undef`. # It is however not acceptable to give other arguments (than `undef`) that cannot be # converted to `T`. # # ### Conversion to Integer # # A new `Integer` can be created from `Integer`, `Float`, `Boolean`, and `String` values. # For conversion from `String` it is possible to specify the radix (base). # # ```puppet # type Radix = Variant[Default, Integer[2,2], Integer[8,8], Integer[10,10], Integer[16,16]] # # function Integer.new( # String $value, # Radix $radix = 10, # Boolean $abs = false # ) # # function Integer.new( # Variant[Numeric, Boolean] $value, # Boolean $abs = false # ) # ``` # # * When converting from `String` the default radix is 10. # * If radix is not specified an attempt is made to detect the radix from the start of the string: # * `0b` or `0B` is taken as radix 2. # * `0x` or `0X` is taken as radix 16. # * `0` as radix 8. # * All others are decimal. # * Conversion from `String` accepts an optional sign in the string. # * For hexadecimal (radix 16) conversion an optional leading `"0x"`, or `"0X"` is accepted. # * For octal (radix 8) an optional leading `"0"` is accepted. # * For binary (radix 2) an optional leading `"0b"` or `"0B"` is accepted. # * When `radix` is set to `default`, the conversion is based on the leading. # characters in the string. A leading `"0"` for radix 8, a leading `"0x"`, or `"0X"` for # radix 16, and leading `"0b"` or `"0B"` for binary. # * Conversion from `Boolean` results in `0` for `false` and `1` for `true`. # * Conversion from `Integer`, `Float`, and `Boolean` ignores the radix. # * `Float` value fractions are truncated (no rounding). # * When `abs` is set to `true`, the result will be an absolute integer. # # @example Converting to Integer in multiple ways # # ```puppet # $a_number = Integer("0xFF", 16) # results in 255 # $a_number = Integer("010") # results in 8 # $a_number = Integer("010", 10) # results in 10 # $a_number = Integer(true) # results in 1 # $a_number = Integer(-38, 10, true) # results in 38 # ``` # # ### Conversion to Float # # A new `Float` can be created from `Integer`, `Float`, `Boolean`, and `String` values. # For conversion from `String` both float and integer formats are supported. # # ```puppet # function Float.new( # Variant[Numeric, Boolean, String] $value, # Boolean $abs = true # ) # ``` # # * For an integer, the floating point fraction of `.0` is added to the value. # * A `Boolean` `true` is converted to `1.0`, and a `false` to `0.0`. # * In `String` format, integer prefixes for hex and binary are understood (but not octal since # floating point in string format may start with a `'0'`). # * When `abs` is set to `true`, the result will be an absolute floating point value. # # ### Conversion to Numeric # # A new `Integer` or `Float` can be created from `Integer`, `Float`, `Boolean` and # `String` values. # # ```puppet # function Numeric.new( # Variant[Numeric, Boolean, String] $value, # Boolean $abs = true # ) # ``` # # * If the value has a decimal period, or if given in scientific notation # (e/E), the result is a `Float`, otherwise the value is an `Integer`. The # conversion from `String` always uses a radix based on the prefix of the string. # * Conversion from `Boolean` results in `0` for `false` and `1` for `true`. # * When `abs` is set to `true`, the result will be an absolute `Float`or `Integer` value. # # @example Converting to Numeric in different ways # # ```puppet # $a_number = Numeric(true) # results in 1 # $a_number = Numeric("0xFF") # results in 255 # $a_number = Numeric("010") # results in 8 # $a_number = Numeric("3.14") # results in 3.14 (a float) # $a_number = Numeric(-42.3, true) # results in 42.3 # $a_number = Numeric(-42, true) # results in 42 # ``` # # ### Conversion to Timespan # # A new `Timespan` can be created from `Integer`, `Float`, `String`, and `Hash` values. Several variants of the constructor are provided. # # **Timespan from seconds** # # When a Float is used, the decimal part represents fractions of a second. # # ```puppet # function Timespan.new( # Variant[Float, Integer] $value # ) # ``` # # **Timespan from days, hours, minutes, seconds, and fractions of a second** # # The arguments can be passed separately in which case the first four, days, hours, minutes, and seconds are mandatory and the rest are optional. # All values may overflow and/or be negative. The internal 128-bit nano-second integer is calculated as: # # ``` # (((((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000 + milliseconds) * 1000 + microseconds) * 1000 + nanoseconds # ``` # # ```puppet # function Timespan.new( # Integer $days, Integer $hours, Integer $minutes, Integer $seconds, # Integer $milliseconds = 0, Integer $microseconds = 0, Integer $nanoseconds = 0 # ) # ``` # # or, all arguments can be passed as a `Hash`, in which case all entries are optional: # # ```puppet # function Timespan.new( # Struct[{ # Optional[negative] => Boolean, # Optional[days] => Integer, # Optional[hours] => Integer, # Optional[minutes] => Integer, # Optional[seconds] => Integer, # Optional[milliseconds] => Integer, # Optional[microseconds] => Integer, # Optional[nanoseconds] => Integer # }] $hash # ) # ``` # # **Timespan from String and format directive patterns** # # The first argument is parsed using the format optionally passed as a string or array of strings. When an array is used, an attempt # will be made to parse the string using the first entry and then with each entry in succession until parsing succeeds. If the second # argument is omitted, an array of default formats will be used. # # An exception is raised when no format was able to parse the given string. # # ```puppet # function Timespan.new( # String $string, Variant[String[2],Array[String[2], 1]] $format = <default format>) # ) # ``` # # the arguments may also be passed as a `Hash`: # # ```puppet # function Timespan.new( # Struct[{ # string => String[1], # Optional[format] => Variant[String[2],Array[String[2], 1]] # }] $hash # ) # ``` # # The directive consists of a percent (`%`) character, zero or more flags, optional minimum field width and # a conversion specifier as follows: # ``` # %[Flags][Width]Conversion # ``` # # ##### Flags: # # | Flag | Meaning # | ---- | --------------- # | - | Don't pad numerical output # | _ | Use spaces for padding # | 0 | Use zeros for padding # # ##### Format directives: # # | Format | Meaning | # | ------ | ------- | # | D | Number of Days | # | H | Hour of the day, 24-hour clock | # | M | Minute of the hour (00..59) | # | S | Second of the minute (00..59) | # | L | Millisecond of the second (000..999) | # | N | Fractional seconds digits | # # The format directive that represents the highest magnitude in the format will be allowed to # overflow. I.e. if no "%D" is used but a "%H" is present, then the hours may be more than 23. # # The default array contains the following patterns: # # ``` # ['%D-%H:%M:%S', '%D-%H:%M', '%H:%M:%S', '%H:%M'] # ``` # # Examples - Converting to Timespan # # ```puppet # $duration = Timespan(13.5) # 13 seconds and 500 milliseconds # $duration = Timespan({days=>4}) # 4 days # $duration = Timespan(4, 0, 0, 2) # 4 days and 2 seconds # $duration = Timespan('13:20') # 13 hours and 20 minutes (using default pattern) # $duration = Timespan('10:03.5', '%M:%S.%L') # 10 minutes, 3 seconds, and 5 milli-seconds # $duration = Timespan('10:03.5', '%M:%S.%N') # 10 minutes, 3 seconds, and 5 nano-seconds # ``` # # ### Conversion to Timestamp # # A new `Timestamp` can be created from `Integer`, `Float`, `String`, and `Hash` values. Several variants of the constructor are provided. # # **Timestamp from seconds since epoch (1970-01-01 00:00:00 UTC)** # # When a Float is used, the decimal part represents fractions of a second. # # ```puppet # function Timestamp.new( # Variant[Float, Integer] $value # ) # ``` # # **Timestamp from String and patterns consisting of format directives** # # The first argument is parsed using the format optionally passed as a string or array of strings. When an array is used, an attempt # will be made to parse the string using the first entry and then with each entry in succession until parsing succeeds. If the second # argument is omitted, an array of default formats will be used. # # A third optional timezone argument can be provided. The first argument will then be parsed as if it represents a local time in that # timezone. The timezone can be any timezone that is recognized when using the `'%z'` or `'%Z'` formats, or the word `'current'`, in which # case the current timezone of the evaluating process will be used. The timezone argument is case insensitive. # # The default timezone, when no argument is provided, or when using the keyword `default`, is 'UTC'. # # It is illegal to provide a timezone argument other than `default` in combination with a format that contains '%z' or '%Z' since that # would introduce an ambiguity as to which timezone to use. The one extracted from the string, or the one provided as an argument. # # An exception is raised when no format was able to parse the given string. # # ```puppet # function Timestamp.new( # String $string, # Variant[String[2],Array[String[2], 1]] $format = <default format>, # String $timezone = default) # ) # ``` # # the arguments may also be passed as a `Hash`: # # ```puppet # function Timestamp.new( # Struct[{ # string => String[1], # Optional[format] => Variant[String[2],Array[String[2], 1]], # Optional[timezone] => String[1] # }] $hash # ) # ``` # # The directive consists of a percent (%) character, zero or more flags, optional minimum field width and # a conversion specifier as follows: # ``` # %[Flags][Width]Conversion # ``` # # ##### Flags: # # | Flag | Meaning # | ---- | --------------- # | - | Don't pad numerical output # | _ | Use spaces for padding # | 0 | Use zeros for padding # | # | Change names to upper-case or change case of am/pm # | ^ | Use uppercase # | : | Use colons for `%z` # # ##### Format directives (names and padding can be altered using flags): # # **Date (Year, Month, Day):** # # | Format | Meaning | # | ------ | ------- | # | Y | Year with century, zero-padded to at least 4 digits | # | C | year / 100 (rounded down such as `20` in `2009`) | # | y | year % 100 (`00..99`) | # | m | Month of the year, zero-padded (`01..12`) | # | B | The full month name (`"January"`) | # | b | The abbreviated month name (`"Jan"`) | # | h | Equivalent to `%b` | # | d | Day of the month, zero-padded (`01..31`) | # | e | Day of the month, blank-padded (`1..31`) | # | j | Day of the year (`001..366`) | # # **Time (Hour, Minute, Second, Subsecond):** # # | Format | Meaning | # | ------ | ------- | # | H | Hour of the day, 24-hour clock, zero-padded (`00..23`) | # | k | Hour of the day, 24-hour clock, blank-padded (`0..23`) | # | I | Hour of the day, 12-hour clock, zero-padded (`01..12`) | # | l | Hour of the day, 12-hour clock, blank-padded (`1..12`) | # | P | Meridian indicator, lowercase (`"am"` or `"pm"`) | # | p | Meridian indicator, uppercase (`"AM"` or `"PM"`) | # | M | Minute of the hour (`00..59`) | # | S | Second of the minute (`00..60`) | # | L | Millisecond of the second (`000..999`). Digits under millisecond are truncated to not produce 1000 | # | N | Fractional seconds digits, default is 9 digits (nanosecond). Digits under a specified width are truncated to avoid carry up | # # **Time (Hour, Minute, Second, Subsecond):** # # | Format | Meaning | # | ------ | ------- | # | z | Time zone as hour and minute offset from UTC (e.g. `+0900`) | # | :z | hour and minute offset from UTC with a colon (e.g. `+09:00`) | # | ::z | hour, minute and second offset from UTC (e.g. `+09:00:00`) | # | Z | Abbreviated time zone name or similar information. (OS dependent) | # # **Weekday:** # # | Format | Meaning | # | ------ | ------- | # | A | The full weekday name (`"Sunday"`) | # | a | The abbreviated name (`"Sun"`) | # | u | Day of the week (Monday is `1`, `1..7`) | # | w | Day of the week (Sunday is `0`, `0..6`) | # # **ISO 8601 week-based year and week number:** # # The first week of YYYY starts with a Monday and includes YYYY-01-04. # The days in the year before the first week are in the last week of # the previous year. # # | Format | Meaning | # | ------ | ------- | # | G | The week-based year | # | g | The last 2 digits of the week-based year (`00..99`) | # | V | Week number of the week-based year (`01..53`) | # # **Week number:** # # The first week of YYYY that starts with a Sunday or Monday (according to %U # or %W). The days in the year before the first week are in week 0. # # | Format | Meaning | # | ------ | ------- | # | U | Week number of the year. The week starts with Sunday. (`00..53`) | # | W | Week number of the year. The week starts with Monday. (`00..53`) | # # **Seconds since the Epoch:** # # | Format | Meaning | # | s | Number of seconds since 1970-01-01 00:00:00 UTC. | # # **Literal string:** # # | Format | Meaning | # | ------ | ------- | # | n | Newline character (`\n`) | # | t | Tab character (`\t`) | # | % | Literal `%` character | # # **Combination:** # # | Format | Meaning | # | ------ | ------- | # | c | date and time (`%a %b %e %T %Y`) | # | D | Date (`%m/%d/%y`) | # | F | The ISO 8601 date format (`%Y-%m-%d`) | # | v | VMS date (`%e-%^b-%4Y`) | # | x | Same as `%D` | # | X | Same as `%T` | # | r | 12-hour time (`%I:%M:%S %p`) | # | R | 24-hour time (`%H:%M`) | # | T | 24-hour time (`%H:%M:%S`) | # # The default array contains the following patterns: # # When a timezone argument (other than `default`) is explicitly provided: # # ``` # ['%FT%T.L', '%FT%T', '%F'] # ``` # # otherwise: # # ``` # ['%FT%T.%L %Z', '%FT%T %Z', '%F %Z', '%FT%T.L', '%FT%T', '%F'] # ``` # # Examples - Converting to Timestamp # # ```puppet # $ts = Timestamp(1473150899) # 2016-09-06 08:34:59 UTC # $ts = Timestamp({string=>'2015', format=>'%Y'}) # 2015-01-01 00:00:00.000 UTC # $ts = Timestamp('Wed Aug 24 12:13:14 2016', '%c') # 2016-08-24 12:13:14 UTC # $ts = Timestamp('Wed Aug 24 12:13:14 2016 PDT', '%c %Z') # 2016-08-24 19:13:14.000 UTC # $ts = Timestamp('2016-08-24 12:13:14', '%F %T', 'PST') # 2016-08-24 20:13:14.000 UTC # $ts = Timestamp('2016-08-24T12:13:14', default, 'PST') # 2016-08-24 20:13:14.000 UTC # # ``` # # ### Conversion to Type # # A new `Type` can be created from its `String` representation. # # @example Creating a type from a string # # ```puppet # $t = Type.new('Integer[10]') # ``` # # ### Conversion to String # # Conversion to `String` is the most comprehensive conversion as there are many # use cases where a string representation is wanted. The defaults for the many options # have been chosen with care to be the most basic "value in textual form" representation. # The more advanced forms of formatting are intended to enable writing special purposes formatting # functions in the Puppet language. # # A new string can be created from all other data types. The process is performed in # several steps - first the data type of the given value is inferred, then the resulting data type # is used to find the most significant format specified for that data type. And finally, # the found format is used to convert the given value. # # The mapping from data type to format is referred to as the *format map*. This map # allows different formatting depending on type. # # @example Positive Integers in Hexadecimal prefixed with `'0x'`, negative in Decimal # # ```puppet # $format_map = { # Integer[default, 0] => "%d", # Integer[1, default] => "%#x" # } # String("-1", $format_map) # produces '-1' # String("10", $format_map) # produces '0xa' # ``` # # A format is specified on the form: # # ``` # %[Flags][Width][.Precision]Format # ``` # # `Width` is the number of characters into which the value should be fitted. This allocated space is # padded if value is shorter. By default it is space padded, and the flag `0` will cause padding with `0` # for numerical formats. # # `Precision` is the number of fractional digits to show for floating point, and the maximum characters # included in a string format. # # Note that all data type supports the formats `s` and `p` with the meaning "default string representation" and # "default programmatic string representation" (which for example means that a String is quoted in 'p' format). # # **Signatures of String conversion** # # ```puppet # type Format = Pattern[/^%([\s\+\-#0\[\{<\(\|]*)([1-9][0-9]*)?(?:\.([0-9]+))?([a-zA-Z])/] # type ContainerFormat = Struct[{ # format => Optional[String], # separator => Optional[String], # separator2 => Optional[String], # string_formats => Hash[Type, Format] # }] # type TypeMap = Hash[Type, Variant[Format, ContainerFormat]] # type Formats = Variant[Default, String[1], TypeMap] # # function String.new( # Any $value, # Formats $string_formats # ) # ``` # # Where: # # * `separator` is the string used to separate entries in an array, or hash (extra space should not be included at # the end), defaults to `","` # * `separator2` is the separator between key and value in a hash entry (space padding should be included as # wanted), defaults to `" => "`. # * `string_formats` is a data type to format map for values contained in arrays and hashes - defaults to `{Any => "%p"}`. Note that # these nested formats are not applicable to data types that are containers; they are always formatted as per the top level # format specification. # # @example Simple Conversion to String (using defaults) # # ```puppet # $str = String(10) # produces '10' # $str = String([10]) # produces '["10"]' # ``` # # @example Simple Conversion to String specifying the format for the given value directly # # ```puppet # $str = String(10, "%#x") # produces '0xa' # $str = String([10], "%(a") # produces '("10")' # ``` # # @example Specifying type for values contained in an array # # ```puppet # $formats = { # Array => { # format => '%(a', # string_formats => { Integer => '%#x' } # } # } # $str = String([1,2,3], $formats) # produces '(0x1, 0x2, 0x3)' # ``` # # The given formats are merged with the default formats, and matching of values to convert against format is based on # the specificity of the mapped type; for example, different formats can be used for short and long arrays. # # **Integer to String** # # | Format | Integer Formats # | ------ | --------------- # | d | Decimal, negative values produces leading `-`. # | x X | Hexadecimal in lower or upper case. Uses `..f/..F` for negative values unless `+` is also used. A `#` adds prefix `0x/0X`. # | o | Octal. Uses `..0` for negative values unless `+` is also used. A `#` adds prefix `0`. # | b B | Binary with prefix `b` or `B`. Uses `..1/..1` for negative values unless `+` is also used. # | c | Numeric value representing a Unicode value, result is a one unicode character string, quoted if alternative flag `#` is used # | s | Same as `d`, or `d` in quotes if alternative flag `#` is used. # | p | Same as `d`. # | eEfgGaA | Converts integer to float and formats using the floating point rules. # # Defaults to `d`. # # **Float to String** # # | Format | Float formats # | ------ | ------------- # | f | Floating point in non exponential notation. # | e E | Exponential notation with `e` or `E`. # | g G | Conditional exponential with `e` or `E` if exponent `< -4` or `>=` the precision. # | a A | Hexadecimal exponential form, using `x`/`X` as prefix and `p`/`P` before exponent. # | s | Converted to string using format `p`, then applying string formatting rule, alternate form `#`` quotes result. # | p | Same as `f` format with minimum significant number of fractional digits, prec has no effect. # | dxXobBc | Converts float to integer and formats using the integer rules. # # Defaults to `p`. # # **String to String** # # | Format | String # | ------ | ------ # | s | Unquoted string, verbatim output of control chars. # | p | Programmatic representation - strings are quoted, interior quotes and control chars are escaped. Selects single or double quotes based on content, or uses double quotes if alternative flag `#` is used. # | C | Each `::` name segment capitalized, quoted if alternative flag `#` is used. # | c | Capitalized string, quoted if alternative flag `#` is used. # | d | Downcased string, quoted if alternative flag `#` is used. # | u | Upcased string, quoted if alternative flag `#` is used. # | t | Trims leading and trailing whitespace from the string, quoted if alternative flag `#` is used. # # Defaults to `s` at top level and `p` inside array or hash. # # **Boolean to String** # # | Format | Boolean Formats # | ---- | ------------------- # | t T | String `'true'/'false'` or `'True'/'False'`, first char if alternate form is used (i.e. `'t'/'f'` or `'T'/'F'`). # | y Y | String `'yes'/'no'`, `'Yes'/'No'`, `'y'/'n'` or `'Y'/'N'` if alternative flag `#` is used. # | dxXobB | Numeric value `0/1` in accordance with the given format which must be valid integer format. # | eEfgGaA | Numeric value `0.0/1.0` in accordance with the given float format and flags. # | s | String `'true'` / `'false'`. # | p | String `'true'` / `'false'`. # # **Regexp to String** # # | Format | Regexp Formats # | ---- | -------------- # | s | No delimiters, quoted if alternative flag `#` is used. # | p | Delimiters `/ /`. # # **Undef to String** # # | Format | Undef formats # | ------ | ------------- # | s | Empty string, or quoted empty string if alternative flag `#` is used. # | p | String `'undef'`, or quoted `'"undef"'` if alternative flag `#` is used. # | n | String `'nil'`, or `'null'` if alternative flag `#` is used. # | dxXobB | String `'NaN'`. # | eEfgGaA | String `'NaN'`. # | v | String `'n/a'`. # | V | String `'N/A'`. # | u | String `'undef'`, or `'undefined'` if alternative `#` flag is used. # # **Default value to String** # # | Format | Default formats # | ------ | --------------- # | d D | String `'default'` or `'Default'`, alternative form `#` causes value to be quoted. # | s | Same as `d`. # | p | Same as `d`. # # **Binary value to String** # # | Format | Default formats # | ------ | --------------- # | s | binary as unquoted UTF-8 characters (errors if byte sequence is invalid UTF-8). Alternate form escapes non ascii bytes. # | p | `'Binary("<base64strict>")'` # | b | `'<base64>'` - base64 string with newlines inserted # | B | `'<base64strict>'` - base64 strict string (without newlines inserted) # | u | `'<base64urlsafe>'` - base64 urlsafe string # | t | `'Binary'` - outputs the name of the type only # | T | `'BINARY'` - output the name of the type in all caps only # # * The alternate form flag `#` will quote the binary or base64 text output. # * The format `%#s` allows invalid UTF-8 characters and outputs all non ascii bytes # as hex escaped characters on the form `\\xHH` where `H` is a hex digit. # * The width and precision values are applied to the text part only in `%p` format. # # **Array & Tuple to String** # # | Format | Array/Tuple Formats # | ------ | ------------- # | a | Formats with `[ ]` delimiters and `,`, alternate form `#` indents nested arrays/hashes. # | s | Same as `a`. # | p | Same as `a`. # # See "Flags" `<[({\|` for formatting of delimiters, and "Additional parameters for containers; Array and Hash" for # more information about options. # # The alternate form flag `#` will cause indentation of nested array or hash containers. If width is also set # it is taken as the maximum allowed length of a sequence of elements (not including delimiters). If this max length # is exceeded, each element will be indented. # # **Hash & Struct to String** # # | Format | Hash/Struct Formats # | ------ | ------------- # | h | Formats with `{ }` delimiters, `,` element separator and ` => ` inner element separator unless overridden by flags. # | s | Same as h. # | p | Same as h. # | a | Converts the hash to an array of `[k,v]` tuples and formats it using array rule(s). # # See "Flags" `<[({\|` for formatting of delimiters, and "Additional parameters for containers; Array and Hash" for # more information about options. # # The alternate form flag `#` will format each hash key/value entry indented on a separate line. # # **Type to String** # # | Format | Array/Tuple Formats # | ------ | ------------- # | s | The same as `p`, quoted if alternative flag `#` is used. # | p | Outputs the type in string form as specified by the Puppet Language. # # **Flags** # # | Flag | Effect # | ------ | ------ # | (space) | A space instead of `+` for numeric output (`-` is shown), for containers skips delimiters. # | # | Alternate format; prefix `0x/0x`, `0` (octal) and `0b/0B` for binary, Floats force decimal '.'. For g/G keep trailing `0`. # | + | Show sign `+/-` depending on value's sign, changes `x`, `X`, `o`, `b`, `B` format to not use 2's complement form. # | - | Left justify the value in the given width. # | 0 | Pad with `0` instead of space for widths larger than value. # | <[({\| | Defines an enclosing pair `<> [] () {} or \| \|` when used with a container type. # # ### Conversion to Boolean # # Accepts a single value as argument: # # * Float `0.0` is `false`, all other float values are `true` # * Integer `0` is `false`, all other integer values are `true` # * Strings # * `true` if 'true', 'yes', 'y' (case independent compare) # * `false` if 'false', 'no', 'n' (case independent compare) # * Boolean is already boolean and is simply returned # # ### Conversion to Array and Tuple # # When given a single value as argument: # # * A non empty `Hash` is converted to an array matching `Array[Tuple[Any,Any], 1]`. # * An empty `Hash` becomes an empty array. # * An `Array` is simply returned. # * An `Iterable[T]` is turned into an array of `T` instances. # * A `Binary` is converted to an `Array[Integer[0,255]]` of byte values # # When given a second Boolean argument: # # * if `true`, a value that is not already an array is returned as a one element array. # * if `false`, (the default), converts the first argument as shown above. # # @example Ensuring value is an array # # ```puppet # $arr = Array($value, true) # ``` # # Conversion to a `Tuple` works exactly as conversion to an `Array`, only that the constructed array is # asserted against the given tuple type. # # ### Conversion to Hash and Struct # # Accepts a single value as argument: # # * An empty `Array` becomes an empty `Hash` # * An `Array` matching `Array[Tuple[Any,Any], 1]` is converted to a hash where each tuple describes a key/value entry # * An `Array` with an even number of entries is interpreted as `[key1, val1, key2, val2, ...]` # * An `Iterable` is turned into an `Array` and then converted to hash as per the array rules # * A `Hash` is simply returned # # Alternatively, a tree can be constructed by giving two values; an array of tuples on the form `[path, value]` # (where the `path` is the path from the root of a tree, and `value` the value at that position in the tree), and # either the option `'tree'` (do not convert arrays to hashes except the top level), or # `'hash_tree'` (convert all arrays to hashes). # # The tree/hash_tree forms of Hash creation are suited for transforming the result of an iteration # using `tree_each` and subsequent filtering or mapping. # # @example Mapping a hash tree # # Mapping an arbitrary structure in a way that keeps the structure, but where some values are replaced # can be done by using the `tree_each` function, mapping, and then constructing a new Hash from the result: # # ```puppet # # A hash tree with 'water' at different locations # $h = { a => { b => { x => 'water'}}, b => { y => 'water'} } # # a helper function that turns water into wine # function make_wine($x) { if $x == 'water' { 'wine' } else { $x } } # # create a flattened tree with water turned into wine # $flat_tree = $h.tree_each.map |$entry| { [$entry[0], make_wine($entry[1])] } # # create a new Hash and log it # notice Hash($flat_tree, 'hash_tree') # ``` # # Would notice the hash `{a => {b => {x => wine}}, b => {y => wine}}` # # Conversion to a `Struct` works exactly as conversion to a `Hash`, only that the constructed hash is # asserted against the given struct type. # # ### Conversion to a Regexp # # A `String` can be converted into a `Regexp` # # **Example**: Converting a String into a Regexp # ```puppet # $s = '[a-z]+\.com' # $r = Regexp($s) # if('foo.com' =~ $r) { # ... # } # ``` # # ### Creating a SemVer # # A SemVer object represents a single [Semantic Version](http://semver.org/). # It can be created from a String, individual values for its parts, or a hash specifying the value per part. # See the specification at [semver.org](http://semver.org/) for the meaning of the SemVer's parts. # # The signatures are: # # ```puppet # type PositiveInteger = Integer[0,default] # type SemVerQualifier = Pattern[/\A(?<part>[0-9A-Za-z-]+)(?:\.\g<part>)*\Z/] # type SemVerString = String[1] # type SemVerHash =Struct[{ # major => PositiveInteger, # minor => PositiveInteger, # patch => PositiveInteger, # Optional[prerelease] => SemVerQualifier, # Optional[build] => SemVerQualifier # }] # # function SemVer.new(SemVerString $str) # # function SemVer.new( # PositiveInteger $major # PositiveInteger $minor # PositiveInteger $patch # Optional[SemVerQualifier] $prerelease = undef # Optional[SemVerQualifier] $build = undef # ) # # function SemVer.new(SemVerHash $hash_args) # ``` # # @example `SemVer` and `SemVerRange` usage # # ```puppet # # As a type, SemVer can describe disjunct ranges which versions can be # # matched against - here the type is constructed with two # # SemVerRange objects. # # # $t = SemVer[ # SemVerRange('>=1.0.0 <2.0.0'), # SemVerRange('>=3.0.0 <4.0.0') # ] # notice(SemVer('1.2.3') =~ $t) # true # notice(SemVer('2.3.4') =~ $t) # false # notice(SemVer('3.4.5') =~ $t) # true # ``` # # ### Creating a `SemVerRange` # # A `SemVerRange` object represents a range of `SemVer`. It can be created from # a `String`, or from two `SemVer` instances, where either end can be given as
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/hiera_include.rb
lib/puppet/functions/hiera_include.rb
# frozen_string_literal: true require 'hiera/puppet_function' # Assigns classes to a node using an # [array merge lookup](https://puppet.com/docs/hiera/latest/lookup_types.html#array-merge) # that retrieves the value for a user-specified key from Hiera's data. # # This function is deprecated in favor of the `lookup` function in combination with `include`. # While this function continues to work, it does **not** support: # * `lookup_options` stored in the data # * lookup across global, environment, and module layers # # @example Using `lookup` and `include` instead of of the deprecated `hiera_include` # # ```puppet # # In site.pp, outside of any node definitions and below any top-scope variables: # lookup('classes', Array[String], 'unique').include # ``` # # The `hiera_include` function requires: # # - A string key name to use for classes. # - A call to this function (i.e. `hiera_include('classes')`) in your environment's # `sites.pp` manifest, outside of any node definitions and below any top-scope variables # that Hiera uses in lookups. # - `classes` keys in the appropriate Hiera data sources, with an array for each # `classes` key and each value of the array containing the name of a class. # # The function takes up to three arguments, in this order: # # 1. A string key that Hiera searches for in the hierarchy. **Required**. # 2. An optional default value to return if Hiera doesn't find anything matching the key. # * If this argument isn't provided and this function results in a lookup failure, Puppet # fails with a compilation error. # 3. The optional name of an arbitrary # [hierarchy level](https://puppet.com/docs/hiera/latest/hierarchy.html) to insert at the # top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup. # * If Hiera doesn't find a matching key in the overriding hierarchy level, it continues # searching the rest of the hierarchy. # # The function uses an # [array merge lookup](https://puppet.com/docs/hiera/latest/lookup_types.html#array-merge) # to retrieve the `classes` array, so every node gets every class from the hierarchy. # # @example Using `hiera_include` # # ```yaml # # Assuming hiera.yaml # # :hierarchy: # # - web01.example.com # # - common # # # Assuming web01.example.com.yaml: # # classes: # # - apache::mod::php # # # Assuming common.yaml: # # classes: # # - apache # ``` # # ```puppet # # In site.pp, outside of any node definitions and below any top-scope variables: # hiera_include('classes', undef) # # # Puppet assigns the apache and apache::mod::php classes to the web01.example.com node. # ``` # # You can optionally generate the default value with a # [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) that # takes one parameter. # # @example Using `hiera_include` with a lambda # # ```puppet # # Assuming the same Hiera data as the previous example: # # # In site.pp, outside of any node definitions and below any top-scope variables: # hiera_include('classes') | $key | {"Key \'${key}\' not found" } # # # Puppet assigns the apache and apache::mod::php classes to the web01.example.com node. # # If hiera_include couldn't match its key, it would return the lambda result, # # "Key 'classes' not found". # ``` # # See # [the 'Using the lookup function' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) for how to perform lookup of data. # Also see # [the 'Using the deprecated hiera functions' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) # for more information about the Hiera 3 functions. # # @since 4.0.0 # Puppet::Functions.create_function(:hiera_include, Hiera::PuppetFunction) do init_dispatch def merge_type :unique end def post_lookup(scope, key, value) raise Puppet::ParseError, _("Could not find data item %{key}") % { key: key } if value.nil? call_function_with_scope(scope, 'include', value) unless value.empty? end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/keys.rb
lib/puppet/functions/keys.rb
# frozen_string_literal: true # Returns the keys of a hash as an Array # # @example Using `keys` # # ```puppet # $hsh = {"apples" => 3, "oranges" => 4 } # $hsh.keys() # keys($hsh) # # both results in the array ["apples", "oranges"] # ``` # # * Note that a hash in the puppet language accepts any data value (including `undef`) unless # it is constrained with a `Hash` data type that narrows the allowed data types. # * For an empty hash, an empty array is returned. # * The order of the keys is the same as the order in the hash (typically the order in which they were added). # Puppet::Functions.create_function(:keys) do dispatch :keys do param 'Hash', :hsh end def keys(hsh) hsh.keys end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/filter.rb
lib/puppet/functions/filter.rb
# frozen_string_literal: true # Applies a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # to every value in a data structure and returns an array or hash containing any elements # for which the lambda evaluates to a truthy value (not `false` or `undef`). # # This function takes two mandatory arguments, in this order: # # 1. An array, hash, or other iterable object that the function will iterate over. # 2. A lambda, which the function calls for each element in the first argument. It can # request one or two parameters. # # @example Using the `filter` function # # `$filtered_data = $data.filter |$parameter| { <PUPPET CODE BLOCK> }` # # or # # `$filtered_data = filter($data) |$parameter| { <PUPPET CODE BLOCK> }` # # When the first argument (`$data` in the above example) is an array, Puppet passes each # value in turn to the lambda and returns an array containing the results. # # @example Using the `filter` function with an array and a one-parameter lambda # # ```puppet # # For the array $data, return an array containing the values that end with "berry" # $data = ["orange", "blueberry", "raspberry"] # $filtered_data = $data.filter |$items| { $items =~ /berry$/ } # # $filtered_data = [blueberry, raspberry] # ``` # # When the first argument is a hash, Puppet passes each key and value pair to the lambda # as an array in the form `[key, value]` and returns a hash containing the results. # # @example Using the `filter` function with a hash and a one-parameter lambda # # ```puppet # # For the hash $data, return a hash containing all values of keys that end with "berry" # $data = { "orange" => 0, "blueberry" => 1, "raspberry" => 2 } # $filtered_data = $data.filter |$items| { $items[0] =~ /berry$/ } # # $filtered_data = {blueberry => 1, raspberry => 2} # ``` # # When the first argument is an array and the lambda has two parameters, Puppet passes the # array's indexes (enumerated from 0) in the first parameter and its values in the second # parameter. # # @example Using the `filter` function with an array and a two-parameter lambda # # ```puppet # # For the array $data, return an array of all keys that both end with "berry" and have # # an even-numbered index # $data = ["orange", "blueberry", "raspberry"] # $filtered_data = $data.filter |$indexes, $values| { $indexes % 2 == 0 and $values =~ /berry$/ } # # $filtered_data = [raspberry] # ``` # # When the first argument is a hash, Puppet passes its keys to the first parameter and its # values to the second parameter. # # @example Using the `filter` function with a hash and a two-parameter lambda # # ```puppet # # For the hash $data, return a hash of all keys that both end with "berry" and have # # values less than or equal to 1 # $data = { "orange" => 0, "blueberry" => 1, "raspberry" => 2 } # $filtered_data = $data.filter |$keys, $values| { $keys =~ /berry$/ and $values <= 1 } # # $filtered_data = {blueberry => 1} # ``` # # @since 4.0.0 # @since 6.0.0 does not filter if truthy value is returned from block # Puppet::Functions.create_function(:filter) do dispatch :filter_Hash_2 do param 'Hash[Any, Any]', :hash block_param 'Callable[2,2]', :block end dispatch :filter_Hash_1 do param 'Hash[Any, Any]', :hash block_param 'Callable[1,1]', :block end dispatch :filter_Enumerable_2 do param 'Iterable', :enumerable block_param 'Callable[2,2]', :block end dispatch :filter_Enumerable_1 do param 'Iterable', :enumerable block_param 'Callable[1,1]', :block end def filter_Hash_1(hash) result = hash.select { |x, y| yield([x, y]) } # Ruby 1.8.7 returns Array result = result.to_h unless result.is_a? Hash result end def filter_Hash_2(hash) result = hash.select { |x, y| yield(x, y) } # Ruby 1.8.7 returns Array result = result.to_h unless result.is_a? Hash result end def filter_Enumerable_1(enumerable) result = [] enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) begin enum.each do |value| result << value if yield(value) end rescue StopIteration end result end def filter_Enumerable_2(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? result = {} enum.each { |k, v| result[k] = v if yield(k, v) } else result = [] begin enum.each_with_index do |value, index| result << value if yield(index, value) end rescue StopIteration end end result end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/sort.rb
lib/puppet/functions/sort.rb
# frozen_string_literal: true # Sorts an Array numerically or lexicographically or the characters of a String lexicographically. # Please note: This function is based on Ruby String comparison and as such may not be entirely UTF8 compatible. # To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # # This function is compatible with the function `sort()` in `stdlib`. # * Comparison of characters in a string always uses a system locale and may not be what is expected for a particular locale # * Sorting is based on Ruby's `<=>` operator unless a lambda is given that performs the comparison. # * comparison of strings is case dependent (use lambda with `compare($a,$b)` to ignore case) # * comparison of mixed data types raises an error (if there is the need to sort mixed data types use a lambda) # # Also see the `compare()` function for information about comparable data types in general. # # @example Sorting a String # # ```puppet # notice(sort("xadb")) # notices 'abdx' # ``` # # @example Sorting an Array # # ```puppet # notice(sort([3,6,2])) # notices [2, 3, 6] # ``` # # @example Sorting with a lambda # # ```puppet # notice(sort([3,6,2]) |$a,$b| { compare($a, $b) }) # notices [2, 3, 6] # notice(sort([3,6,2]) |$a,$b| { compare($b, $a) }) # notices [6, 3, 2] # ``` # # @example Case independent sorting with a lambda # # ```puppet # notice(sort(['A','b','C'])) # notices ['A', 'C', 'b'] # notice(sort(['A','b','C']) |$a,$b| { compare($a, $b) }) # notices ['A', 'b', 'C'] # notice(sort(['A','b','C']) |$a,$b| { compare($a, $b, true) }) # notices ['A', 'b', 'C'] # notice(sort(['A','b','C']) |$a,$b| { compare($a, $b, false) }) # notices ['A','C', 'b'] # ``` # # @example Sorting Array with Numeric and String so that numbers are before strings # # ```puppet # notice(sort(['b', 3, 'a', 2]) |$a, $b| { # case [$a, $b] { # [String, Numeric] : { 1 } # [Numeric, String] : { -1 } # default: { compare($a, $b) } # } # }) # ``` # Would notice `[2,3,'a','b']` # # @since 6.0.0 - supporting a lambda to do compare # Puppet::Functions.create_function(:sort) do dispatch :sort_string do param 'String', :string_value optional_block_param 'Callable[2,2]', :block end dispatch :sort_array do param 'Array', :array_value optional_block_param 'Callable[2,2]', :block end def sort_string(s, &block) sort_array(s.split(''), &block).join('') end def sort_array(a, &block) a.sort(&block) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/chomp.rb
lib/puppet/functions/chomp.rb
# frozen_string_literal: true # Returns a new string with the record separator character(s) removed. # The record separator is the line ending characters `\r` and `\n`. # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String` the conversion removes `\r\n`, `\n` or `\r` from the end of a string. # * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is processed and the conversion is not recursive. # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # # @example Removing line endings # ```puppet # "hello\r\n".chomp() # chomp("hello\r\n") # ``` # Would both result in `"hello"` # # @example Removing line endings in an array # ```puppet # ["hello\r\n", "hi\r\n"].chomp() # chomp(["hello\r\n", "hi\r\n"]) # ``` # Would both result in `['hello', 'hi']` # Puppet::Functions.create_function(:chomp) do dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_iterable do param 'Iterable[Variant[String, Numeric]]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.chomp end def on_iterable(a) a.map { |x| do_chomp(x) } end def do_chomp(x) # x can only be a String or Numeric because type constraints have been automatically applied x.is_a?(String) ? x.chomp : x end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/length.rb
lib/puppet/functions/length.rb
# frozen_string_literal: true # Returns the length of an Array, Hash, String, or Binary value. # # The returned value is a positive integer indicating the number # of elements in the container; counting (possibly multibyte) characters for a `String`, # bytes in a `Binary`, number of elements in an `Array`, and number of # key-value associations in a Hash. # # @example Using `length` # # ```puppet # "roses".length() # 5 # length("violets") # 7 # [10, 20].length # 2 # {a => 1, b => 3}.length # 2 # ``` # # @since 5.5.0 - also supporting Binary # Puppet::Functions.create_function(:length) do dispatch :collection_length do param 'Collection', :arg end dispatch :string_length do param 'String', :arg end dispatch :binary_length do param 'Binary', :arg end def collection_length(col) col.size end def string_length(s) s.length end def binary_length(bin) bin.length end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/unique.rb
lib/puppet/functions/unique.rb
# frozen_string_literal: true # Produces a unique set of values from an `Iterable` argument. # # * If the argument is a `String`, the unique set of characters are returned as a new `String`. # * If the argument is a `Hash`, the resulting hash associates a set of keys with a set of unique values. # * For all other types of `Iterable` (`Array`, `Iterator`) the result is an `Array` with # a unique set of entries. # * Comparison of all `String` values are case sensitive. # * An optional code block can be given - if present it is given each candidate value and its return is used instead of the given value. This # enables transformation of the value before comparison. The result of the lambda is only used for comparison. # * The optional code block when used with a hash is given each value (not the keys). # # @example Using unique with a String # # ```puppet # # will produce 'abc' # "abcaabb".unique # ``` # # @example Using unique with an Array # # ```puppet # # will produce ['a', 'b', 'c'] # ['a', 'b', 'c', 'a', 'a', 'b'].unique # ``` # # @example Using unique with a Hash # # ```puppet # # will produce { ['a', 'b'] => [10], ['c'] => [20]} # {'a' => 10, 'b' => 10, 'c' => 20}.unique # # # will produce { 'a' => 10, 'c' => 20 } (use first key with first value) # Hash.new({'a' => 10, 'b' => 10, 'c' => 20}.unique.map |$k, $v| { [ $k[0] , $v[0]] }) # # # will produce { 'b' => 10, 'c' => 20 } (use last key with first value) # Hash.new({'a' => 10, 'b' => 10, 'c' => 20}.unique.map |$k, $v| { [ $k[-1] , $v[0]] }) # ``` # # @example Using unique with an Iterable # # ``` # # will produce [3, 2, 1] # [1,2,2,3,3].reverse_each.unique # ``` # # @example Using unique with a lambda # # ```puppet # # will produce [['sam', 'smith'], ['sue', 'smith']] # [['sam', 'smith'], ['sam', 'brown'], ['sue', 'smith']].unique |$x| { $x[0] } # # # will produce [['sam', 'smith'], ['sam', 'brown']] # [['sam', 'smith'], ['sam', 'brown'], ['sue', 'smith']].unique |$x| { $x[1] } # # # will produce ['aBc', 'bbb'] (using a lambda to make comparison using downcased (%d) strings) # ['aBc', 'AbC', 'bbb'].unique |$x| { String($x,'%d') } # # # will produce {[a] => [10], [b, c, d, e] => [11, 12, 100]} # {a => 10, b => 11, c => 12, d => 100, e => 11}.unique |$v| { if $v > 10 { big } else { $v } } # ``` # # Note that for `Hash` the result is slightly different than for the other data types. For those the result contains the # *first-found* unique value, but for `Hash` it contains associations from a set of keys to the set of values clustered by the # equality lambda (or the default value equality if no lambda was given). This makes the `unique` function more versatile for hashes # in general, while requiring that the simple computation of "hash's unique set of values" is performed as `$hsh.map |$k, $v| { $v }.unique`. # (Generally, it's meaningless to compute the unique set of hash keys because they are unique by definition. However, the # situation can change if the hash keys are processed with a different lambda for equality. For this unique computation, # first map the hash to an array of its keys.) # If the more advanced clustering is wanted for one of the other data types, simply transform it into a `Hash` as shown in the # following example. # # @example turning a string or array into a hash with index keys # # ```puppet # # Array ['a', 'b', 'c'] to Hash with index results in # # {0 => 'a', 1 => 'b', 2 => 'c'} # Hash(['a', 'b', 'c'].map |$i, $v| { [$i, $v]}) # # # String "abc" to Hash with index results in # # {0 => 'a', 1 => 'b', 2 => 'c'} # Hash(Array("abc").map |$i,$v| { [$i, $v]}) # "abc".to(Array).map |$i,$v| { [$i, $v]}.to(Hash) # ``` # # @since Puppet 5.0.0 # Puppet::Functions.create_function(:unique) do dispatch :unique_string do param 'String', :string optional_block_param 'Callable[String]', :block end dispatch :unique_hash do param 'Hash', :hash optional_block_param 'Callable[Any]', :block end dispatch :unique_array do param 'Array', :array optional_block_param 'Callable[Any]', :block end dispatch :unique_iterable do param 'Iterable', :iterable optional_block_param 'Callable[Any]', :block end def unique_string(string, &block) string.split('').uniq(&block).join('') end def unique_hash(hash, &block) block = ->(v) { v } unless block_given? result = Hash.new { |h, k| h[k] = { :keys => [], :values => [] } } hash.each_pair do |k, v| rc = result[block.call(v)] rc[:keys] << k rc[:values] << v end # reduce the set of possibly duplicated value entries inverted = {} result.each_pair { |_k, v| inverted[v[:keys]] = v[:values].uniq } inverted end def unique_array(array, &block) array.uniq(&block) end def unique_iterable(iterable, &block) Puppet::Pops::Types::Iterable.on(iterable).uniq(&block) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/getvar.rb
lib/puppet/functions/getvar.rb
# frozen_string_literal: true # Digs into a variable with dot notation to get a value from a structure. # # **To get the value from a variable** (that may or may not exist), call the function with # one or two arguments: # # * The **first** argument must be a string, and must start with a variable name without leading `$`, # for example `get('facts')`. The variable name can be followed # by a _dot notation navigation string_ to dig out a value in the array or hash value # of the variable. # * The **optional second** argument can be any type of value and it is used as the # _default value_ if the function would otherwise return `undef`. # * An **optional lambda** for error handling taking one `Error` argument. # # **Dot notation navigation string** - # The dot string consists of period `.` separated segments where each # segment is either the index into an array or the value of a hash key. # If a wanted key contains a period it must be quoted to avoid it being # taken as a segment separator. Quoting can be done with either # single quotes `'` or double quotes `"`. If a segment is # a decimal number it is converted to an Integer index. This conversion # can be prevented by quoting the value. # # @example Getting the value of a variable # ```puppet # getvar('facts') # results in the value of $facts # ``` # # @example Navigating into a variable # ```puppet # getvar('facts.os.family') # results in the value of $facts['os']['family'] # ``` # # @example Using a default value # ```puppet # $x = [1,2,[{'name' =>'waldo'}]] # getvar('x.2.1.name', 'not waldo') # # results in 'not waldo' # ``` # # For further examples and how to perform error handling, see the `get()` function # which this function delegates to after having resolved the variable value. # # @since 6.0.0 - the ability to dig into the variable's value with dot notation. # Puppet::Functions.create_function(:getvar, Puppet::Functions::InternalFunction) do dispatch :get_from_navigation do scope_param param 'Pattern[/\A(?:::)?(?:[a-z]\w*::)*[a-z_]\w*(?:\.|\Z)/]', :get_string optional_param 'Any', :default_value optional_block_param 'Callable[1,1]', :block end argument_mismatch :invalid_variable_error do param 'String', :get_string optional_param 'Any', :default_value optional_block_param 'Callable', :block end def invalid_variable_error(navigation, default_value = nil, &block) _("The given string does not start with a valid variable name") end # Gets a result from a navigation string starting with $var # def get_from_navigation(scope, navigation, default_value = nil, &block) # asserted to start with a valid variable name - dig out the variable matches = navigation.match(/^((::)?(\w+::)*\w+)(.*)\z/) navigation = matches[4] if navigation[0] == '.' navigation = navigation[1..] else unless navigation.empty? raise ArgumentError, _("First character after var name in get string must be a '.' - got %{char}") % { char: navigation[0] } end end get_from_var_name(scope, matches[1], navigation, default_value, &block) end # Gets a result from a $var name and a navigation string # def get_from_var_name(scope, var_string, navigation, default_value = nil, &block) catch(:undefined_variable) do return call_function_with_scope(scope, 'get', scope.lookupvar(var_string), navigation, default_value, &block) end default_value end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/max.rb
lib/puppet/functions/max.rb
# frozen_string_literal: true # Returns the highest value among a variable number of arguments. # Takes at least one argument. # # This function is (with one exception) compatible with the stdlib function # with the same name and performs deprecated type conversion before # comparison as follows: # # * If a value converted to String is an optionally '-' prefixed, # string of digits, one optional decimal point, followed by optional # decimal digits - then the comparison is performed on the values # converted to floating point. # * If a value is not considered convertible to float, it is converted # to a `String` and the comparison is a lexical compare where min is # the lexicographical later value. # * A lexicographical compare is performed in a system locale - international # characters may therefore not appear in what a user thinks is the correct order. # * The conversion rules apply to values in pairs - the rule must hold for both # values - a value may therefore be compared using different rules depending # on the "other value". # * The returned result found to be the "highest" is the original unconverted value. # # The above rules have been deprecated in Puppet 6.0.0 as they produce strange results when # given values of mixed data types. In general, either convert values to be # all `String` or all `Numeric` values before calling the function, or call the # function with a lambda that performs type conversion and comparison. This because one # simply cannot compare `Boolean` with `Regexp` and with any arbitrary `Array`, `Hash` or # `Object` and getting a meaningful result. # # The one change in the function's behavior is when the function is given a single # array argument. The stdlib implementation would return that array as the result where # it now instead returns the max value from that array. # # @example 'max of values - stdlib compatible' # # ```puppet # notice(max(1)) # would notice 1 # notice(max(1,2)) # would notice 2 # notice(max("1", 2)) # would notice 2 # notice(max("0777", 512)) # would notice "0777", since "0777" is not converted from octal form # notice(max(0777, 512)) # would notice 512, since 0777 is decimal 511 # notice(max('aa', 'ab')) # would notice 'ab' # notice(max(['a'], ['b'])) # would notice ['b'], since "['b']" is after "['a']" # ``` # # @example find 'max' value in an array - stdlib compatible # # ```puppet # $x = [1,2,3,4] # notice(max(*$x)) # would notice 4 # ``` # # @example find 'max' value in an array directly - since Puppet 6.0.0 # # ```puppet # $x = [1,2,3,4] # notice(max($x)) # would notice 4 # notice($x.max) # would notice 4 # ``` # This example shows that a single array argument is used as the set of values # as opposed to being a single returned value. # # When calling with a lambda, it must accept two variables and it must return # one of -1, 0, or 1 depending on if first argument is before/lower than, equal to, # or higher/after the second argument. # # @example 'max of values using a lambda - since Puppet 6.0.0' # # ```puppet # notice(max("2", "10", "100") |$a, $b| { compare($a, $b) }) # ``` # # Would notice "2" as higher since it is lexicographically higher/after the other values. Without the # lambda the stdlib compatible (deprecated) behavior would have been to return "100" since number conversion # kicks in. # Puppet::Functions.create_function(:max) do dispatch :on_numeric do repeated_param 'Numeric', :values end dispatch :on_string do repeated_param 'String', :values end dispatch :on_semver do repeated_param 'Semver', :values end dispatch :on_timespan do repeated_param 'Timespan', :values end dispatch :on_timestamp do repeated_param 'Timestamp', :values end dispatch :on_single_numeric_array do param 'Array[Numeric]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_string_array do param 'Array[String]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_semver_array do param 'Array[Semver]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_timespan_array do param 'Array[Timespan]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_timestamp_array do param 'Array[Timestamp]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_any_array do param 'Array', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_any_with_block do repeated_param 'Any', :values block_param 'Callable[2,2]', :block end dispatch :on_any do repeated_param 'Any', :values end # All are Numeric - ok now, will be ok later def on_numeric(*args) assert_arg_count(args) args.max end # All are String, may convert to numeric (which is deprecated) def on_string(*args) assert_arg_count(args) args.max do |a, b| if a.to_s =~ /\A^-?\d+([._eE]\d+)?\z/ && b.to_s =~ /\A-?\d+([._eE]\d+)?\z/ Puppet.warn_once('deprecations', 'max_function_numeric_coerce_string', _("The max() function's auto conversion of String to Numeric is deprecated - change to convert input before calling, or use lambda")) a.to_f <=> b.to_f else # case sensitive as in the stdlib function a <=> b end end end def on_semver(*args) assert_arg_count(args) args.max end def on_timespan(*args) assert_arg_count(args) args.max end def on_timestamp(*args) assert_arg_count(args) args.max end def on_any_with_block(*args, &block) args.max { |x, y| block.call(x, y) } end def on_single_numeric_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_numeric(*array) end end def on_single_string_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_string(*array) end end def on_single_semver_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_semver(*array) end end def on_single_timespan_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_timespan(*array) end end def on_single_timestamp_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_timestamp(*array) end end def on_single_any_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_any(*array) end end # Mix of data types - while only some compares are actually bad it will deprecate # the entire call # def on_any(*args) assert_arg_count(args) args.max do |a, b| as = a.to_s bs = b.to_s if as =~ /\A^-?\d+([._eE]\d+)?\z/ && bs =~ /\A-?\d+([._eE]\d+)?\z/ Puppet.warn_once('deprecations', 'max_function_numeric_coerce_string', _("The max() function's auto conversion of String to Numeric is deprecated - change to convert input before calling, or use lambda")) a.to_f <=> b.to_f else Puppet.warn_once('deprecations', 'max_function_string_coerce_any', _("The max() function's auto conversion of Any to String is deprecated - change to convert input before calling, or use lambda")) as <=> bs end end end def assert_arg_count(args) raise(ArgumentError, 'max(): Wrong number of arguments need at least one') if args.empty? end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/any.rb
lib/puppet/functions/any.rb
# frozen_string_literal: true # Runs a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # repeatedly using each value in a data structure until the lambda returns a "truthy" value which # makes the function return `true`, or if the end of the iteration is reached, false is returned. # # This function takes two mandatory arguments, in this order: # # 1. An array, hash, or other iterable object that the function will iterate over. # 2. A lambda, which the function calls for each element in the first argument. It can # request one or two parameters. # # @example Using the `any` function # # `$data.any |$parameter| { <PUPPET CODE BLOCK> }` # # or # # `any($data) |$parameter| { <PUPPET CODE BLOCK> }` # # @example Using the `any` function with an Array and a one-parameter lambda # # ```puppet # # For the array $data, run a lambda that checks if an unknown hash contains those keys # $data = ["routers", "servers", "workstations"] # $looked_up = lookup('somekey', Hash) # notice $data.any |$item| { $looked_up[$item] } # ``` # # Would notice `true` if the looked up hash had a value that is neither `false` nor `undef` for at least # one of the keys. That is, it is equivalent to the expression # `$looked_up[routers] || $looked_up[servers] || $looked_up[workstations]`. # # When the first argument is a `Hash`, Puppet passes each key and value pair to the lambda # as an array in the form `[key, value]`. # # @example Using the `any` function with a `Hash` and a one-parameter lambda # # ```puppet # # For the hash $data, run a lambda using each item as a key-value array. # $data = {"rtr" => "Router", "svr" => "Server", "wks" => "Workstation"} # $looked_up = lookup('somekey', Hash) # notice $data.any |$item| { $looked_up[$item[0]] } # ``` # # Would notice `true` if the looked up hash had a value for one of the wanted key that is # neither `false` nor `undef`. # # When the lambda accepts two arguments, the first argument gets the index in an array # or the key from a hash, and the second argument the value. # # # @example Using the `any` function with an array and a two-parameter lambda # # ```puppet # # Check if there is an even numbered index that has a non String value # $data = [key1, 1, 2, 2] # notice $data.any |$index, $value| { $index % 2 == 0 and $value !~ String } # ``` # # Would notice true as the index `2` is even and not a `String` # # For an general examples that demonstrates iteration, see the Puppet # [iteration](https://puppet.com/docs/puppet/latest/lang_iteration.html) # documentation. # # @since 5.2.0 # Puppet::Functions.create_function(:any) do dispatch :any_Hash_2 do param 'Hash[Any, Any]', :hash block_param 'Callable[2,2]', :block end dispatch :any_Hash_1 do param 'Hash[Any, Any]', :hash block_param 'Callable[1,1]', :block end dispatch :any_Enumerable_2 do param 'Iterable', :enumerable block_param 'Callable[2,2]', :block end dispatch :any_Enumerable_1 do param 'Iterable', :enumerable block_param 'Callable[1,1]', :block end def any_Hash_1(hash) hash.each_pair.any? { |x| yield(x) } end def any_Hash_2(hash) hash.each_pair.any? { |x, y| yield(x, y) } end def any_Enumerable_1(enumerable) Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable).any? { |e| yield(e) } end def any_Enumerable_2(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? enum.any? { |entry| yield(*entry) } else enum.each_with_index { |e, i| return true if yield(i, e) } false end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/chop.rb
lib/puppet/functions/chop.rb
# frozen_string_literal: true # Returns a new string with the last character removed. # If the string ends with `\r\n`, both characters are removed. Applying chop to an empty # string returns an empty string. If you wish to merely remove record # separators then you should use the `chomp` function. # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String` the conversion removes the last character, or if it ends with \r\n` it removes both. If String is empty # an empty string is returned. # * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is processed and the conversion is not recursive. # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # # @example Removing line endings # ```puppet # "hello\r\n".chop() # chop("hello\r\n") # ``` # Would both result in `"hello"` # # @example Removing last char # ```puppet # "hello".chop() # chop("hello") # ``` # Would both result in `"hell"` # # @example Removing last char in an array # ```puppet # ["hello\r\n", "hi\r\n"].chop() # chop(["hello\r\n", "hi\r\n"]) # ``` # Would both result in `['hello', 'hi']` # Puppet::Functions.create_function(:chop) do dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_iterable do param 'Iterable[Variant[String, Numeric]]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.chop end def on_iterable(a) a.map { |x| do_chop(x) } end def do_chop(x) # x can only be a String or Numeric because type constraints have been automatically applied x.is_a?(String) ? x.chop : x end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/warning.rb
lib/puppet/functions/warning.rb
# frozen_string_literal: true # Logs a message on the server at level `warning`. Puppet::Functions.create_function(:warning, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :warning do scope_param repeated_param 'Any', :values return_type 'Undef' end def warning(scope, *values) Puppet::Util::Log.log_func(scope, :warning, values) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/json_data.rb
lib/puppet/functions/json_data.rb
# frozen_string_literal: true # The `json_data` is a hiera 5 `data_hash` data provider function. # See [the configuration guide documentation](https://puppet.com/docs/puppet/latest/hiera_config_yaml_5.html#configuring-a-hierarchy-level-built-in-backends) for # how to use this function. # # @since 4.8.0 # Puppet::Functions.create_function(:json_data) do dispatch :json_data do param 'Struct[{path=>String[1]}]', :options param 'Puppet::LookupContext', :context end argument_mismatch :missing_path do param 'Hash', :options param 'Puppet::LookupContext', :context end def json_data(options, context) path = options['path'] context.cached_file_data(path) do |content| Puppet::Util::Json.load(content) rescue Puppet::Util::Json::ParseError => ex # Filename not included in message, so we add it here. raise Puppet::DataBinding::LookupError, "Unable to parse (%{path}): %{message}" % { path: path, message: ex.message } end end def missing_path(options, context) "one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml when using this data_hash function" end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/abs.rb
lib/puppet/functions/abs.rb
# frozen_string_literal: true # Returns the absolute value of a Numeric value, for example -34.56 becomes # 34.56. Takes a single `Integer` or `Float` value as an argument. # # *Deprecated behavior* # # For backwards compatibility reasons this function also works when given a # number in `String` format such that it first attempts to covert it to either a `Float` or # an `Integer` and then taking the absolute value of the result. Only strings representing # a number in decimal format is supported - an error is raised if # value is not decimal (using base 10). Leading 0 chars in the string # are ignored. A floating point value in string form can use some forms of # scientific notation but not all. # # Callers should convert strings to `Numeric` before calling # this function to have full control over the conversion. # # @example Converting to Numeric before calling # ```puppet # abs(Numeric($str_val)) # ``` # # It is worth noting that `Numeric` can convert to absolute value # directly as in the following examples: # # @example Absolute value and String to Numeric # ```puppet # Numeric($strval, true) # Converts to absolute Integer or Float # Integer($strval, 10, true) # Converts to absolute Integer using base 10 (decimal) # Integer($strval, 16, true) # Converts to absolute Integer using base 16 (hex) # Float($strval, true) # Converts to absolute Float # ``` # Puppet::Functions.create_function(:abs) do dispatch :on_numeric do param 'Numeric', :val end dispatch :on_string do param 'String', :val end def on_numeric(x) x.abs end def on_string(x) Puppet.warn_once('deprecations', 'abs_function_numeric_coerce_string', _("The abs() function's auto conversion of String to Numeric is deprecated - change to convert input before calling")) # These patterns for conversion are backwards compatible with the stdlib # version of this function. # case x when /^-?(?:\d+)(?:\.\d+){1}$/ x.to_f.abs when /^-?\d+$/ x.to_i.abs else raise(ArgumentError, 'abs(): Requires float or integer to work with - was given non decimal string') end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/crit.rb
lib/puppet/functions/crit.rb
# frozen_string_literal: true # Logs a message on the server at level `crit`. Puppet::Functions.create_function(:crit, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :crit do scope_param repeated_param 'Any', :values return_type 'Undef' end def crit(scope, *values) Puppet::Util::Log.log_func(scope, :crit, values) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/size.rb
lib/puppet/functions/size.rb
# frozen_string_literal: true # The same as length() - returns the size of an Array, Hash, String, or Binary value. # # @since 6.0.0 - also supporting Binary # Puppet::Functions.create_function(:size) do dispatch :generic_size do param 'Variant[Collection, String, Binary]', :arg end def generic_size(arg) call_function('length', arg) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/strip.rb
lib/puppet/functions/strip.rb
# frozen_string_literal: true # Strips leading and trailing spaces from a String # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String` the conversion removes all leading and trailing ASCII white space characters such as space, tab, newline, and return. # It does not remove other space-like characters like hard space (Unicode U+00A0). (Tip, `/^[[:space:]]/` regular expression # matches all space-like characters). # * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is processed and the conversion is not recursive. # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # # @example Removing leading and trailing space from a String # ```puppet # " hello\n\t".strip() # strip(" hello\n\t") # ``` # Would both result in `"hello"` # # @example Removing trailing space from strings in an Array # ```puppet # [" hello\n\t", " hi\n\t"].strip() # strip([" hello\n\t", " hi\n\t"]) # ``` # Would both result in `['hello', 'hi']` # Puppet::Functions.create_function(:strip) do dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_iterable do param 'Iterable[Variant[String, Numeric]]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.strip end def on_iterable(a) a.map { |x| do_strip(x) } end def do_strip(x) # x can only be a String or Numeric because type constraints have been automatically applied x.is_a?(String) ? x.strip : x end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/rstrip.rb
lib/puppet/functions/rstrip.rb
# frozen_string_literal: true # Strips trailing spaces from a String # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String` the conversion removes all trailing ASCII white space characters such as space, tab, newline, and return. # It does not remove other space-like characters like hard space (Unicode U+00A0). (Tip, `/^[[:space:]]/` regular expression # matches all space-like characters). # * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is processed and the conversion is not recursive. # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # # @example Removing trailing space from a String # ```puppet # " hello\n\t".rstrip() # rstrip(" hello\n\t") # ``` # Would both result in `"hello"` # # @example Removing trailing space from strings in an Array # ```puppet # [" hello\n\t", " hi\n\t"].rstrip() # rstrip([" hello\n\t", " hi\n\t"]) # ``` # Would both result in `['hello', 'hi']` # Puppet::Functions.create_function(:rstrip) do dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_iterable do param 'Iterable[Variant[String, Numeric]]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.rstrip end def on_iterable(a) a.map { |x| do_rstrip(x) } end def do_rstrip(x) # x can only be a String or Numeric because type constraints have been automatically applied x.is_a?(String) ? x.rstrip : x end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/hiera.rb
lib/puppet/functions/hiera.rb
# frozen_string_literal: true require 'hiera/puppet_function' # Performs a standard priority lookup of the hierarchy and returns the most specific value # for a given key. The returned value can be any type of data. # # This function is deprecated in favor of the `lookup` function. While this function # continues to work, it does **not** support: # * `lookup_options` stored in the data # * lookup across global, environment, and module layers # # The function takes up to three arguments, in this order: # # 1. A string key that Hiera searches for in the hierarchy. **Required**. # 2. An optional default value to return if Hiera doesn't find anything matching the key. # * If this argument isn't provided and this function results in a lookup failure, Puppet # fails with a compilation error. # 3. The optional name of an arbitrary # [hierarchy level](https://puppet.com/docs/hiera/latest/hierarchy.html) to insert at the # top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup. # * If Hiera doesn't find a matching key in the overriding hierarchy level, it continues # searching the rest of the hierarchy. # # The `hiera` function does **not** find all matches throughout a hierarchy, instead # returning the first specific value starting at the top of the hierarchy. To search # throughout a hierarchy, use the `hiera_array` or `hiera_hash` functions. # # @example Using `hiera` # # ```yaml # # Assuming hiera.yaml # # :hierarchy: # # - web01.example.com # # - common # # # Assuming web01.example.com.yaml: # # users: # # - "Amy Barry" # # - "Carrie Douglas" # # # Assuming common.yaml: # users: # admins: # - "Edith Franklin" # - "Ginny Hamilton" # regular: # - "Iris Jackson" # - "Kelly Lambert" # ``` # # ```puppet # # Assuming we are not web01.example.com: # # $users = hiera('users', undef) # # # $users contains {admins => ["Edith Franklin", "Ginny Hamilton"], # # regular => ["Iris Jackson", "Kelly Lambert"]} # ``` # # You can optionally generate the default value with a # [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) that # takes one parameter. # # @example Using `hiera` with a lambda # # ```puppet # # Assuming the same Hiera data as the previous example: # # $users = hiera('users') | $key | { "Key \'${key}\' not found" } # # # $users contains {admins => ["Edith Franklin", "Ginny Hamilton"], # # regular => ["Iris Jackson", "Kelly Lambert"]} # # If hiera couldn't match its key, it would return the lambda result, # # "Key 'users' not found". # ``` # # The returned value's data type depends on the types of the results. In the example # above, Hiera matches the 'users' key and returns it as a hash. # # See # [the 'Using the lookup function' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) for how to perform lookup of data. # Also see # [the 'Using the deprecated hiera functions' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) # for more information about the Hiera 3 functions. # # @since 4.0.0 # Puppet::Functions.create_function(:hiera, Hiera::PuppetFunction) do init_dispatch end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/step.rb
lib/puppet/functions/step.rb
# frozen_string_literal: true # Provides stepping with given interval over elements in an iterable and optionally runs a # [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) for each # element. # # This function takes two to three arguments: # # 1. An 'Iterable' that the function will iterate over. # 2. An `Integer` step factor. This must be a positive integer. # 3. An optional lambda, which the function calls for each element in the interval. It must # request one parameter. # # @example Using the `step` function # # ```puppet # $data.step(<n>) |$parameter| { <PUPPET CODE BLOCK> } # ``` # # or # # ```puppet # $stepped_data = $data.step(<n>) # ``` # # or # # ```puppet # step($data, <n>) |$parameter| { <PUPPET CODE BLOCK> } # ``` # # or # # ```puppet # $stepped_data = step($data, <n>) # ``` # # When no block is given, Puppet returns an `Iterable` that yields the first element and every nth successor # element, from its first argument. This allows functions on iterables to be chained. # When a block is given, Puppet iterates and calls the block with the first element and then with # every nth successor element. It then returns `undef`. # # @example Using the `step` function with an array, a step factor, and a one-parameter block # # ```puppet # # For the array $data, call a block with the first element and then with each 3rd successor element # $data = [1,2,3,4,5,6,7,8] # $data.step(3) |$item| { # notice($item) # } # # Puppet notices the values '1', '4', '7'. # ``` # When no block is given, Puppet returns a new `Iterable` which allows it to be directly chained into # another function that takes an `Iterable` as an argument. # # @example Using the `step` function chained with a `map` function. # # ```puppet # # For the array $data, return an array, set to the first element and each 5th successor element, in reverse # # order multiplied by 10 # $data = Integer[0,20] # $transformed_data = $data.step(5).map |$item| { $item * 10 } # $transformed_data contains [0,50,100,150,200] # ``` # # @example The same example using `step` function chained with a `map` in alternative syntax # # ```puppet # # For the array $data, return an array, set to the first and each 5th # # successor, in reverse order, multiplied by 10 # $data = Integer[0,20] # $transformed_data = map(step($data, 5)) |$item| { $item * 10 } # $transformed_data contains [0,50,100,150,200] # ``` # # @since 4.4.0 # Puppet::Functions.create_function(:step) do dispatch :step do param 'Iterable', :iterable param 'Integer[1]', :step end dispatch :step_block do param 'Iterable', :iterable param 'Integer[1]', :step block_param 'Callable[1,1]', :block end def step(iterable, step) # produces an Iterable Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable, true).step(step) end def step_block(iterable, step, &block) Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable).step(step, &block) nil end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/floor.rb
lib/puppet/functions/floor.rb
# frozen_string_literal: true # Returns the largest `Integer` less or equal to the argument. # Takes a single numeric value as an argument. # # This function is backwards compatible with the same function in stdlib # and accepts a `Numeric` value. A `String` that can be converted # to a floating point number can also be used in this version - but this # is deprecated. # # In general convert string input to `Numeric` before calling this function # to have full control over how the conversion is done. # Puppet::Functions.create_function(:floor) do dispatch :on_numeric do param 'Numeric', :val end dispatch :on_string do param 'String', :val end def on_numeric(x) x.floor end def on_string(x) Puppet.warn_once('deprecations', 'floor_function_numeric_coerce_string', _("The floor() function's auto conversion of String to Float is deprecated - change to convert input before calling")) begin Float(x).floor rescue TypeError, ArgumentError => _e # TRANSLATORS: 'floor' is a name and should not be translated raise(ArgumentError, _('floor(): cannot convert given value to a floating point value.')) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/epp.rb
lib/puppet/functions/epp.rb
# frozen_string_literal: true # Evaluates an Embedded Puppet (EPP) template file and returns the rendered text # result as a String. # # `epp('<MODULE NAME>/<TEMPLATE FILE>', <PARAMETER HASH>)` # # The first argument to this function should be a `<MODULE NAME>/<TEMPLATE FILE>` # reference, which loads `<TEMPLATE FILE>` from `<MODULE NAME>`'s `templates` # directory. In most cases, the last argument is optional; if used, it should be a # [hash](https://puppet.com/docs/puppet/latest/lang_data_hash.html) that contains parameters to # pass to the template. # # - See the [template](https://puppet.com/docs/puppet/latest/lang_template.html) # documentation for general template usage information. # - See the [EPP syntax](https://puppet.com/docs/puppet/latest/lang_template_epp.html) # documentation for examples of EPP. # # For example, to call the apache module's `templates/vhost/_docroot.epp` # template and pass the `docroot` and `virtual_docroot` parameters, call the `epp` # function like this: # # `epp('apache/vhost/_docroot.epp', { 'docroot' => '/var/www/html', # 'virtual_docroot' => '/var/www/example' })` # # This function can also accept an absolute path, which can load a template file # from anywhere on disk. # # Puppet produces a syntax error if you pass more parameters than are declared in # the template's parameter tag. When passing parameters to a template that # contains a parameter tag, use the same names as the tag's declared parameters. # # Parameters are required only if they are declared in the called template's # parameter tag without default values. Puppet produces an error if the `epp` # function fails to pass any required parameter. # # @since 4.0.0 # Puppet::Functions.create_function(:epp, Puppet::Functions::InternalFunction) do dispatch :epp do scope_param param 'String', :path optional_param 'Hash[Pattern[/^\w+$/], Any]', :parameters return_type 'Variant[String, Sensitive[String]]' end def epp(scope, path, parameters = nil) Puppet::Pops::Evaluator::EppEvaluator.epp(scope, path, scope.compiler.environment, parameters) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/defined.rb
lib/puppet/functions/defined.rb
# frozen_string_literal: true # Determines whether a given class or resource type is defined and returns a Boolean # value. You can also use `defined` to determine whether a specific resource is defined, # or whether a variable has a value (including `undef`, as opposed to the variable never # being declared or assigned). # # This function takes at least one string argument, which can be a class name, type name, # resource reference, or variable reference of the form `'$name'`. (Note that the `$` sign # is included in the string which must be in single quotes to prevent the `$` character # to be interpreted as interpolation. # # The `defined` function checks both native and defined types, including types # provided by modules. Types and classes are matched by their names. The function matches # resource declarations by using resource references. # # @example Different types of `defined` function matches # # ```puppet # # Matching resource types # defined("file") # defined("customtype") # # # Matching defines and classes # defined("foo") # defined("foo::bar") # # # Matching variables (note the single quotes) # defined('$name') # # # Matching declared resources # defined(File['/tmp/file']) # ``` # # Puppet depends on the configuration's evaluation order when checking whether a resource # is declared. # # @example Importance of evaluation order when using `defined` # # ```puppet # # Assign values to $is_defined_before and $is_defined_after using identical `defined` # # functions. # # $is_defined_before = defined(File['/tmp/file']) # # file { "/tmp/file": # ensure => present, # } # # $is_defined_after = defined(File['/tmp/file']) # # # $is_defined_before returns false, but $is_defined_after returns true. # ``` # # This order requirement only refers to evaluation order. The order of resources in the # configuration graph (e.g. with `before` or `require`) does not affect the `defined` # function's behavior. # # > **Warning:** Avoid relying on the result of the `defined` function in modules, as you # > might not be able to guarantee the evaluation order well enough to produce consistent # > results. This can cause other code that relies on the function's result to behave # > inconsistently or fail. # # If you pass more than one argument to `defined`, the function returns `true` if _any_ # of the arguments are defined. You can also match resources by type, allowing you to # match conditions of different levels of specificity, such as whether a specific resource # is of a specific data type. # # @example Matching multiple resources and resources by different types with `defined` # # ```puppet # file { "/tmp/file1": # ensure => file, # } # # $tmp_file = file { "/tmp/file2": # ensure => file, # } # # # Each of these statements return `true` ... # defined(File['/tmp/file1']) # defined(File['/tmp/file1'],File['/tmp/file2']) # defined(File['/tmp/file1'],File['/tmp/file2'],File['/tmp/file3']) # # ... but this returns `false`. # defined(File['/tmp/file3']) # # # Each of these statements returns `true` ... # defined(Type[Resource['file','/tmp/file2']]) # defined(Resource['file','/tmp/file2']) # defined(File['/tmp/file2']) # defined('$tmp_file') # # ... but each of these returns `false`. # defined(Type[Resource['exec','/tmp/file2']]) # defined(Resource['exec','/tmp/file2']) # defined(File['/tmp/file3']) # defined('$tmp_file2') # ``` # # @since 2.7.0 # @since 3.6.0 variable reference and future parser types # @since 3.8.1 type specific requests with future parser # @since 4.0.0 # Puppet::Functions.create_function(:defined, Puppet::Functions::InternalFunction) do dispatch :is_defined do scope_param required_repeated_param 'Variant[String, Type[CatalogEntry], Type[Type[CatalogEntry]]]', :vals end def is_defined(scope, *vals) # rubocop:disable Naming/PredicatePrefix vals.any? do |val| case val when String if val =~ /^\$(.+)$/ scope.exist?(Regexp.last_match(1)) else case val when '' next nil when 'main' # Find the main class (known as ''), it does not have to be in the catalog Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_main_class(scope) else # Find a resource type, definition or class definition Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_resource_type_or_class(scope, val) end end when Puppet::Resource # Find instance of given resource type and title that is in the catalog scope.compiler.findresource(val.resource_type, val.title) when Puppet::Pops::Types::PResourceType raise ArgumentError, _('The given resource type is a reference to all kind of types') if val.type_name.nil? type = Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_resource_type(scope, val.type_name) val.title.nil? ? type : scope.compiler.findresource(type, val.title) when Puppet::Pops::Types::PClassType raise ArgumentError, _('The given class type is a reference to all classes') if val.class_name.nil? scope.compiler.findresource(:class, val.class_name) when Puppet::Pops::Types::PTypeType case val.type when Puppet::Pops::Types::PResourceType # It is most reasonable to take Type[File] and Type[File[foo]] to mean the same as if not wrapped in a Type # Since the difference between File and File[foo] already captures the distinction of type vs instance. is_defined(scope, val.type) when Puppet::Pops::Types::PClassType # Interpreted as asking if a class (and nothing else) is defined without having to be included in the catalog # (this is the same as asking for just the class' name, but with the added certainty that it cannot be a defined type. # raise ArgumentError, _('The given class type is a reference to all classes') if val.type.class_name.nil? Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_hostclass(scope, val.type.class_name) end else raise ArgumentError, _("Invalid argument of type '%{value_class}' to 'defined'") % { value_class: val.class } end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/info.rb
lib/puppet/functions/info.rb
# frozen_string_literal: true # Logs a message on the server at level `info`. Puppet::Functions.create_function(:info, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :info do scope_param repeated_param 'Any', :values return_type 'Undef' end def info(scope, *values) Puppet::Util::Log.log_func(scope, :info, values) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/contain.rb
lib/puppet/functions/contain.rb
# frozen_string_literal: true # Makes one or more classes be contained inside the current class. # If any of these classes are undeclared, they will be declared as if # there were declared with the `include` function. # Accepts a class name, an array of class names, or a comma-separated # list of class names. # # A contained class will not be applied before the containing class is # begun, and will be finished before the containing class is finished. # # You must use the class's full name; # relative names are not allowed. In addition to names in string form, # you may also directly use `Class` and `Resource` `Type`-values that are produced by # evaluating resource and relationship expressions. # # The function returns an array of references to the classes that were contained thus # allowing the function call to `contain` to directly continue. # # - Since 4.0.0 support for `Class` and `Resource` `Type`-values, absolute names # - Since 4.7.0 a value of type `Array[Type[Class[n]]]` is returned with all the contained classes # Puppet::Functions.create_function(:contain, Puppet::Functions::InternalFunction) do dispatch :contain do scope_param # The function supports what the type system sees as Ruby runtime objects, and # they cannot be parameterized to find what is actually valid instances. # The validation is instead done in the function body itself via a call to # `transform_and_assert_classnames` on the calling scope. required_repeated_param 'Any', :names end def contain(scope, *classes) if Puppet[:tasks] raise Puppet::ParseErrorWithIssue.from_issue_and_stack( Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING, { :operation => 'contain' } ) end # Make call patterns uniform and protected against nested arrays, also make # names absolute if so desired. classes = scope.transform_and_assert_classnames(classes.flatten) result = classes.map { |name| Puppet::Pops::Types::TypeFactory.host_class(name) } containing_resource = scope.resource # This is the same as calling the include function but faster and does not rely on the include # function. (scope.compiler.evaluate_classes(classes, scope, false) || []).each do |resource| unless scope.catalog.edge?(containing_resource, resource) scope.catalog.add_edge(containing_resource, resource) end end # Result is an Array[Class, 1, n] which allows chaining other operations result end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/debug.rb
lib/puppet/functions/debug.rb
# frozen_string_literal: true # Logs a message on the server at level `debug`. Puppet::Functions.create_function(:debug, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :debug do scope_param repeated_param 'Any', :values return_type 'Undef' end def debug(scope, *values) Puppet::Util::Log.log_func(scope, :debug, values) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/partition.rb
lib/puppet/functions/partition.rb
# frozen_string_literal: true # Returns two arrays, the first containing the elements of enum for which the block evaluates to true, # the second containing the rest. Puppet::Functions.create_function(:partition) do # @param collection A collection of things to partition. # @example Partition array of empty strings, results in e.g. `[[''], [b, c]]` # ```puppet # ['', b, c].partition |$s| { $s.empty } # ``` # @example Partition array of strings using index, results in e.g. `[['', 'ab'], ['b']]` # ```puppet # ['', b, ab].partition |$i, $s| { $i == 2 or $s.empty } # ``` # @example Partition hash of strings by key-value pair, results in e.g. `[[['b', []]], [['a', [1, 2]]]]` # ```puppet # { a => [1, 2], b => [] }.partition |$kv| { $kv[1].empty } # ``` # @example Partition hash of strings by key and value, results in e.g. `[[['b', []]], [['a', [1, 2]]]]` # ```puppet # { a => [1, 2], b => [] }.partition |$k, $v| { $v.empty } # ``` dispatch :partition_1 do required_param 'Collection', :collection block_param 'Callable[1,1]', :block return_type 'Tuple[Array, Array]' end dispatch :partition_2a do required_param 'Array', :array block_param 'Callable[2,2]', :block return_type 'Tuple[Array, Array]' end dispatch :partition_2 do required_param 'Collection', :collection block_param 'Callable[2,2]', :block return_type 'Tuple[Array, Array]' end def partition_1(collection) collection.partition do |item| yield(item) end.freeze end def partition_2a(array) partitioned = array.size.times.zip(array).partition do |k, v| yield(k, v) end partitioned.map do |part| part.map { |item| item[1] } end.freeze end def partition_2(collection) collection.partition do |k, v| yield(k, v) end.freeze end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/strftime.rb
lib/puppet/functions/strftime.rb
# frozen_string_literal: true # Formats timestamp or timespan according to the directives in the given format string. The directives begins with a percent (%) character. # Any text not listed as a directive will be passed through to the output string. # # A third optional timezone argument can be provided. The first argument will then be formatted to represent a local time in that # timezone. The timezone can be any timezone that is recognized when using the '%z' or '%Z' formats, or the word 'current', in which # case the current timezone of the evaluating process will be used. The timezone argument is case insensitive. # # The default timezone, when no argument is provided, or when using the keyword `default`, is 'UTC'. # # The directive consists of a percent (%) character, zero or more flags, optional minimum field width and # a conversion specifier as follows: # # ``` # %[Flags][Width]Conversion # ``` # # ### Flags that controls padding # # | Flag | Meaning # | ---- | --------------- # | - | Don't pad numerical output # | _ | Use spaces for padding # | 0 | Use zeros for padding # # ### `Timestamp` specific flags # # | Flag | Meaning # | ---- | --------------- # | # | Change case # | ^ | Use uppercase # | : | Use colons for %z # # ### Format directives applicable to `Timestamp` (names and padding can be altered using flags): # # **Date (Year, Month, Day):** # # | Format | Meaning | # | ------ | ------- | # | Y | Year with century, zero-padded to at least 4 digits | # | C | year / 100 (rounded down such as 20 in 2009) | # | y | year % 100 (00..99) | # | m | Month of the year, zero-padded (01..12) | # | B | The full month name ("January") | # | b | The abbreviated month name ("Jan") | # | h | Equivalent to %b | # | d | Day of the month, zero-padded (01..31) | # | e | Day of the month, blank-padded ( 1..31) | # | j | Day of the year (001..366) | # # **Time (Hour, Minute, Second, Subsecond):** # # | Format | Meaning | # | ------ | ------- | # | H | Hour of the day, 24-hour clock, zero-padded (00..23) | # | k | Hour of the day, 24-hour clock, blank-padded ( 0..23) | # | I | Hour of the day, 12-hour clock, zero-padded (01..12) | # | l | Hour of the day, 12-hour clock, blank-padded ( 1..12) | # | P | Meridian indicator, lowercase ("am" or "pm") | # | p | Meridian indicator, uppercase ("AM" or "PM") | # | M | Minute of the hour (00..59) | # | S | Second of the minute (00..60) | # | L | Millisecond of the second (000..999). Digits under millisecond are truncated to not produce 1000 | # | N | Fractional seconds digits, default is 9 digits (nanosecond). Digits under a specified width are truncated to avoid carry up | # # **Time (Hour, Minute, Second, Subsecond):** # # | Format | Meaning | # | ------ | ------- | # | z | Time zone as hour and minute offset from UTC (e.g. +0900) | # | :z | hour and minute offset from UTC with a colon (e.g. +09:00) | # | ::z | hour, minute and second offset from UTC (e.g. +09:00:00) | # | Z | Abbreviated time zone name or similar information. (OS dependent) | # # **Weekday:** # # | Format | Meaning | # | ------ | ------- | # | A | The full weekday name ("Sunday") | # | a | The abbreviated name ("Sun") | # | u | Day of the week (Monday is 1, 1..7) | # | w | Day of the week (Sunday is 0, 0..6) | # # **ISO 8601 week-based year and week number:** # # The first week of YYYY starts with a Monday and includes YYYY-01-04. # The days in the year before the first week are in the last week of # the previous year. # # | Format | Meaning | # | ------ | ------- | # | G | The week-based year | # | g | The last 2 digits of the week-based year (00..99) | # | V | Week number of the week-based year (01..53) | # # **Week number:** # # The first week of YYYY that starts with a Sunday or Monday (according to %U # or %W). The days in the year before the first week are in week 0. # # | Format | Meaning | # | ------ | ------- | # | U | Week number of the year. The week starts with Sunday. (00..53) | # | W | Week number of the year. The week starts with Monday. (00..53) | # # **Seconds since the Epoch:** # # | Format | Meaning | # | ------ | ------- | # | s | Number of seconds since 1970-01-01 00:00:00 UTC. | # # **Literal string:** # # | Format | Meaning | # | ------ | ------- | # | n | Newline character (\n) | # | t | Tab character (\t) | # | % | Literal "%" character | # # **Combination:** # # | Format | Meaning | # | ------ | ------- | # | c | date and time (%a %b %e %T %Y) | # | D | Date (%m/%d/%y) | # | F | The ISO 8601 date format (%Y-%m-%d) | # | v | VMS date (%e-%^b-%4Y) | # | x | Same as %D | # | X | Same as %T | # | r | 12-hour time (%I:%M:%S %p) | # | R | 24-hour time (%H:%M) | # | T | 24-hour time (%H:%M:%S) | # # @example Using `strftime` with a `Timestamp`: # # ```puppet # $timestamp = Timestamp('2016-08-24T12:13:14') # # # Notice the timestamp using a format that notices the ISO 8601 date format # notice($timestamp.strftime('%F')) # outputs '2016-08-24' # # # Notice the timestamp using a format that notices weekday, month, day, time (as UTC), and year # notice($timestamp.strftime('%c')) # outputs 'Wed Aug 24 12:13:14 2016' # # # Notice the timestamp using a specific timezone # notice($timestamp.strftime('%F %T %z', 'PST')) # outputs '2016-08-24 04:13:14 -0800' # # # Notice the timestamp using timezone that is current for the evaluating process # notice($timestamp.strftime('%F %T', 'current')) # outputs the timestamp using the timezone for the current process # ``` # # ### Format directives applicable to `Timespan`: # # | Format | Meaning | # | ------ | ------- | # | D | Number of Days | # | H | Hour of the day, 24-hour clock | # | M | Minute of the hour (00..59) | # | S | Second of the minute (00..59) | # | L | Millisecond of the second (000..999). Digits under millisecond are truncated to not produce 1000. | # | N | Fractional seconds digits, default is 9 digits (nanosecond). Digits under a specified length are truncated to avoid carry up | # # The format directive that represents the highest magnitude in the format will be allowed to overflow. # I.e. if no "%D" is used but a "%H" is present, then the hours will be more than 23 in case the # timespan reflects more than a day. # # @example Using `strftime` with a Timespan and a format # # ```puppet # $duration = Timespan({ hours => 3, minutes => 20, seconds => 30 }) # # # Notice the duration using a format that outputs <hours>:<minutes>:<seconds> # notice($duration.strftime('%H:%M:%S')) # outputs '03:20:30' # # # Notice the duration using a format that outputs <minutes>:<seconds> # notice($duration.strftime('%M:%S')) # outputs '200:30' # ``` # # - Since 4.8.0 # Puppet::Functions.create_function(:strftime) do dispatch :format_timespan do param 'Timespan', :time_object param 'String', :format end dispatch :format_timestamp do param 'Timestamp', :time_object param 'String', :format optional_param 'String', :timezone end dispatch :legacy_strftime do param 'String', :format optional_param 'String', :timezone end def format_timespan(time_object, format) time_object.format(format) end def format_timestamp(time_object, format, timezone = nil) time_object.format(format, timezone) end def legacy_strftime(format, timezone = nil) file, line = Puppet::Pops::PuppetStack.top_of_stack Puppet.warn_once('deprecations', 'legacy#strftime', _('The argument signature (String format, [String timezone]) is deprecated for #strftime. See #strftime documentation and Timespan type for more info'), file, line) Puppet::Pops::Time::Timestamp.format_time(format, Time.now.utc, timezone) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/match.rb
lib/puppet/functions/match.rb
# frozen_string_literal: true # Matches a regular expression against a string and returns an array containing the match # and any matched capturing groups. # # The first argument is a string or array of strings. The second argument is either a # regular expression, regular expression represented as a string, or Regex or Pattern # data type that the function matches against the first argument. # # The returned array contains the entire match at index 0, and each captured group at # subsequent index values. If the value or expression being matched is an array, the # function returns an array with mapped match results. # # If the function doesn't find a match, it returns 'undef'. # # @example Matching a regular expression in a string # # ```puppet # $matches = "abc123".match(/[a-z]+[1-9]+/) # # $matches contains [abc123] # ``` # # @example Matching a regular expressions with grouping captures in a string # # ```puppet # $matches = "abc123".match(/([a-z]+)([1-9]+)/) # # $matches contains [abc123, abc, 123] # ``` # # @example Matching a regular expression with grouping captures in an array of strings # # ```puppet # $matches = ["abc123","def456"].match(/([a-z]+)([1-9]+)/) # # $matches contains [[abc123, abc, 123], [def456, def, 456]] # ``` # # @since 4.0.0 # Puppet::Functions.create_function(:match) do dispatch :match do param 'String', :string param 'Variant[Any, Type]', :pattern end dispatch :enumerable_match do param 'Array[String]', :string param 'Variant[Any, Type]', :pattern end def initialize(closure_scope, loader) super # Make this visitor shared among all instantiations of this function since it is faster. # This can be used because it is not possible to replace # a puppet runtime (where this function is) without a reboot. If you model a function in a module after # this class, use a regular instance variable instead to enable reloading of the module without reboot # @@match_visitor ||= Puppet::Pops::Visitor.new(self, "match", 1, 1) end # Matches given string against given pattern and returns an Array with matches. # @param string [String] the string to match # @param pattern [String, Regexp, Puppet::Pops::Types::PPatternType, Puppet::Pops::PRegexpType, Array] the pattern # @return [Array<String>] matches where first match is the entire match, and index 1-n are captures from left to right # def match(string, pattern) @@match_visitor.visit_this_1(self, pattern, string) end # Matches given Array[String] against given pattern and returns an Array with mapped match results. # # @param array [Array<String>] the array of strings to match # @param pattern [String, Regexp, Puppet::Pops::Types::PPatternType, Puppet::Pops::PRegexpType, Array] the pattern # @return [Array<Array<String, nil>>] Array with matches (see {#match}), non matching entries produce a nil entry # def enumerable_match(array, pattern) array.map { |s| match(s, pattern) } end protected def match_Object(obj, s) msg = _("match() expects pattern of T, where T is String, Regexp, Regexp[r], Pattern[p], or Array[T]. Got %{klass}") % { klass: obj.class } raise ArgumentError, msg end def match_String(pattern_string, s) do_match(s, Regexp.new(pattern_string)) end def match_Regexp(regexp, s) do_match(s, regexp) end def match_PTypeAliasType(alias_t, s) match(s, alias_t.resolved_type) end def match_PVariantType(var_t, s) # Find first matching type (or error out if one of the variants is not acceptable) result = nil var_t.types.find { |t| result = match(s, t) } result end def match_PRegexpType(regexp_t, s) raise ArgumentError, _("Given Regexp Type has no regular expression") unless regexp_t.pattern do_match(s, regexp_t.regexp) end def match_PPatternType(pattern_t, s) # Since we want the actual match result (not just a boolean), an iteration over # Pattern's regular expressions is needed. (They are of PRegexpType) result = nil pattern_t.patterns.find { |pattern| result = match(s, pattern) } result end # Returns the first matching entry def match_Array(array, s) result = nil array.flatten.find { |entry| result = match(s, entry) } result end private def do_match(s, regexp) result = regexp.match(s) result.to_a if result end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/values.rb
lib/puppet/functions/values.rb
# frozen_string_literal: true # Returns the values of a hash as an Array # # @example Using `values` # # ```puppet # $hsh = {"apples" => 3, "oranges" => 4 } # $hsh.values() # values($hsh) # # both results in the array [3, 4] # ``` # # * Note that a hash in the puppet language accepts any data value (including `undef`) unless # it is constrained with a `Hash` data type that narrows the allowed data types. # * For an empty hash, an empty array is returned. # * The order of the values is the same as the order in the hash (typically the order in which they were added). # Puppet::Functions.create_function(:values) do dispatch :values do param 'Hash', :hsh end def values(hsh) hsh.values end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/unwrap.rb
lib/puppet/functions/unwrap.rb
# frozen_string_literal: true # Unwraps a Sensitive value and returns the wrapped object. # Returns the Value itself, if it is not Sensitive. # # @example Usage of unwrap # # ```puppet # $plaintext = 'hunter2' # $pw = Sensitive.new($plaintext) # notice("Wrapped object is $pw") #=> Prints "Wrapped object is Sensitive [value redacted]" # $unwrapped = $pw.unwrap # notice("Unwrapped object is $unwrapped") #=> Prints "Unwrapped object is hunter2" # ``` # # You can optionally pass a block to unwrap in order to limit the scope where the # unwrapped value is visible. # # @example Unwrapping with a block of code # # ```puppet # $pw = Sensitive.new('hunter2') # notice("Wrapped object is $pw") #=> Prints "Wrapped object is Sensitive [value redacted]" # $pw.unwrap |$unwrapped| { # $conf = inline_template("password: ${unwrapped}\n") # Sensitive.new($conf) # } #=> Returns a new Sensitive object containing an interpolated config file # # $unwrapped is now out of scope # ``` # # @since 4.0.0 # Puppet::Functions.create_function(:unwrap) do dispatch :from_sensitive do param 'Sensitive', :arg optional_block_param end dispatch :from_any do param 'Any', :arg optional_block_param end def from_sensitive(arg) unwrapped = arg.unwrap if block_given? yield(unwrapped) else unwrapped end end def from_any(arg) unwrapped = arg if block_given? yield(unwrapped) else unwrapped end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/lest.rb
lib/puppet/functions/lest.rb
# frozen_string_literal: true # Calls a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # without arguments if the value given to `lest` is `undef`. # Returns the result of calling the lambda if the argument is `undef`, otherwise the # given argument. # # The `lest` function is useful in a chain of `then` calls, or in general # as a guard against `undef` values. The function can be used to call `fail`, or to # return a default value. # # These two expressions are equivalent: # # ```puppet # if $x == undef { do_things() } # lest($x) || { do_things() } # ``` # # @example Using the `lest` function # # ```puppet # $data = {a => [ b, c ] } # notice $data.dig(a, b, c) # .then |$x| { $x * 2 } # .lest || { fail("no value for $data[a][b][c]" } # ``` # # Would fail the operation because `$data[a][b][c]` results in `undef` # (there is no `b` key in `a`). # # In contrast - this example: # # ```puppet # $data = {a => { b => { c => 10 } } } # notice $data.dig(a, b, c) # .then |$x| { $x * 2 } # .lest || { fail("no value for $data[a][b][c]" } # ``` # # Would notice the value `20` # # @since 4.5.0 # Puppet::Functions.create_function(:lest) do dispatch :lest do param 'Any', :arg block_param 'Callable[0,0]', :block end def lest(arg) if arg.nil? yield() else arg end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/join.rb
lib/puppet/functions/join.rb
# frozen_string_literal: true # Joins the values of an Array into a string with elements separated by a delimiter. # # Supports up to two arguments # * **values** - first argument is required and must be an an `Array` # * **delimiter** - second arguments is the delimiter between elements, must be a `String` if given, and defaults to an empty string. # # @example Typical use of `join` # # ```puppet # join(['a','b','c'], ",") # # Would result in: "a,b,c" # ``` # # Note that array is flattened before elements are joined, but flattening does not extend to arrays nested in hashes or other objects. # # @example Arrays nested in hashes are not joined # # ```puppet # $a = [1,2, undef, 'hello', [x,y,z], {a => 2, b => [3, 4]}] # notice join($a, ', ') # # # would result in noticing: # # 1, 2, , hello, x, y, z, {"a"=>2, "b"=>[3, 4]} # ``` # # For joining iterators and other containers of elements a conversion must first be made to # an `Array`. The reason for this is that there are many options how such a conversion should # be made. # # @example Joining the result of a reverse_each converted to an array # # ```puppet # [1,2,3].reverse_each.convert_to(Array).join(', ') # # would result in: "3, 2, 1" # ``` # @example Joining a hash # # ```puppet # {a => 1, b => 2}.convert_to(Array).join(', ') # # would result in "a, 1, b, 2" # ``` # # For more detailed control over the formatting (including indentations and line breaks, delimiters around arrays # and hash entries, between key/values in hash entries, and individual formatting of values in the array) # see the `new` function for `String` and its formatting options for `Array` and `Hash`. # Puppet::Functions.create_function(:join) do dispatch :join do param 'Array', :arg optional_param 'String', :delimiter end def join(arg, delimiter = '', puppet_formatting = false) arg.join(delimiter) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/compare.rb
lib/puppet/functions/compare.rb
# frozen_string_literal: true # Compares two values and returns -1, 0 or 1 if first value is smaller, equal or larger than the second value. # The compare function accepts arguments of the data types `String`, `Numeric`, `Timespan`, `Timestamp`, and `Semver`, # such that: # # * two of the same data type can be compared # * `Timespan` and `Timestamp` can be compared with each other and with `Numeric` # # When comparing two `String` values the comparison can be made to consider case by passing a third (optional) # boolean `false` value - the default is `true` which ignores case as the comparison operators # in the Puppet Language. # Puppet::Functions.create_function(:compare) do local_types do type 'TimeComparable = Variant[Numeric, Timespan, Timestamp]' type 'Comparable = Variant[String, Semver, TimeComparable]' end dispatch :on_numeric do param 'Numeric', :a param 'Numeric', :b end dispatch :on_string do param 'String', :a param 'String', :b optional_param 'Boolean', :ignore_case end dispatch :on_version do param 'Semver', :a param 'Semver', :b end dispatch :on_time_num_first do param 'Numeric', :a param 'Variant[Timespan, Timestamp]', :b end dispatch :on_timestamp do param 'Timestamp', :a param 'Variant[Timestamp, Numeric]', :b end dispatch :on_timespan do param 'Timespan', :a param 'Variant[Timespan, Numeric]', :b end argument_mismatch :on_error do param 'Comparable', :a param 'Comparable', :b repeated_param 'Any', :ignore_case end argument_mismatch :on_not_comparable do param 'Any', :a param 'Any', :b repeated_param 'Any', :ignore_case end def on_numeric(a, b) a <=> b end def on_string(a, b, ignore_case = true) if ignore_case a.casecmp(b) else a <=> b end end def on_version(a, b) a <=> b end def on_time_num_first(a, b) # Time data types can compare against Numeric but not the other way around # the comparison is therefore done in reverse and the answer is inverted. -(b <=> a) end def on_timespan(a, b) a <=> b end def on_timestamp(a, b) a <=> b end def on_not_comparable(a, b, *ignore_case) # TRANSLATORS 'compare' is a name _("compare(): Non comparable type. Only values of the types Numeric, String, Semver, Timestamp and Timestamp can be compared. Got %{type_a} and %{type_b}") % { type_a: type_label(a), type_b: type_label(b) } end def on_error(a, b, *ignore_case) unless ignore_case.empty? unless a.is_a?(String) && b.is_a?(String) # TRANSLATORS 'compare' is a name return _("compare(): The third argument (ignore case) can only be used when comparing strings") end unless ignore_case.size == 1 # TRANSLATORS 'compare' is a name return _("compare(): Accepts at most 3 arguments, got %{actual_number}") % { actual_number: 2 + ignore_case.size } end unless ignore_case[0].is_a?(Boolean) # TRANSLATORS 'compare' is a name return _("compare(): The third argument (ignore case) must be a Boolean. Got %{type}") % { type: type_label(ignore_case[0]) } end end if a.class != b.class # TRANSLATORS 'compare' is a name _("compare(): Can only compare values of the same type (or for Timestamp/Timespan also against Numeric). Got %{type_a} and %{type_b}") % { type_a: type_label(a), type_b: type_label(b) } end end def type_label(x) Puppet::Pops::Model::ModelLabelProvider.new.label(x) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/emerg.rb
lib/puppet/functions/emerg.rb
# frozen_string_literal: true # Logs a message on the server at level `emerg`. Puppet::Functions.create_function(:emerg, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :emerg do scope_param repeated_param 'Any', :values return_type 'Undef' end def emerg(scope, *values) Puppet::Util::Log.log_func(scope, :emerg, values) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/notice.rb
lib/puppet/functions/notice.rb
# frozen_string_literal: true # Logs a message on the server at level `notice`. Puppet::Functions.create_function(:notice, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :notice do scope_param repeated_param 'Any', :values return_type 'Undef' end def notice(scope, *values) Puppet::Util::Log.log_func(scope, :notice, values) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/require.rb
lib/puppet/functions/require.rb
# frozen_string_literal: true # Requires the specified classes. # Evaluate one or more classes, adding the required class as a dependency. # # The relationship metaparameters work well for specifying relationships # between individual resources, but they can be clumsy for specifying # relationships between classes. This function is a superset of the # `include` function, adding a class relationship so that the requiring # class depends on the required class. # # Warning: using `require` in place of `include` can lead to unwanted dependency cycles. # # For instance, the following manifest, with `require` instead of `include`, would produce a nasty # dependence cycle, because `notify` imposes a `before` between `File[/foo]` and `Service[foo]`: # # ```puppet # class myservice { # service { foo: ensure => running } # } # # class otherstuff { # include myservice # file { '/foo': notify => Service[foo] } # } # ``` # # Note that this function only works with clients 0.25 and later, and it will # fail if used with earlier clients. # # You must use the class's full name; # relative names are not allowed. In addition to names in string form, # you may also directly use Class and Resource Type values that are produced when evaluating # resource and relationship expressions. # # - Since 4.0.0 Class and Resource types, absolute names # - Since 4.7.0 Returns an `Array[Type[Class]]` with references to the required classes # Puppet::Functions.create_function(:require, Puppet::Functions::InternalFunction) do dispatch :require_impl do scope_param # The function supports what the type system sees as Ruby runtime objects, and # they cannot be parameterized to find what is actually valid instances. # The validation is instead done in the function body itself via a call to # `transform_and_assert_classnames` on the calling scope. required_repeated_param 'Any', :names end def require_impl(scope, *classes) if Puppet[:tasks] raise Puppet::ParseErrorWithIssue.from_issue_and_stack( Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING, { :operation => 'require' } ) end # Make call patterns uniform and protected against nested arrays, also make # names absolute if so desired. classes = scope.transform_and_assert_classnames(classes.flatten) result = classes.map { |name| Puppet::Pops::Types::TypeFactory.host_class(name) } # This is the same as calling the include function (but faster) since it again # would otherwise need to perform the optional absolute name transformation # (for no reason since they are already made absolute here). # scope.compiler.evaluate_classes(classes, scope, false) krt = scope.environment.known_resource_types classes.each do |klass| # lookup the class in the scopes klass = (classobj = krt.find_hostclass(klass)) ? classobj.name : nil raise Puppet::ParseError, _("Could not find class %{klass}") % { klass: klass } unless klass ref = Puppet::Resource.new(:class, klass) resource = scope.resource resource.set_parameter(:require, [resource[:require]].flatten.compact << ref) end result end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/camelcase.rb
lib/puppet/functions/camelcase.rb
# frozen_string_literal: true # Creates a Camel Case version of a String # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String` the conversion replaces all combinations of `*_<char>*` with an upcased version of the # character following the _. This is done using Ruby system locale which handles some, but not all # special international up-casing rules (for example German double-s ß is upcased to "Ss"). # * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is capitalized and the conversion is not recursive. # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # * The result will not contain any underscore characters. # # Please note: This function relies directly on Ruby's String implementation and as such may not be entirely UTF8 compatible. # To ensure best compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # # @example Camelcase a String # ```puppet # 'hello_friend'.camelcase() # camelcase('hello_friend') # ``` # Would both result in `"HelloFriend"` # # @example Camelcase of strings in an Array # ```puppet # ['abc_def', 'bcd_xyz'].camelcase() # camelcase(['abc_def', 'bcd_xyz']) # ``` # Would both result in `['AbcDef', 'BcdXyz']` # Puppet::Functions.create_function(:camelcase) do dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_iterable do param 'Iterable[Variant[String, Numeric]]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.split('_').map(&:capitalize).join('') end def on_iterable(a) a.map { |x| do_camelcase(x) } end def do_camelcase(x) # x can only be a String or Numeric because type constraints have been automatically applied x.is_a?(String) ? on_string(x) : x end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/get.rb
lib/puppet/functions/get.rb
# frozen_string_literal: true # Digs into a value with dot notation to get a value from within a structure. # # **To dig into a given value**, call the function with (at least) two arguments: # # * The **first** argument must be an Array, or Hash. Value can also be `undef` # (which also makes the result `undef` unless a _default value_ is given). # * The **second** argument must be a _dot notation navigation string_. # * The **optional third** argument can be any type of value and it is used # as the _default value_ if the function would otherwise return `undef`. # * An **optional lambda** for error handling taking one `Error` argument. # # **Dot notation navigation string** - # The dot string consists of period `.` separated segments where each # segment is either the index into an array or the value of a hash key. # If a wanted key contains a period it must be quoted to avoid it being # taken as a segment separator. Quoting can be done with either # single quotes `'` or double quotes `"`. If a segment is # a decimal number it is converted to an Integer index. This conversion # can be prevented by quoting the value. # # @example Navigating into a value # ```puppet # #get($facts, 'os.family') # $facts.get('os.family') # ``` # Would both result in the value of `$facts['os']['family']` # # @example Getting the value from an expression # ```puppet # get([1,2,[{'name' =>'waldo'}]], '2.0.name') # ``` # Would result in `'waldo'` # # @example Using a default value # ```puppet # get([1,2,[{'name' =>'waldo'}]], '2.1.name', 'not waldo') # # ``` # Would result in `'not waldo'` # # @example Quoting a key with period # ```puppet # $x = [1, 2, { 'readme.md' => "This is a readme."}] # $x.get('2."readme.md"') # ``` # # @example Quoting a numeric string # ```puppet # $x = [1, 2, { '10' => "ten"}] # $x.get('2."0"') # ``` # # **Error Handling** - There are two types of common errors that can # be handled by giving the function a code block to execute. # (A third kind or error; when the navigation string has syntax errors # (for example an empty segment or unbalanced quotes) will always raise # an error). # # The given block will be given an instance of the `Error` data type, # and it has methods to extract `msg`, `issue_code`, `kind`, and # `details`. # # The `msg` will be a preformatted message describing the error. # This is the error message that would have surfaced if there was # no block to handle the error. # # The `kind` is the string `'SLICE_ERROR'` for both kinds of errors, # and the `issue_code` is either the string `'EXPECTED_INTEGER_INDEX'` # for an attempt to index into an array with a String, # or `'EXPECTED_COLLECTION'` for an attempt to index into something that # is not a Collection. # # The `details` is a Hash that for both issue codes contain the # entry `'walked_path'` which is an Array with each key in the # progression of the dig up to the place where the error occurred. # # For an `EXPECTED_INTEGER_INDEX`-issue the detail `'index_type'` is # set to the data type of the index value and for an # `'EXPECTED_COLLECTION'`-issue the detail `'value_type'` is set # to the type of the value. # # The logic in the error handling block can inspect the details, # and either call `fail()` with a custom error message or produce # the wanted value. # # If the block produces `undef` it will not be replaced with a # given default value. # # @example Ensure `undef` result on error # ```puppet # $x = 'blue' # $x.get('0.color', 'green') |$error| { undef } # result is undef # # $y = ['blue'] # $y.get('color', 'green') |$error| { undef } # result is undef # ``` # # @example Accessing information in the Error # ```puppet # $x = [1, 2, ['blue']] # $x.get('2.color') |$error| { # notice("Walked path is ${error.details['walked_path']}") # } # ``` # Would notice `Walked path is [2, color]` # # Also see: # * `getvar()` that takes the first segment to be the name of a variable # and then delegates to this function. # * `dig()` function which is similar but uses an # array of navigation values instead of a dot notation string. # # @since 6.0.0 # Puppet::Functions.create_function(:get, Puppet::Functions::InternalFunction) do dispatch :get_from_value do param 'Any', :value param 'String', :dotted_string optional_param 'Any', :default_value optional_block_param 'Callable[1,1]', :block end # Gets a result from given value and a navigation string # def get_from_value(value, navigation, default_value = nil, &block) return default_value if value.nil? return value if navigation.empty? # Note: split_key always processes the initial segment as a string even if it could be an integer. # This since it is designed for lookup keys. For a numeric first segment # like '0.1' the wanted result is `[0,1]`, not `["0", 1]`. The workaround here is to # prefix the navigation with `"x."` thus giving split_key a first segment that is a string. # The fake segment is then dropped. segments = split_key("x." + navigation) { |_err| _("Syntax error in dotted-navigation string") } segments.shift begin result = call_function('dig', value, *segments) result.nil? ? default_value : result rescue Puppet::ErrorWithData => e if block_given? yield(e.error_data) else raise e end end end # reuse the split_key parser used also by lookup include Puppet::Pops::Lookup::SubLookup end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/assert_type.rb
lib/puppet/functions/assert_type.rb
# frozen_string_literal: true # Returns the given value if it is of the given # [data type](https://puppet.com/docs/puppet/latest/lang_data.html), or # otherwise either raises an error or executes an optional two-parameter # [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html). # # The function takes two mandatory arguments, in this order: # # 1. The expected data type. # 2. A value to compare against the expected data type. # # @example Using `assert_type` # # ```puppet # $raw_username = 'Amy Berry' # # # Assert that $raw_username is a non-empty string and assign it to $valid_username. # $valid_username = assert_type(String[1], $raw_username) # # # $valid_username contains "Amy Berry". # # If $raw_username was an empty string or a different data type, the Puppet run would # # fail with an "Expected type does not match actual" error. # ``` # # You can use an optional lambda to provide enhanced feedback. The lambda takes two # mandatory parameters, in this order: # # 1. The expected data type as described in the function's first argument. # 2. The actual data type of the value. # # @example Using `assert_type` with a warning and default value # # ```puppet # $raw_username = 'Amy Berry' # # # Assert that $raw_username is a non-empty string and assign it to $valid_username. # # If it isn't, output a warning describing the problem and use a default value. # $valid_username = assert_type(String[1], $raw_username) |$expected, $actual| { # warning( "The username should be \'${expected}\', not \'${actual}\'. Using 'anonymous'." ) # 'anonymous' # } # # # $valid_username contains "Amy Berry". # # If $raw_username was an empty string, the Puppet run would set $valid_username to # # "anonymous" and output a warning: "The username should be 'String[1, default]', not # # 'String[0, 0]'. Using 'anonymous'." # ``` # # For more information about data types, see the # [documentation](https://puppet.com/docs/puppet/latest/lang_data.html). # # @since 4.0.0 # Puppet::Functions.create_function(:assert_type) do dispatch :assert_type do param 'Type', :type param 'Any', :value optional_block_param 'Callable[Type, Type]', :block end dispatch :assert_type_s do param 'String', :type_string param 'Any', :value optional_block_param 'Callable[Type, Type]', :block end # @param type [Type] the type the value must be an instance of # @param value [Object] the value to assert # def assert_type(type, value) unless Puppet::Pops::Types::TypeCalculator.instance?(type, value) inferred_type = Puppet::Pops::Types::TypeCalculator.infer_set(value) if block_given? # Give the inferred type to allow richer comparison in the given block (if generalized # information is lost). # value = yield(type, inferred_type) else raise Puppet::Pops::Types::TypeAssertionError.new( Puppet::Pops::Types::TypeMismatchDescriber.singleton.describe_mismatch('assert_type():', type, inferred_type), type, inferred_type ) end end value end # @param type_string [String] the type the value must be an instance of given in String form # @param value [Object] the value to assert # def assert_type_s(type_string, value, &proc) t = Puppet::Pops::Types::TypeParser.singleton.parse(type_string) block_given? ? assert_type(t, value, &proc) : assert_type(t, value) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/next.rb
lib/puppet/functions/next.rb
# frozen_string_literal: true # Makes iteration continue with the next value, optionally with a given value for this iteration. # If a value is not given it defaults to `undef` # # @example Using the `next()` function # # ```puppet # $data = ['a','b','c'] # $data.each |Integer $index, String $value| { # if $index == 1 { # next() # } # notice ("${index} = ${value}") # } # ``` # # Would notice: # ``` # Notice: Scope(Class[main]): 0 = a # Notice: Scope(Class[main]): 2 = c # ``` # # @since 4.7.0 Puppet::Functions.create_function(:next) do dispatch :next_impl do optional_param 'Any', :value end def next_impl(value = nil) file, line = Puppet::Pops::PuppetStack.top_of_stack exc = Puppet::Pops::Evaluator::Next.new(value, file, line) raise exc end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/convert_to.rb
lib/puppet/functions/convert_to.rb
# frozen_string_literal: true # The `convert_to(value, type)` is a convenience function that does the same as `new(type, value)`. # The difference in the argument ordering allows it to be used in chained style for # improved readability "left to right". # # When the function is given a lambda, it is called with the converted value, and the function # returns what the lambda returns, otherwise the converted value. # # @example 'convert_to' instead of 'new' # # ```puppet # # The harder to read variant: # # Using new operator - that is "calling the type" with operator () # Hash(Array("abc").map |$i,$v| { [$i, $v] }) # # # The easier to read variant: # # using 'convert_to' # "abc".convert_to(Array).map |$i,$v| { [$i, $v] }.convert_to(Hash) # ``` # # @since 5.4.0 # Puppet::Functions.create_function(:convert_to) do dispatch :convert_to do param 'Any', :value param 'Type', :type optional_repeated_param 'Any', :args optional_block_param 'Callable[1,1]', :block end def convert_to(value, type, *args, &block) result = call_function('new', type, value, *args) block_given? ? yield(result) : result end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/split.rb
lib/puppet/functions/split.rb
# frozen_string_literal: true # Splits a string into an array using a given pattern. # The pattern can be a string, regexp or regexp type. # # @example Splitting a String value # # ```puppet # $string = 'v1.v2:v3.v4' # $array_var1 = split($string, /:/) # $array_var2 = split($string, '[.]') # $array_var3 = split($string, Regexp['[.:]']) # # #`$array_var1` now holds the result `['v1.v2', 'v3.v4']`, # # while `$array_var2` holds `['v1', 'v2:v3', 'v4']`, and # # `$array_var3` holds `['v1', 'v2', 'v3', 'v4']`. # ``` # # Note that in the second example, we split on a literal string that contains # a regexp meta-character (`.`), which must be escaped. A simple # way to do that for a single character is to enclose it in square # brackets; a backslash will also escape a single character. # Puppet::Functions.create_function(:split) do dispatch :split_String do param 'String', :str param 'String', :pattern end dispatch :split_Regexp do param 'String', :str param 'Regexp', :pattern end dispatch :split_RegexpType do param 'String', :str param 'Type[Regexp]', :pattern end dispatch :split_String_sensitive do param 'Sensitive[String]', :sensitive param 'String', :pattern end dispatch :split_Regexp_sensitive do param 'Sensitive[String]', :sensitive param 'Regexp', :pattern end dispatch :split_RegexpType_sensitive do param 'Sensitive[String]', :sensitive param 'Type[Regexp]', :pattern end def split_String(str, pattern) str.split(Regexp.compile(pattern)) end def split_Regexp(str, pattern) str.split(pattern) end def split_RegexpType(str, pattern) str.split(pattern.regexp) end def split_String_sensitive(sensitive, pattern) Puppet::Pops::Types::PSensitiveType::Sensitive.new(split_String(sensitive.unwrap, pattern)) end def split_Regexp_sensitive(sensitive, pattern) Puppet::Pops::Types::PSensitiveType::Sensitive.new(split_Regexp(sensitive.unwrap, pattern)) end def split_RegexpType_sensitive(sensitive, pattern) Puppet::Pops::Types::PSensitiveType::Sensitive.new(split_RegexpType(sensitive.unwrap, pattern)) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/scanf.rb
lib/puppet/functions/scanf.rb
# frozen_string_literal: true # Scans a string and returns an array of one or more converted values based on the given format string. # See the documentation of Ruby's String#scanf method for details about the supported formats (which # are similar but not identical to the formats used in Puppet's `sprintf` function.) # # This function takes two mandatory arguments: the first is the string to convert, and the second is # the format string. The result of the scan is an array, with each successfully scanned and transformed value. # The scanning stops if a scan is unsuccessful, and the scanned result up to that point is returned. If there # was no successful scan, the result is an empty array. # # "42".scanf("%i") # # You can also optionally pass a lambda to scanf, to do additional validation or processing. # # # "42".scanf("%i") |$x| { # unless $x[0] =~ Integer { # fail "Expected a well formed integer value, got '$x[0]'" # } # $x[0] # } # # # # # # @since 4.0.0 # Puppet::Functions.create_function(:scanf) do require 'scanf' dispatch :scanf do param 'String', :data param 'String', :format optional_block_param end def scanf(data, format) result = data.scanf(format) if block_given? result = yield(result) end result end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/map.rb
lib/puppet/functions/map.rb
# frozen_string_literal: true # Applies a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # to every value in a data structure and returns an array containing the results. # # This function takes two mandatory arguments, in this order: # # 1. An array, hash, or other iterable object that the function will iterate over. # 2. A lambda, which the function calls for each element in the first argument. It can # request one or two parameters. # # @example Using the `map` function # # `$transformed_data = $data.map |$parameter| { <PUPPET CODE BLOCK> }` # # or # # `$transformed_data = map($data) |$parameter| { <PUPPET CODE BLOCK> }` # # When the first argument (`$data` in the above example) is an array, Puppet passes each # value in turn to the lambda. # # @example Using the `map` function with an array and a one-parameter lambda # # ```puppet # # For the array $data, return an array containing each value multiplied by 10 # $data = [1,2,3] # $transformed_data = $data.map |$items| { $items * 10 } # # $transformed_data contains [10,20,30] # ``` # # When the first argument is a hash, Puppet passes each key and value pair to the lambda # as an array in the form `[key, value]`. # # @example Using the `map` function with a hash and a one-parameter lambda # # ```puppet # # For the hash $data, return an array containing the keys # $data = {'a'=>1,'b'=>2,'c'=>3} # $transformed_data = $data.map |$items| { $items[0] } # # $transformed_data contains ['a','b','c'] # ``` # # When the first argument is an array and the lambda has two parameters, Puppet passes the # array's indexes (enumerated from 0) in the first parameter and its values in the second # parameter. # # @example Using the `map` function with an array and a two-parameter lambda # # ```puppet # # For the array $data, return an array containing the indexes # $data = [1,2,3] # $transformed_data = $data.map |$index,$value| { $index } # # $transformed_data contains [0,1,2] # ``` # # When the first argument is a hash, Puppet passes its keys to the first parameter and its # values to the second parameter. # # @example Using the `map` function with a hash and a two-parameter lambda # # ```puppet # # For the hash $data, return an array containing each value # $data = {'a'=>1,'b'=>2,'c'=>3} # $transformed_data = $data.map |$key,$value| { $value } # # $transformed_data contains [1,2,3] # ``` # # @since 4.0.0 # Puppet::Functions.create_function(:map) do dispatch :map_Hash_2 do param 'Hash[Any, Any]', :hash block_param 'Callable[2,2]', :block end dispatch :map_Hash_1 do param 'Hash[Any, Any]', :hash block_param 'Callable[1,1]', :block end dispatch :map_Enumerable_2 do param 'Iterable', :enumerable block_param 'Callable[2,2]', :block end dispatch :map_Enumerable_1 do param 'Iterable', :enumerable block_param 'Callable[1,1]', :block end def map_Hash_1(hash) result = [] begin hash.each { |x, y| result << yield([x, y]) } rescue StopIteration end result end def map_Hash_2(hash) result = [] begin hash.each { |x, y| result << yield(x, y) } rescue StopIteration end result end def map_Enumerable_1(enumerable) result = [] enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) begin enum.each do |val| result << yield(val) end rescue StopIteration end result end def map_Enumerable_2(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? enum.map { |entry| yield(*entry) } else result = [] begin enum.each_with_index do |val, index| result << yield(index, val) end rescue StopIteration end result end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/import.rb
lib/puppet/functions/import.rb
# frozen_string_literal: true # The import function raises an error when called to inform the user that import is no longer supported. # Puppet::Functions.create_function(:import) do def import(*args) raise Puppet::Pops::SemanticError, Puppet::Pops::Issues::DISCONTINUED_IMPORT end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/return.rb
lib/puppet/functions/return.rb
# frozen_string_literal: true # Makes iteration continue with the next value, optionally with a given value for this iteration. # If a value is not given it defaults to `undef` # # @since 4.7.0 # Puppet::Functions.create_function(:return, Puppet::Functions::InternalFunction) do dispatch :return_impl do optional_param 'Any', :value end def return_impl(value = nil) file, line = Puppet::Pops::PuppetStack.top_of_stack raise Puppet::Pops::Evaluator::Return.new(value, file, line) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/min.rb
lib/puppet/functions/min.rb
# frozen_string_literal: true # Returns the lowest value among a variable number of arguments. # Takes at least one argument. # # This function is (with one exception) compatible with the stdlib function # with the same name and performs deprecated type conversion before # comparison as follows: # # * If a value converted to String is an optionally '-' prefixed, # string of digits, one optional decimal point, followed by optional # decimal digits - then the comparison is performed on the values # converted to floating point. # * If a value is not considered convertible to float, it is converted # to a `String` and the comparison is a lexical compare where min is # the lexicographical earlier value. # * A lexicographical compare is performed in a system locale - international # characters may therefore not appear in what a user thinks is the correct order. # * The conversion rules apply to values in pairs - the rule must hold for both # values - a value may therefore be compared using different rules depending # on the "other value". # * The returned result found to be the "lowest" is the original unconverted value. # # The above rules have been deprecated in Puppet 6.0.0 as they produce strange results when # given values of mixed data types. In general, either convert values to be # all `String` or all `Numeric` values before calling the function, or call the # function with a lambda that performs type conversion and comparison. This because one # simply cannot compare `Boolean` with `Regexp` and with any arbitrary `Array`, `Hash` or # `Object` and getting a meaningful result. # # The one change in the function's behavior is when the function is given a single # array argument. The stdlib implementation would return that array as the result where # it now instead returns the max value from that array. # # @example 'min of values - stdlib compatible' # # ```puppet # notice(min(1)) # would notice 1 # notice(min(1,2)) # would notice 1 # notice(min("1", 2)) # would notice 1 # notice(min("0777", 512)) # would notice 512, since "0777" is not converted from octal form # notice(min(0777, 512)) # would notice 511, since 0777 is decimal 511 # notice(min('aa', 'ab')) # would notice 'aa' # notice(min(['a'], ['b'])) # would notice ['a'], since "['a']" is before "['b']" # ``` # # @example find 'min' value in an array # # ```puppet # $x = [1,2,3,4] # notice(min(*$x)) # would notice 1 # ``` # # @example find 'min' value in an array directly - since Puppet 6.0.0 # # ```puppet # $x = [1,2,3,4] # notice(min($x)) # would notice 1 # notice($x.min) # would notice 1 # ``` # This example shows that a single array argument is used as the set of values # as opposed to being a single returned value. # # When calling with a lambda, it must accept two variables and it must return # one of -1, 0, or 1 depending on if first argument is before/lower than, equal to, # or higher/after the second argument. # # @example 'min of values using a lambda' # # ```puppet # notice(min("2", "10", "100") |$a, $b| { compare($a, $b) }) # ``` # # Would notice "10" as lower since it is lexicographically lower/before the other values. Without the # lambda the stdlib compatible (deprecated) behavior would have been to return "2" since number conversion kicks in. # Puppet::Functions.create_function(:min) do dispatch :on_numeric do repeated_param 'Numeric', :values end dispatch :on_string do repeated_param 'String', :values end dispatch :on_semver do repeated_param 'Semver', :values end dispatch :on_timespan do repeated_param 'Timespan', :values end dispatch :on_timestamp do repeated_param 'Timestamp', :values end dispatch :on_single_numeric_array do param 'Array[Numeric]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_semver_array do param 'Array[Semver]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_timespan_array do param 'Array[Timespan]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_timestamp_array do param 'Array[Timestamp]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_string_array do param 'Array[String]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_any_array do param 'Array', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_any_with_block do repeated_param 'Any', :values block_param 'Callable[2,2]', :block end dispatch :on_any do repeated_param 'Any', :values end # All are Numeric - ok now, will be ok later def on_numeric(*args) assert_arg_count(args) args.min end # All are String, may convert to numeric (which is deprecated) def on_string(*args) assert_arg_count(args) args.min do |a, b| if a.to_s =~ /\A^-?\d+([._eE]\d+)?\z/ && b.to_s =~ /\A-?\d+([._eE]\d+)?\z/ Puppet.warn_once('deprecations', 'min_function_numeric_coerce_string', _("The min() function's auto conversion of String to Numeric is deprecated - change to convert input before calling, or use lambda")) a.to_f <=> b.to_f else # case sensitive as in the stdlib function a <=> b end end end def on_semver(*args) assert_arg_count(args) args.min end def on_timespan(*args) assert_arg_count(args) args.min end def on_timestamp(*args) assert_arg_count(args) args.min end def on_any_with_block(*args, &block) args.min { |x, y| block.call(x, y) } end def on_single_numeric_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_numeric(*array) end end def on_single_string_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_string(*array) end end def on_single_semver_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_semver(*array) end end def on_single_timespan_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_timespan(*array) end end def on_single_timestamp_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_timestamp(*array) end end def on_single_any_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_any(*array) end end # Mix of data types - while only some compares are actually bad it will deprecate # the entire call # def on_any(*args) assert_arg_count(args) args.min do |a, b| as = a.to_s bs = b.to_s if as =~ /\A^-?\d+([._eE]\d+)?\z/ && bs =~ /\A-?\d+([._eE]\d+)?\z/ Puppet.warn_once('deprecations', 'min_function_numeric_coerce_string', _("The min() function's auto conversion of String to Numeric is deprecated - change to convert input before calling, or use lambda")) a.to_f <=> b.to_f else Puppet.warn_once('deprecations', 'min_function_string_coerce_any', _("The min() function's auto conversion of Any to String is deprecated - change to convert input before calling, or use lambda")) as <=> bs end end end def assert_arg_count(args) raise(ArgumentError, 'min(): Wrong number of arguments need at least one') if args.empty? end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/err.rb
lib/puppet/functions/err.rb
# frozen_string_literal: true # Logs a message on the server at level `err`. Puppet::Functions.create_function(:err, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :err do scope_param repeated_param 'Any', :values return_type 'Undef' end def err(scope, *values) Puppet::Util::Log.log_func(scope, :err, values) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/downcase.rb
lib/puppet/functions/downcase.rb
# frozen_string_literal: true # Converts a String, Array or Hash (recursively) into lower case. # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String`, its lower case version is returned. This is done using Ruby system locale which handles some, but not all # special international up-casing rules (for example German double-s ß is upcased to "SS", whereas upper case double-s # is downcased to ß). # * For `Array` and `Hash` the conversion to lower case is recursive and each key and value must be convertible by # this function. # * When a `Hash` is converted, some keys could result in the same key - in those cases, the # latest key-value wins. For example if keys "aBC", and "abC" where both present, after downcase there would only be one # key "abc". # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # # Please note: This function relies directly on Ruby's String implementation and as such may not be entirely UTF8 compatible. # To ensure best compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # # @example Converting a String to lower case # ```puppet # 'HELLO'.downcase() # downcase('HEllO') # ``` # Would both result in `"hello"` # # @example Converting an Array to lower case # ```puppet # ['A', 'B'].downcase() # downcase(['A', 'B']) # ``` # Would both result in `['a', 'b']` # # @example Converting a Hash to lower case # ```puppet # {'A' => 'HEllO', 'B' => 'GOODBYE'}.downcase() # ``` # Would result in `{'a' => 'hello', 'b' => 'goodbye'}` # # @example Converting a recursive structure # ```puppet # ['A', 'B', ['C', ['D']], {'X' => 'Y'}].downcase # ``` # Would result in `['a', 'b', ['c', ['d']], {'x' => 'y'}]` # Puppet::Functions.create_function(:downcase) do local_types do type 'StringData = Variant[String, Numeric, Array[StringData], Hash[StringData, StringData]]' end dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_array do param 'Array[StringData]', :arg end dispatch :on_hash do param 'Hash[StringData, StringData]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.downcase end def on_array(a) a.map { |x| do_downcase(x) } end def on_hash(h) result = {} h.each_pair { |k, v| result[do_downcase(k)] = do_downcase(v) } result end def do_downcase(x) x.is_a?(String) ? x.downcase : call_function('downcase', x) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/each.rb
lib/puppet/functions/each.rb
# frozen_string_literal: true # Runs a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # repeatedly using each value in a data structure, then returns the values unchanged. # # This function takes two mandatory arguments, in this order: # # 1. An array, hash, or other iterable object that the function will iterate over. # 2. A lambda, which the function calls for each element in the first argument. It can # request one or two parameters. # # @example Using the `each` function # # `$data.each |$parameter| { <PUPPET CODE BLOCK> }` # # or # # `each($data) |$parameter| { <PUPPET CODE BLOCK> }` # # When the first argument (`$data` in the above example) is an array, Puppet passes each # value in turn to the lambda, then returns the original values. # # @example Using the `each` function with an array and a one-parameter lambda # # ```puppet # # For the array $data, run a lambda that creates a resource for each item. # $data = ["routers", "servers", "workstations"] # $data.each |$item| { # notify { $item: # message => $item # } # } # # Puppet creates one resource for each of the three items in $data. Each resource is # # named after the item's value and uses the item's value in a parameter. # ``` # # When the first argument is a hash, Puppet passes each key and value pair to the lambda # as an array in the form `[key, value]` and returns the original hash. # # @example Using the `each` function with a hash and a one-parameter lambda # # ```puppet # # For the hash $data, run a lambda using each item as a key-value array that creates a # # resource for each item. # $data = {"rtr" => "Router", "svr" => "Server", "wks" => "Workstation"} # $data.each |$items| { # notify { $items[0]: # message => $items[1] # } # } # # Puppet creates one resource for each of the three items in $data, each named after the # # item's key and containing a parameter using the item's value. # ``` # # When the first argument is an array and the lambda has two parameters, Puppet passes the # array's indexes (enumerated from 0) in the first parameter and its values in the second # parameter. # # @example Using the `each` function with an array and a two-parameter lambda # # ```puppet # # For the array $data, run a lambda using each item's index and value that creates a # # resource for each item. # $data = ["routers", "servers", "workstations"] # $data.each |$index, $value| { # notify { $value: # message => $index # } # } # # Puppet creates one resource for each of the three items in $data, each named after the # # item's value and containing a parameter using the item's index. # ``` # # When the first argument is a hash, Puppet passes its keys to the first parameter and its # values to the second parameter. # # @example Using the `each` function with a hash and a two-parameter lambda # # ```puppet # # For the hash $data, run a lambda using each item's key and value to create a resource # # for each item. # $data = {"rtr" => "Router", "svr" => "Server", "wks" => "Workstation"} # $data.each |$key, $value| { # notify { $key: # message => $value # } # } # # Puppet creates one resource for each of the three items in $data, each named after the # # item's key and containing a parameter using the item's value. # ``` # # For an example that demonstrates how to create multiple `file` resources using `each`, # see the Puppet # [iteration](https://puppet.com/docs/puppet/latest/lang_iteration.html) # documentation. # # @since 4.0.0 # Puppet::Functions.create_function(:each) do dispatch :foreach_Hash_2 do param 'Hash[Any, Any]', :hash block_param 'Callable[2,2]', :block end dispatch :foreach_Hash_1 do param 'Hash[Any, Any]', :hash block_param 'Callable[1,1]', :block end dispatch :foreach_Enumerable_2 do param 'Iterable', :enumerable block_param 'Callable[2,2]', :block end dispatch :foreach_Enumerable_1 do param 'Iterable', :enumerable block_param 'Callable[1,1]', :block end def foreach_Hash_1(hash) begin hash.each_pair do |pair| yield(pair) end rescue StopIteration end # produces the receiver hash end def foreach_Hash_2(hash) begin hash.each_pair do |pair| yield(*pair) end rescue StopIteration end # produces the receiver hash end def foreach_Enumerable_1(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) begin enum.each do |value| yield value end rescue StopIteration end # produces the receiver enumerable end def foreach_Enumerable_2(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? enum.each { |entry| yield(*entry) } else begin enum.each_with_index do |value, index| yield(index, value) end rescue StopIteration end end # produces the receiver enumerable end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/lookup.rb
lib/puppet/functions/lookup.rb
# frozen_string_literal: true # Uses the Puppet lookup system to retrieve a value for a given key. By default, # this returns the first value found (and fails compilation if no values are # available), but you can configure it to merge multiple values into one, fail # gracefully, and more. # # When looking up a key, Puppet will search up to three tiers of data, in the # following order: # # 1. Hiera. # 2. The current environment's data provider. # 3. The indicated module's data provider, if the key is of the form # `<MODULE NAME>::<SOMETHING>`. # # #### Arguments # # You must provide the name of a key to look up, and can optionally provide other # arguments. You can combine these arguments in the following ways: # # * `lookup( <NAME>, [<VALUE TYPE>], [<MERGE BEHAVIOR>], [<DEFAULT VALUE>] )` # * `lookup( [<NAME>], <OPTIONS HASH> )` # * `lookup( as above ) |$key| { # lambda returns a default value }` # # Arguments in `[square brackets]` are optional. # # The arguments accepted by `lookup` are as follows: # # 1. `<NAME>` (string or array) --- The name of the key to look up. # * This can also be an array of keys. If Puppet doesn't find anything for the # first key, it will try again with the subsequent ones, only resorting to a # default value if none of them succeed. # 2. `<VALUE TYPE>` (data type) --- A # [data type](https://puppet.com/docs/puppet/latest/lang_data_type.html) # that must match the retrieved value; if not, the lookup (and catalog # compilation) will fail. Defaults to `Data` (accepts any normal value). # 3. `<MERGE BEHAVIOR>` (string or hash; see **"Merge Behaviors"** below) --- # Whether (and how) to combine multiple values. If present, this overrides any # merge behavior specified in the data sources. Defaults to no value; Puppet will # use merge behavior from the data sources if present, and will otherwise do a # first-found lookup. # 4. `<DEFAULT VALUE>` (any normal value) --- If present, `lookup` returns this # when it can't find a normal value. Default values are never merged with found # values. Like a normal value, the default must match the value type. Defaults to # no value; if Puppet can't find a normal value, the lookup (and compilation) will # fail. # 5. `<OPTIONS HASH>` (hash) --- Alternate way to set the arguments above, plus # some less-common extra options. If you pass an options hash, you can't combine # it with any regular arguments (except `<NAME>`). An options hash can have the # following keys: # * `'name'` --- Same as `<NAME>` (argument 1). You can pass this as an # argument or in the hash, but not both. # * `'value_type'` --- Same as `<VALUE TYPE>` (argument 2). # * `'merge'` --- Same as `<MERGE BEHAVIOR>` (argument 3). # * `'default_value'` --- Same as `<DEFAULT VALUE>` (argument 4). # * `'default_values_hash'` (hash) --- A hash of lookup keys and default # values. If Puppet can't find a normal value, it will check this hash for the # requested key before giving up. You can combine this with `default_value` or # a lambda, which will be used if the key isn't present in this hash. Defaults # to an empty hash. # * `'override'` (hash) --- A hash of lookup keys and override values. Puppet # will check for the requested key in the overrides hash _first;_ if found, it # returns that value as the _final_ value, ignoring merge behavior. Defaults # to an empty hash. # # Finally, `lookup` can take a lambda, which must accept a single parameter. # This is yet another way to set a default value for the lookup; if no results are # found, Puppet will pass the requested key to the lambda and use its result as # the default value. # # #### Merge Behaviors # # Puppet lookup uses a hierarchy of data sources, and a given key might have # values in multiple sources. By default, Puppet returns the first value it finds, # but it can also continue searching and merge all the values together. # # > **Note:** Data sources can use the special `lookup_options` metadata key to # request a specific merge behavior for a key. The `lookup` function will use that # requested behavior unless you explicitly specify one. # # The valid merge behaviors are: # # * `'first'` --- Returns the first value found, with no merging. Puppet lookup's # default behavior. # * `'unique'` (called "array merge" in classic Hiera) --- Combines any number of # arrays and scalar values to return a merged, flattened array with all duplicate # values removed. The lookup will fail if any hash values are found. # * `'hash'` --- Combines the keys and values of any number of hashes to return a # merged hash. If the same key exists in multiple source hashes, Puppet will use # the value from the highest-priority data source; it won't recursively merge the # values. # * `'deep'` --- Combines the keys and values of any number of hashes to return a # merged hash. If the same key exists in multiple source hashes, Puppet will # recursively merge hash or array values (with duplicate values removed from # arrays). For conflicting scalar values, the highest-priority value will win. # * `{'strategy' => 'first'}`, `{'strategy' => 'unique'}`, # or `{'strategy' => 'hash'}` --- Same as the string versions of these merge behaviors. # * `{'strategy' => 'deep', <DEEP OPTION> => <VALUE>, ...}` --- Same as `'deep'`, # but can adjust the merge with additional options. The available options are: # * `'knockout_prefix'` (string) --- A string prefix to indicate a # value should be _removed_ from the final result. If a value is exactly equal # to the prefix, it will knockout the entire element. Defaults to `undef`, which # disables this feature. # * `'sort_merged_arrays'` (boolean) --- Whether to sort all arrays that are # merged together. Defaults to `false`. # * `'merge_hash_arrays'` (boolean) --- Whether to merge hashes within arrays. # Defaults to `false`. # # @example Look up a key and return the first value found # # lookup('ntp::service_name') # # @example Do a unique merge lookup of class names, then add all of those classes to the catalog (like `hiera_include`) # # lookup('classes', Array[String], 'unique').include # # @example Do a deep hash merge lookup of user data, but let higher priority sources remove values by prefixing them with `--` # # lookup( { 'name' => 'users', # 'merge' => { # 'strategy' => 'deep', # 'knockout_prefix' => '--', # }, # }) # # @since 4.0.0 Puppet::Functions.create_function(:lookup, Puppet::Functions::InternalFunction) do local_types do type 'NameType = Variant[String, Array[String]]' type 'ValueType = Type' type 'DefaultValueType = Any' type 'MergeType = Variant[String[1], Hash[String, Scalar]]' type 'BlockType = Callable[NameType]' type "OptionsWithName = Struct[{\ name => NameType,\ value_type => Optional[ValueType],\ default_value => Optional[DefaultValueType],\ override => Optional[Hash[String,Any]],\ default_values_hash => Optional[Hash[String,Any]],\ merge => Optional[MergeType]\ }]" type "OptionsWithoutName = Struct[{\ value_type => Optional[ValueType],\ default_value => Optional[DefaultValueType],\ override => Optional[Hash[String,Any]],\ default_values_hash => Optional[Hash[String,Any]],\ merge => Optional[MergeType]\ }]" end dispatch :lookup_1 do scope_param param 'NameType', :name optional_param 'ValueType', :value_type optional_param 'MergeType', :merge end dispatch :lookup_2 do scope_param param 'NameType', :name param 'Optional[ValueType]', :value_type param 'Optional[MergeType]', :merge param 'DefaultValueType', :default_value end dispatch :lookup_3 do scope_param param 'NameType', :name optional_param 'ValueType', :value_type optional_param 'MergeType', :merge required_block_param 'BlockType', :block end # Lookup without name. Name then becomes a required entry in the options hash dispatch :lookup_4 do scope_param param 'OptionsWithName', :options_hash optional_block_param 'BlockType', :block end # Lookup using name and options hash. dispatch :lookup_5 do scope_param param 'Variant[String,Array[String]]', :name param 'OptionsWithoutName', :options_hash optional_block_param 'BlockType', :block end def lookup_1(scope, name, value_type = nil, merge = nil) do_lookup(scope, name, value_type, nil, false, {}, {}, merge) end def lookup_2(scope, name, value_type, merge, default_value) do_lookup(scope, name, value_type, default_value, true, {}, {}, merge) end def lookup_3(scope, name, value_type = nil, merge = nil, &block) do_lookup(scope, name, value_type, nil, false, {}, {}, merge, &block) end def lookup_4(scope, options_hash, &block) do_lookup(scope, options_hash['name'], *hash_args(options_hash), &block) end def lookup_5(scope, name, options_hash, &block) do_lookup(scope, name, *hash_args(options_hash), &block) end def do_lookup(scope, name, value_type, default_value, has_default, override, default_values_hash, merge, &block) Puppet::Pops::Lookup.lookup(name, value_type, default_value, has_default, merge, Puppet::Pops::Lookup::Invocation.new(scope, override, default_values_hash), &block) end def hash_args(options_hash) [ options_hash['value_type'], options_hash['default_value'], options_hash.include?('default_value'), options_hash['override'] || {}, options_hash['default_values_hash'] || {}, options_hash['merge'] ] end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/lstrip.rb
lib/puppet/functions/lstrip.rb
# frozen_string_literal: true # Strips leading spaces from a String # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String` the conversion removes all leading ASCII white space characters such as space, tab, newline, and return. # It does not remove other space-like characters like hard space (Unicode U+00A0). (Tip, `/^[[:space:]]/` regular expression # matches all space-like characters). # * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is processed and the conversion is not recursive. # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # # @example Removing leading space from a String # ```puppet # "\n\thello ".lstrip() # lstrip("\n\thello ") # ``` # Would both result in `"hello"` # # @example Removing leading space from strings in an Array # ```puppet # ["\n\thello ", "\n\thi "].lstrip() # lstrip(["\n\thello ", "\n\thi "]) # ``` # Would both result in `['hello', 'hi']` # Puppet::Functions.create_function(:lstrip) do dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_iterable do param 'Iterable[Variant[String, Numeric]]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.lstrip end def on_iterable(a) a.map { |x| do_lstrip(x) } end def do_lstrip(x) # x can only be a String or Numeric because type constraints have been automatically applied x.is_a?(String) ? x.lstrip : x end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/capitalize.rb
lib/puppet/functions/capitalize.rb
# frozen_string_literal: true # Capitalizes the first character of a String, or the first character of every String in an Iterable value (such as an Array). # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String`, a string is returned in which the first character is uppercase. # This is done using Ruby system locale which handles some, but not all # special international up-casing rules (for example German double-s ß is capitalized to "Ss"). # * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is capitalized and the conversion is not recursive. # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # # Please note: This function relies directly on Ruby's String implementation and as such may not be entirely UTF8 compatible. # To ensure best compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # # @example Capitalizing a String # ```puppet # 'hello'.capitalize() # capitalize('hello') # ``` # Would both result in `"Hello"` # # @example Capitalizing strings in an Array # ```puppet # ['abc', 'bcd'].capitalize() # capitalize(['abc', 'bcd']) # ``` # Would both result in `['Abc', 'Bcd']` # Puppet::Functions.create_function(:capitalize) do dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_iterable do param 'Iterable[Variant[String, Numeric]]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.capitalize end def on_iterable(a) a.map { |x| do_capitalize(x) } end def do_capitalize(x) # x can only be a String or Numeric because type constraints have been automatically applied x.is_a?(String) ? x.capitalize : x end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/versioncmp.rb
lib/puppet/functions/versioncmp.rb
# frozen_string_literal: true require_relative '../../puppet/util/package' # Compares two version numbers. # # Prototype: # # $result = versioncmp(a, b) # # Where a and b are arbitrary version strings. # # Optional parameter ignore_trailing_zeroes is used to ignore unnecessary # trailing version numbers like .0 or .0.00 # # This function returns: # # * `1` if version a is greater than version b # * `0` if the versions are equal # * `-1` if version a is less than version b # # @example Using versioncmp # # if versioncmp('2.6-1', '2.4.5') > 0 { # notice('2.6-1 is > than 2.4.5') # } # # This function uses the same version comparison algorithm used by Puppet's # `package` type. # Puppet::Functions.create_function(:versioncmp) do dispatch :versioncmp do param 'String', :a param 'String', :b optional_param 'Boolean', :ignore_trailing_zeroes end def versioncmp(a, b, ignore_trailing_zeroes = false) Puppet::Util::Package.versioncmp(a, b, ignore_trailing_zeroes) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/find_template.rb
lib/puppet/functions/find_template.rb
# frozen_string_literal: true # Finds an existing template from a module and returns its path. # # This function accepts an argument that is a String as a `<MODULE NAME>/<TEMPLATE>` # reference, which searches for `<TEMPLATE>` relative to a module's `templates` # directory on the primary server. (For example, the reference `mymod/secret.conf.epp` # will search for the file `<MODULES DIRECTORY>/mymod/templates/secret.conf.epp`.) # # The primary use case is for agent-side template rendering with late-bound variables # resolved, such as from secret stores inaccessible to the primary server, such as # # ``` # $variables = { # 'password' => Deferred('vault_lookup::lookup', # ['secret/mymod', 'https://vault.example.com:8200']), # } # # # compile the template source into the catalog # file { '/etc/secrets.conf': # ensure => file, # content => Deferred('inline_epp', # [find_template('mymod/secret.conf.epp').file, $variables]), # } # ``` # # # # This function can also accept: # # * An absolute String path, which checks for the existence of a template from anywhere on disk. # * Multiple String arguments, which returns the path of the **first** template # found, skipping nonexistent files. # * An array of string paths, which returns the path of the **first** template # found from the given paths in the array, skipping nonexistent files. # # The function returns `undef` if none of the given paths were found. # # @since 6.x # Puppet::Functions.create_function(:find_template, Puppet::Functions::InternalFunction) do dispatch :find_template do scope_param repeated_param 'String', :paths end dispatch :find_template_array do scope_param repeated_param 'Array[String]', :paths_array end def find_template_array(scope, array) find_template(scope, *array) end def find_template(scope, *args) args.each do |file| found = Puppet::Parser::Files.find_template(file, scope.compiler.environment) if found && Puppet::FileSystem.exist?(found) return found end end nil end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/inline_epp.rb
lib/puppet/functions/inline_epp.rb
# frozen_string_literal: true # Evaluates an Embedded Puppet (EPP) template string and returns the rendered # text result as a String. # # `inline_epp('<EPP TEMPLATE STRING>', <PARAMETER HASH>)` # # The first argument to this function should be a string containing an EPP # template. In most cases, the last argument is optional; if used, it should be a # [hash](https://puppet.com/docs/puppet/latest/lang_data_hash.html) that contains parameters to # pass to the template. # # - See the [template](https://puppet.com/docs/puppet/latest/lang_template.html) # documentation for general template usage information. # - See the [EPP syntax](https://puppet.com/docs/puppet/latest/lang_template_epp.html) # documentation for examples of EPP. # # For example, to evaluate an inline EPP template and pass it the `docroot` and # `virtual_docroot` parameters, call the `inline_epp` function like this: # # `inline_epp('docroot: <%= $docroot %> Virtual docroot: <%= $virtual_docroot %>', # { 'docroot' => '/var/www/html', 'virtual_docroot' => '/var/www/example' })` # # Puppet produces a syntax error if you pass more parameters than are declared in # the template's parameter tag. When passing parameters to a template that # contains a parameter tag, use the same names as the tag's declared parameters. # # Parameters are required only if they are declared in the called template's # parameter tag without default values. Puppet produces an error if the # `inline_epp` function fails to pass any required parameter. # # An inline EPP template should be written as a single-quoted string or # [heredoc](https://puppet.com/docs/puppet/latest/lang_data_string.html#heredocs). # A double-quoted string is subject to expression interpolation before the string # is parsed as an EPP template. # # For example, to evaluate an inline EPP template using a heredoc, call the # `inline_epp` function like this: # # ```puppet # # Outputs 'Hello given argument planet!' # inline_epp(@(END), { x => 'given argument' }) # <%- | $x, $y = planet | -%> # Hello <%= $x %> <%= $y %>! # END # ``` # # @since 4.0.0 # Puppet::Functions.create_function(:inline_epp, Puppet::Functions::InternalFunction) do dispatch :inline_epp do scope_param() param 'String', :template optional_param 'Hash[Pattern[/^\w+$/], Any]', :parameters return_type 'Variant[String, Sensitive[String]]' end def inline_epp(scope, template, parameters = nil) Puppet::Pops::Evaluator::EppEvaluator.inline_epp(scope, template, parameters) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/regsubst.rb
lib/puppet/functions/regsubst.rb
# frozen_string_literal: true # Performs regexp replacement on a string or array of strings. Puppet::Functions.create_function(:regsubst) do # @param target [String] # The string or array of strings to operate on. If an array, the replacement will be # performed on each of the elements in the array, and the return value will be an array. # @param pattern [String, Regexp, Type[Regexp]] # The regular expression matching the target string. If you want it anchored at the start # and or end of the string, you must do that with ^ and $ yourself. # @param replacement [String, Hash[String, String]] # Replacement string. Can contain backreferences to what was matched using \\0 (whole match), # \\1 (first set of parentheses), and so on. # If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string. # @param flags [Optional[Pattern[/^[GEIM]*$/]], Pattern[/^G?$/]] # Optional. String of single letter flags for how the regexp is interpreted (E, I, and M cannot be used # if pattern is a precompiled regexp): # - *E* Extended regexps # - *I* Ignore case in regexps # - *M* Multiline regexps # - *G* Global replacement; all occurrences of the regexp in each target string will be replaced. Without this, only the first occurrence will be replaced. # @param encoding [Enum['N','E','S','U']] # Deprecated and ignored parameter, included only for compatibility. # @return [Array[String], String] The result of the substitution. Result type is the same as for the target parameter. # @deprecated # This method has the optional encoding parameter, which is ignored. # @example Get the third octet from the node's IP address: # ```puppet # $i3 = regsubst($ipaddress,'^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$','\\3') # ``` dispatch :regsubst_string do param 'Variant[Array[String],String]', :target param 'String', :pattern param 'Variant[String,Hash[String,String]]', :replacement optional_param 'Optional[Pattern[/^[GEIM]*$/]]', :flags optional_param "Enum['N','E','S','U']", :encoding end # @param target [String, Array[String]] # The string or array of strings to operate on. If an array, the replacement will be # performed on each of the elements in the array, and the return value will be an array. # @param pattern [Regexp, Type[Regexp]] # The regular expression matching the target string. If you want it anchored at the start # and or end of the string, you must do that with ^ and $ yourself. # @param replacement [String, Hash[String, String]] # Replacement string. Can contain backreferences to what was matched using \\0 (whole match), # \\1 (first set of parentheses), and so on. # If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string. # @param flags [Optional[Pattern[/^[GEIM]*$/]], Pattern[/^G?$/]] # Optional. String of single letter flags for how the regexp is interpreted (E, I, and M cannot be used # if pattern is a precompiled regexp): # - *E* Extended regexps # - *I* Ignore case in regexps # - *M* Multiline regexps # - *G* Global replacement; all occurrences of the regexp in each target string will be replaced. Without this, only the first occurrence will be replaced. # @return [Array[String], String] The result of the substitution. Result type is the same as for the target parameter. # @example Put angle brackets around each octet in the node's IP address: # ```puppet # $x = regsubst($ipaddress, /([0-9]+)/, '<\\1>', 'G') # ``` dispatch :regsubst_regexp do param 'Variant[Array[String],String]', :target param 'Variant[Regexp,Type[Regexp]]', :pattern param 'Variant[String,Hash[String,String]]', :replacement optional_param 'Pattern[/^G?$/]', :flags end def regsubst_string(target, pattern, replacement, flags = nil, encoding = nil) if encoding Puppet.warn_once( 'deprecations', 'regsubst_function_encoding', _("The regsubst() function's encoding argument has been ignored since Ruby 1.9 and will be removed in a future release") ) end re_flags = 0 operation = :sub unless flags.nil? flags.split(//).each do |f| case f when 'G' then operation = :gsub when 'E' then re_flags |= Regexp::EXTENDED when 'I' then re_flags |= Regexp::IGNORECASE when 'M' then re_flags |= Regexp::MULTILINE end end end inner_regsubst(target, Regexp.compile(pattern, re_flags), replacement, operation) end def regsubst_regexp(target, pattern, replacement, flags = nil) pattern = pattern.pattern || '' if pattern.is_a?(Puppet::Pops::Types::PRegexpType) inner_regsubst(target, pattern, replacement, flags == 'G' ? :gsub : :sub) end def inner_regsubst(target, re, replacement, op) target.respond_to?(op) ? target.send(op, re, replacement) : target.collect { |e| e.send(op, re, replacement) } end private :inner_regsubst end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/group_by.rb
lib/puppet/functions/group_by.rb
# frozen_string_literal: true # Groups the collection by result of the block. Returns a hash where the keys are the evaluated result from the block # and the values are arrays of elements in the collection that correspond to the key. Puppet::Functions.create_function(:group_by) do # @param collection A collection of things to group. # @example Group array of strings by length, results in e.g. `{ 1 => [a, b], 2 => [ab] }` # ```puppet # [a, b, ab].group_by |$s| { $s.length } # ``` # @example Group array of strings by length and index, results in e.g. `{1 => ['a'], 2 => ['b', 'ab']}` # ```puppet # [a, b, ab].group_by |$i, $s| { $i%2 + $s.length } # ``` # @example Group hash iterating by key-value pair, results in e.g. `{ 2 => [['a', [1, 2]]], 1 => [['b', [1]]] }` # ```puppet # { a => [1, 2], b => [1] }.group_by |$kv| { $kv[1].length } # ``` # @example Group hash iterating by key and value, results in e.g. `{ 2 => [['a', [1, 2]]], 1 => [['b', [1]]] }` # ```puppet # { a => [1, 2], b => [1] }.group_by |$k, $v| { $v.length } # ``` dispatch :group_by_1 do required_param 'Collection', :collection block_param 'Callable[1,1]', :block return_type 'Hash' end dispatch :group_by_2a do required_param 'Array', :array block_param 'Callable[2,2]', :block return_type 'Hash' end dispatch :group_by_2 do required_param 'Collection', :collection block_param 'Callable[2,2]', :block return_type 'Hash' end def group_by_1(collection) collection.group_by do |item| yield(item) end.freeze end def group_by_2a(array) grouped = array.size.times.zip(array).group_by do |k, v| yield(k, v) end grouped.transform_values do |v| v.map { |item| item[1] } end.freeze end def group_by_2(collection) collection.group_by do |k, v| yield(k, v) end.freeze end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/break.rb
lib/puppet/functions/break.rb
# frozen_string_literal: true # Breaks an innermost iteration as if it encountered an end of input. # This function does not return to the caller. # # The signal produced to stop the iteration bubbles up through # the call stack until either terminating the innermost iteration or # raising an error if the end of the call stack is reached. # # The break() function does not accept an argument. # # @example Using `break` # # ```puppet # $data = [1,2,3] # notice $data.map |$x| { if $x == 3 { break() } $x*10 } # ``` # # Would notice the value `[10, 20]` # # @example Using a nested `break` # # ```puppet # function break_if_even($x) { # if $x % 2 == 0 { break() } # } # $data = [1,2,3] # notice $data.map |$x| { break_if_even($x); $x*10 } # ``` # Would notice the value `[10]` # # * Also see functions `next` and `return` # # @since 4.8.0 # Puppet::Functions.create_function(:break) do dispatch :break_impl do end def break_impl # get file, line if available, else they are set to nil file, line = Puppet::Pops::PuppetStack.top_of_stack # PuppetStopIteration contains file and line and is a StopIteration exception # so it can break a Ruby Kernel#loop or enumeration # raise Puppet::Pops::Evaluator::PuppetStopIteration.new(file, line) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/dig.rb
lib/puppet/functions/dig.rb
# frozen_string_literal: true # Returns a value for a sequence of given keys/indexes into a structure, such as # an array or hash. # # This function is used to "dig into" a complex data structure by # using a sequence of keys / indexes to access a value from which # the next key/index is accessed recursively. # # The first encountered `undef` value or key stops the "dig" and `undef` is returned. # # An error is raised if an attempt is made to "dig" into # something other than an `undef` (which immediately returns `undef`), an `Array` or a `Hash`. # # @example Using `dig` # # ```puppet # $data = {a => { b => [{x => 10, y => 20}, {x => 100, y => 200}]}} # notice $data.dig('a', 'b', 1, 'x') # ``` # # Would notice the value 100. # # This is roughly equivalent to `$data['a']['b'][1]['x']`. However, a standard # index will return an error and cause catalog compilation failure if any parent # of the final key (`'x'`) is `undef`. The `dig` function will return `undef`, # rather than failing catalog compilation. This allows you to check if data # exists in a structure without mandating that it always exists. # # @since 4.5.0 # Puppet::Functions.create_function(:dig) do dispatch :dig do param 'Optional[Collection]', :data repeated_param 'Any', :arg end def dig(data, *args) walked_path = [] args.reduce(data) do |d, k| return nil if d.nil? || k.nil? unless d.is_a?(Array) || d.is_a?(Hash) t = Puppet::Pops::Types::TypeCalculator.infer(d) msg = _("The given data does not contain a Collection at %{walked_path}, got '%{type}'") % { walked_path: walked_path, type: t } error_data = Puppet::DataTypes::Error.new( msg, 'SLICE_ERROR', { 'walked_path' => walked_path, 'value_type' => t }, 'EXPECTED_COLLECTION' ) raise Puppet::ErrorWithData.new(error_data, msg) end walked_path << k if d.is_a?(Array) && !k.is_a?(Integer) t = Puppet::Pops::Types::TypeCalculator.infer(k) msg = _("The given data requires an Integer index at %{walked_path}, got '%{type}'") % { walked_path: walked_path, type: t } error_data = Puppet::DataTypes::Error.new( msg, 'SLICE_ERROR', { 'walked_path' => walked_path, 'index_type' => t }, 'EXPECTED_INTEGER_INDEX' ) raise Puppet::ErrorWithData.new(error_data, msg) end d[k] end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/hocon_data.rb
lib/puppet/functions/hocon_data.rb
# frozen_string_literal: true # The `hocon_data` is a hiera 5 `data_hash` data provider function. # See [the configuration guide documentation](https://puppet.com/docs/puppet/latest/hiera_config_yaml_5.html#configuring-a-hierarchy-level-built-in-backends) for # how to use this function. # # Note that this function is not supported without a hocon library being present. # # @since 4.9.0 # Puppet::Functions.create_function(:hocon_data) do unless Puppet.features.hocon? raise Puppet::DataBinding::LookupError, _('Lookup using Hocon data_hash function is not supported without hocon library') end require 'hocon' require 'hocon/config_error' dispatch :hocon_data do param 'Struct[{path=>String[1]}]', :options param 'Puppet::LookupContext', :context end argument_mismatch :missing_path do param 'Hash', :options param 'Puppet::LookupContext', :context end def hocon_data(options, context) path = options['path'] context.cached_file_data(path) do |content| Hocon.parse(content) rescue Hocon::ConfigError => ex raise Puppet::DataBinding::LookupError, _("Unable to parse (%{path}): %{message}") % { path: path, message: ex.message } end end def missing_path(options, context) "one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml when using this data_hash function" end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/alert.rb
lib/puppet/functions/alert.rb
# frozen_string_literal: true # Logs a message on the server at level `alert`. Puppet::Functions.create_function(:alert, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :alert do scope_param repeated_param 'Any', :values return_type 'Undef' end def alert(scope, *values) Puppet::Util::Log.log_func(scope, :alert, values) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/then.rb
lib/puppet/functions/then.rb
# frozen_string_literal: true # Calls a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # with the given argument unless the argument is `undef`. # Returns `undef` if the argument is `undef`, and otherwise the result of giving the # argument to the lambda. # # This is useful to process a sequence of operations where an intermediate # result may be `undef` (which makes the entire sequence `undef`). # The `then` function is especially useful with the function `dig` which # performs in a similar way "digging out" a value in a complex structure. # # @example Using `dig` and `then` # # ```puppet # $data = {a => { b => [{x => 10, y => 20}, {x => 100, y => 200}]}} # notice $data.dig(a, b, 1, x).then |$x| { $x * 2 } # ``` # # Would notice the value 200 # # Contrast this with: # # ```puppet # $data = {a => { b => [{x => 10, y => 20}, {not_x => 100, why => 200}]}} # notice $data.dig(a, b, 1, x).then |$x| { $x * 2 } # ``` # # Which would notice `undef` since the last lookup of 'x' results in `undef` which # is returned (without calling the lambda given to the `then` function). # # As a result there is no need for conditional logic or a temporary (non local) # variable as the result is now either the wanted value (`x`) multiplied # by 2 or `undef`. # # Calls to `then` can be chained. In the next example, a structure is using an offset based on # using 1 as the index to the first element (instead of 0 which is used in the language). # We are not sure if user input actually contains an index at all, or if it is # outside the range of available names.args. # # @example Chaining calls to the `then` function # # ```puppet # # Names to choose from # $names = ['Ringo', 'Paul', 'George', 'John'] # # # Structure where 'beatle 2' is wanted (but where the number refers # # to 'Paul' because input comes from a source using 1 for the first # # element). # # $data = ['singer', { beatle => 2 }] # $picked = assert_type(String, # # the data we are interested in is the second in the array, # # a hash, where we want the value of the key 'beatle' # $data.dig(1, 'beatle') # # and we want the index in $names before the given index # .then |$x| { $names[$x-1] } # # so we can construct a string with that beatle's name # .then |$x| { "Picked Beatle '${x}'" } # ) # notice $picked # ``` # # Would notice "Picked Beatle 'Paul'", and would raise an error if the result # was not a String. # # * Since 4.5.0 # Puppet::Functions.create_function(:then) do dispatch :then do param 'Any', :arg block_param 'Callable[1,1]', :block end def then(arg) return nil if arg.nil? yield(arg) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/reverse_each.rb
lib/puppet/functions/reverse_each.rb
# frozen_string_literal: true # Reverses the order of the elements of something that is iterable and optionally runs a # [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) for each # element. # # This function takes one to two arguments: # # 1. An `Iterable` that the function will iterate over. # 2. An optional lambda, which the function calls for each element in the first argument. It must # request one parameter. # # @example Using the `reverse_each` function # # ```puppet # $data.reverse_each |$parameter| { <PUPPET CODE BLOCK> } # ``` # # or # # ```puppet # $reverse_data = $data.reverse_each # ``` # # or # # ```puppet # reverse_each($data) |$parameter| { <PUPPET CODE BLOCK> } # ``` # # or # # ```puppet # $reverse_data = reverse_each($data) # ``` # # When no second argument is present, Puppet returns an `Iterable` that represents the reverse # order of its first argument. This allows methods on `Iterable` to be chained. # # When a lambda is given as the second argument, Puppet iterates the first argument in reverse # order and passes each value in turn to the lambda, then returns `undef`. # # @example Using the `reverse_each` function with an array and a one-parameter lambda # # ```puppet # # Puppet will log a notice for each of the three items # # in $data in reverse order. # $data = [1,2,3] # $data.reverse_each |$item| { notice($item) } # ``` # # When no second argument is present, Puppet returns a new `Iterable` which allows it to # be directly chained into another function that takes an `Iterable` as an argument. # # @example Using the `reverse_each` function chained with a `map` function. # # ```puppet # # For the array $data, return an array containing each # # value multiplied by 10 in reverse order # $data = [1,2,3] # $transformed_data = $data.reverse_each.map |$item| { $item * 10 } # # $transformed_data is set to [30,20,10] # ``` # # @example Using `reverse_each` function chained with a `map` in alternative syntax # # ```puppet # # For the array $data, return an array containing each # # value multiplied by 10 in reverse order # $data = [1,2,3] # $transformed_data = map(reverse_each($data)) |$item| { $item * 10 } # # $transformed_data is set to [30,20,10] # ``` # # @since 4.4.0 # Puppet::Functions.create_function(:reverse_each) do dispatch :reverse_each do param 'Iterable', :iterable end dispatch :reverse_each_block do param 'Iterable', :iterable block_param 'Callable[1,1]', :block end def reverse_each(iterable) # produces an Iterable Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable, true).reverse_each end def reverse_each_block(iterable, &block) Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable).reverse_each(&block) nil end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/call.rb
lib/puppet/functions/call.rb
# frozen_string_literal: true # Calls an arbitrary Puppet function by name. # # This function takes one mandatory argument and one or more optional arguments: # # 1. A string corresponding to a function name. # 2. Any number of arguments to be passed to the called function. # 3. An optional lambda, if the function being called supports it. # # This function can also be used to resolve a `Deferred` given as # the only argument to the function (does not accept arguments nor # a block). # # @example Using the `call` function # # ```puppet # $a = 'notice' # call($a, 'message') # ``` # # @example Using the `call` function with a lambda # # ```puppet # $a = 'each' # $b = [1,2,3] # call($a, $b) |$item| { # notify { $item: } # } # ``` # # The `call` function can be used to call either Ruby functions or Puppet language # functions. # # When used with `Deferred` values, the deferred value can either describe # a function call, or a dig into a variable. # # @example Resolving a deferred function call # # ```puppet # $d = Deferred('join', [[1,2,3], ':']) # A future call to join that joins the arguments 1,2,3 with ':' # notice($d.call()) # ``` # # Would notice the string "1:2:3". # # @example Resolving a deferred variable value with optional dig into its structure # # ```puppet # $d = Deferred('$facts', ['processors', 'count']) # notice($d.call()) # ``` # # Would notice the value of `$facts['processors']['count']` at the time when the `call` is made. # # * Deferred values supported since Puppet 6.0 # # @since 5.0.0 # Puppet::Functions.create_function(:call, Puppet::Functions::InternalFunction) do dispatch :call_impl_block do scope_param param 'String', :function_name repeated_param 'Any', :arguments optional_block_param end dispatch :call_deferred do scope_param param 'Deferred', :deferred end def call_impl_block(scope, function_name, *args, &block) # The call function must be able to call functions loaded by any loader visible from the calling scope. Puppet::Pops::Parser::EvaluatingParser.new.evaluator.external_call_function(function_name, args, scope, &block) end def call_deferred(scope, deferred) Puppet::Pops::Evaluator::DeferredResolver.resolve(deferred, scope.compiler) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/flatten.rb
lib/puppet/functions/flatten.rb
# frozen_string_literal: true # Returns a flat Array produced from its possibly deeply nested given arguments. # # One or more arguments of any data type can be given to this function. # The result is always a flat array representation where any nested arrays are recursively flattened. # # @example Typical use of `flatten()` # # ```puppet # flatten(['a', ['b', ['c']]]) # # Would return: ['a','b','c'] # ``` # # To flatten other kinds of iterables (for example hashes, or intermediate results like from a `reverse_each`) # first convert the result to an array using `Array($x)`, or `$x.convert_to(Array)`. See the `new` function # for details and options when performing a conversion. # # @example Flattening a Hash # # ```puppet # $hsh = { a => 1, b => 2} # # # -- without conversion # $hsh.flatten() # # Would return [{a => 1, b => 2}] # # # -- with conversion # $hsh.convert_to(Array).flatten() # # Would return [a,1,b,2] # # flatten(Array($hsh)) # # Would also return [a,1,b,2] # ``` # # @example Flattening and concatenating at the same time # # ```puppet # $a1 = [1, [2, 3]] # $a2 = [[4,[5,6]] # $x = 7 # flatten($a1, $a2, $x) # # would return [1,2,3,4,5,6,7] # ``` # # @example Transforming to Array if not already an Array # # ```puppet # flatten(42) # # Would return [42] # # flatten([42]) # # Would also return [42] # ``` # # @since 5.5.0 support for flattening and concatenating at the same time # Puppet::Functions.create_function(:flatten) do dispatch :flatten_args do repeated_param 'Any', :args end def flatten_args(*args) args.flatten() end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/with.rb
lib/puppet/functions/with.rb
# frozen_string_literal: true # Calls a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # with the given arguments and returns the result. # # Since a lambda's scope is # [local](https://puppet.com/docs/puppet/latest/lang_lambdas.html#lambda-scope) # to the lambda, you can use the `with` function to create private blocks of code within a # class using variables whose values cannot be accessed outside of the lambda. # # @example Using `with` # # ```puppet # # Concatenate three strings into a single string formatted as a list. # $fruit = with("apples", "oranges", "bananas") |$x, $y, $z| { # "${x}, ${y}, and ${z}" # } # $check_var = $x # # $fruit contains "apples, oranges, and bananas" # # $check_var is undefined, as the value of $x is local to the lambda. # ``` # # @since 4.0.0 # Puppet::Functions.create_function(:with) do dispatch :with do repeated_param 'Any', :arg block_param end def with(*args) yield(*args) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/round.rb
lib/puppet/functions/round.rb
# frozen_string_literal: true # Returns an `Integer` value rounded to the nearest value. # Takes a single `Numeric` value as an argument. # # @example 'rounding a value' # # ```puppet # notice(round(2.9)) # would notice 3 # notice(round(2.1)) # would notice 2 # notice(round(-2.9)) # would notice -3 # ``` # Puppet::Functions.create_function(:round) do dispatch :on_numeric do param 'Numeric', :val end def on_numeric(x) if x > 0 Integer(x + 0.5) else Integer(x - 0.5) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/all.rb
lib/puppet/functions/all.rb
# frozen_string_literal: true # Runs a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # repeatedly using each value in a data structure until the lambda returns a non "truthy" value which # makes the function return `false`, or if the end of the iteration is reached, `true` is returned. # # This function takes two mandatory arguments, in this order: # # 1. An array, hash, or other iterable object that the function will iterate over. # 2. A lambda, which the function calls for each element in the first argument. It can # request one or two parameters. # # @example Using the `all` function # # `$data.all |$parameter| { <PUPPET CODE BLOCK> }` # # or # # `all($data) |$parameter| { <PUPPET CODE BLOCK> }` # # @example Using the `all` function with an Array and a one-parameter lambda # # ```puppet # # For the array $data, run a lambda that checks that all values are multiples of 10 # $data = [10, 20, 30] # notice $data.all |$item| { $item % 10 == 0 } # ``` # # Would notice `true`. # # When the first argument is a `Hash`, Puppet passes each key and value pair to the lambda # as an array in the form `[key, value]`. # # @example Using the `all` function with a `Hash` and a one-parameter lambda # # ```puppet # # For the hash $data, run a lambda using each item as a key-value array # $data = { 'a_0'=> 10, 'b_1' => 20 } # notice $data.all |$item| { $item[1] % 10 == 0 } # ``` # # Would notice `true` if all values in the hash are multiples of 10. # # When the lambda accepts two arguments, the first argument gets the index in an array # or the key from a hash, and the second argument the value. # # # @example Using the `all` function with a hash and a two-parameter lambda # # ```puppet # # Check that all values are a multiple of 10 and keys start with 'abc' # $data = {abc_123 => 10, abc_42 => 20, abc_blue => 30} # notice $data.all |$key, $value| { $value % 10 == 0 and $key =~ /^abc/ } # ``` # # Would notice `true`. # # For an general examples that demonstrates iteration, see the Puppet # [iteration](https://puppet.com/docs/puppet/latest/lang_iteration.html) # documentation. # # @since 5.2.0 # Puppet::Functions.create_function(:all) do dispatch :all_Hash_2 do param 'Hash[Any, Any]', :hash block_param 'Callable[2,2]', :block end dispatch :all_Hash_1 do param 'Hash[Any, Any]', :hash block_param 'Callable[1,1]', :block end dispatch :all_Enumerable_2 do param 'Iterable', :enumerable block_param 'Callable[2,2]', :block end dispatch :all_Enumerable_1 do param 'Iterable', :enumerable block_param 'Callable[1,1]', :block end def all_Hash_1(hash) hash.each_pair.all? { |x| yield(x) } end def all_Hash_2(hash) hash.each_pair.all? { |x, y| yield(x, y) } end def all_Enumerable_1(enumerable) Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable).all? { |e| yield(e) } end def all_Enumerable_2(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? enum.all? { |entry| yield(*entry) } else enum.each_with_index { |e, i| return false unless yield(i, e) } true end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/authconfig.rb
lib/puppet/network/authconfig.rb
# frozen_string_literal: true module Puppet class Network::AuthConfig def self.authprovider_class=(_) # legacy auth is not supported, ignore end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/format.rb
lib/puppet/network/format.rb
# frozen_string_literal: true require_relative '../../puppet/confiner' # A simple class for modeling encoding formats for moving # instances around the network. class Puppet::Network::Format include Puppet::Confiner attr_reader :name, :mime attr_accessor :intern_method, :render_method, :intern_multiple_method, :render_multiple_method, :weight, :required_methods, :extension, :charset def init_attribute(name, default) value = @options.delete(name) value = default if value.nil? send(name.to_s + "=", value) end def initialize(name, options = {}, &block) @name = name.to_s.downcase.intern @options = options # This must be done early the values can be used to set required_methods define_method_names method_list = { :intern_method => "from_#{name}", :intern_multiple_method => "from_multiple_#{name}", :render_multiple_method => "to_multiple_#{name}", :render_method => "to_#{name}" } init_attribute(:mime, "text/#{name}") init_attribute(:weight, 5) init_attribute(:required_methods, method_list.keys) init_attribute(:extension, name.to_s) init_attribute(:charset, nil) method_list.each do |method, value| init_attribute(method, value) end raise ArgumentError, _("Unsupported option(s) %{options_list}") % { options_list: @options.keys } unless @options.empty? @options = nil instance_eval(&block) if block_given? end def intern(klass, text) return klass.send(intern_method, text) if klass.respond_to?(intern_method) raise NotImplementedError, "#{klass} does not respond to #{intern_method}; can not intern instances from #{mime}" end def intern_multiple(klass, text) return klass.send(intern_multiple_method, text) if klass.respond_to?(intern_multiple_method) raise NotImplementedError, "#{klass} does not respond to #{intern_multiple_method}; can not intern multiple instances from #{mime}" end def mime=(mime) @mime = mime.to_s.downcase end def render(instance) return instance.send(render_method) if instance.respond_to?(render_method) raise NotImplementedError, "#{instance.class} does not respond to #{render_method}; can not render instances to #{mime}" end def render_multiple(instances) # This method implicitly assumes that all instances are of the same type. return instances[0].class.send(render_multiple_method, instances) if instances[0].class.respond_to?(render_multiple_method) raise NotImplementedError, _("%{klass} does not respond to %{method}; can not render multiple instances to %{mime}") % { klass: instances[0].class, method: render_multiple_method, mime: mime } end def required_methods_present?(klass) [:intern_method, :intern_multiple_method, :render_multiple_method].each do |name| return false unless required_method_present?(name, klass, :class) end return false unless required_method_present?(:render_method, klass, :instance) true end def supported?(klass) suitable? and required_methods_present?(klass) end def to_s "Puppet::Network::Format[#{name}]" end private def define_method_names @intern_method = "from_#{name}" @render_method = "to_#{name}" @intern_multiple_method = "from_multiple_#{name}" @render_multiple_method = "to_multiple_#{name}" end def required_method_present?(name, klass, type) return true unless required_methods.include?(name) method = send(name) (type == :class ? klass.respond_to?(method) : klass.method_defined?(method)) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/format_support.rb
lib/puppet/network/format_support.rb
# frozen_string_literal: true require_relative '../../puppet/network/format_handler' # Provides network serialization support when included # @api public module Puppet::Network::FormatSupport def self.included(klass) klass.extend(ClassMethods) end module ClassMethods def convert_from(format, data) get_format(format).intern(self, data) rescue => err # TRANSLATORS "intern" is a function name and should not be translated raise Puppet::Network::FormatHandler::FormatError, _("Could not intern from %{format}: %{err}") % { format: format, err: err }, err.backtrace end def convert_from_multiple(format, data) get_format(format).intern_multiple(self, data) rescue => err # TRANSLATORS "intern_multiple" is a function name and should not be translated raise Puppet::Network::FormatHandler::FormatError, _("Could not intern_multiple from %{format}: %{err}") % { format: format, err: err }, err.backtrace end def render_multiple(format, instances) get_format(format).render_multiple(instances) rescue => err # TRANSLATORS "render_multiple" is a function name and should not be translated raise Puppet::Network::FormatHandler::FormatError, _("Could not render_multiple to %{format}: %{err}") % { format: format, err: err }, err.backtrace end def default_format supported_formats[0] end def support_format?(name) Puppet::Network::FormatHandler.format(name).supported?(self) end def supported_formats result = format_handler.formats.collect do |f| format_handler.format(f) end.find_all do |f| f.supported?(self) end.sort do |a, b| # It's an inverse sort -- higher weight formats go first. b.weight <=> a.weight end result = put_preferred_format_first(result).map(&:name) Puppet.debug { "#{friendly_name} supports formats: #{result.join(' ')}" } result end # @api private def get_format(format_name) format_handler.format_for(format_name) end private def format_handler Puppet::Network::FormatHandler end def friendly_name if respond_to? :indirection indirection.name else self end end def put_preferred_format_first(list) preferred_format = Puppet.settings[:preferred_serialization_format].to_s preferred = list.select { |format| format.mime.end_with?(preferred_format) } if preferred.empty? Puppet.debug { "Value of 'preferred_serialization_format' (#{preferred_format}) is invalid for #{friendly_name}, using default (#{list.first.name})" } else list = preferred + list.reject { |format| format.mime.end_with?(preferred_format) } end list end end def to_msgpack(*args) to_data_hash.to_msgpack(*args) end # @deprecated, use to_json def to_pson(*args) to_data_hash.to_pson(*args) end def to_json(*args) Puppet::Util::Json.dump(to_data_hash, *args) end def render(format = nil) format ||= self.class.default_format self.class.get_format(format).render(self) rescue => err # TRANSLATORS "render" is a function name and should not be translated raise Puppet::Network::FormatHandler::FormatError, _("Could not render to %{format}: %{err}") % { format: format, err: err }, err.backtrace end def mime(format = nil) format ||= self.class.default_format self.class.get_format(format).mime rescue => err # TRANSLATORS "mime" is a function name and should not be translated raise Puppet::Network::FormatHandler::FormatError, _("Could not mime to %{format}: %{err}") % { format: format, err: err }, err.backtrace end def support_format?(name) self.class.support_format?(name) end # @comment Document to_data_hash here as it is called as a hook from to_msgpack if it exists # @!method to_data_hash(*args) # @api public # @abstract # This method may be implemented to return a hash object that is used for serializing. # The object returned by this method should contain all the info needed to instantiate it again. # If the method exists it will be called from to_msgpack and other serialization methods. # @return [Hash] end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http.rb
lib/puppet/network/http.rb
# frozen_string_literal: true # This module is used to handle puppet REST requests in puppetserver. module Puppet::Network::HTTP HEADER_ENABLE_PROFILING = "X-Puppet-Profiling" HEADER_PUPPET_VERSION = "X-Puppet-Version" SERVER_URL_PREFIX = "/puppet" SERVER_URL_VERSIONS = "v3" MASTER_URL_PREFIX = SERVER_URL_PREFIX MASTER_URL_VERSIONS = SERVER_URL_VERSIONS CA_URL_PREFIX = "/puppet-ca" CA_URL_VERSIONS = "v1" require_relative '../../puppet/network/authconfig' require_relative '../../puppet/network/authorization' require_relative 'http/issues' require_relative 'http/error' require_relative 'http/route' require_relative 'http/api' require_relative 'http/api/master' require_relative 'http/api/master/v3' require_relative 'http/handler' require_relative 'http/response' require_relative 'http/request' require_relative 'http/memory_response' end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/uri.rb
lib/puppet/network/uri.rb
# frozen_string_literal: true # This module holds funtions for network URI's module Puppet::Network::Uri # Mask credentials in given URI or address as string. Resulting string will # contain '***' in place of password. It will only be replaced if actual # password is given. # # @param uri [URI|String] an uri or address to be masked # @return [String] a masked url def mask_credentials(uri) if uri.is_a? URI uri = uri.dup else uri = URI.parse(uri) end uri.password = '***' unless uri.password.nil? uri.to_s end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http_pool.rb
lib/puppet/network/http_pool.rb
# frozen_string_literal: true require_relative '../../puppet/network/http/connection' module Puppet::Network; end # This module is deprecated. # # @api public # @deprecated Use {Puppet::HTTP::Client} instead. # module Puppet::Network::HttpPool @http_client_class = Puppet::Network::HTTP::Connection def self.http_client_class @http_client_class end def self.http_client_class=(klass) @http_client_class = klass end # Retrieve a connection for the given host and port. # # @param host [String] The hostname to connect to # @param port [Integer] The port on the host to connect to # @param use_ssl [Boolean] Whether to use an SSL connection # @param verify_peer [Boolean] Whether to verify the peer credentials, if possible. Verification will not take place if the CA certificate is missing. # @return [Puppet::Network::HTTP::Connection] # # @deprecated Use {Puppet.runtime[:http]} instead. # @api public # def self.http_instance(host, port, use_ssl = true, verify_peer = true) Puppet.warn_once('deprecations', self, "The method 'Puppet::Network::HttpPool.http_instance' is deprecated. Use Puppet.runtime[:http] instead") if verify_peer verifier = Puppet::SSL::Verifier.new(host, nil) else ssl = Puppet::SSL::SSLProvider.new verifier = Puppet::SSL::Verifier.new(host, ssl.create_insecure_context) end http_client_class.new(host, port, use_ssl: use_ssl, verifier: verifier) end # Retrieve a connection for the given host and port. # # @param host [String] The host to connect to # @param port [Integer] The port to connect to # @param use_ssl [Boolean] Whether to use SSL, defaults to `true`. # @param ssl_context [Puppet::SSL:SSLContext, nil] The ssl context to use # when making HTTPS connections. Required when `use_ssl` is `true`. # @return [Puppet::Network::HTTP::Connection] # # @deprecated Use {Puppet.runtime[:http]} instead. # @api public # def self.connection(host, port, use_ssl: true, ssl_context: nil) Puppet.warn_once('deprecations', self, "The method 'Puppet::Network::HttpPool.connection' is deprecated. Use Puppet.runtime[:http] instead") if use_ssl unless ssl_context # TRANSLATORS 'ssl_context' is an argument and should not be translated raise ArgumentError, _("An ssl_context is required when connecting to 'https://%{host}:%{port}'") % { host: host, port: port } end verifier = Puppet::SSL::Verifier.new(host, ssl_context) http_client_class.new(host, port, use_ssl: true, verifier: verifier) else if ssl_context # TRANSLATORS 'ssl_context' is an argument and should not be translated Puppet.warning(_("An ssl_context is unnecessary when connecting to 'http://%{host}:%{port}' and will be ignored") % { host: host, port: port }) end http_client_class.new(host, port, use_ssl: false) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/client_request.rb
lib/puppet/network/client_request.rb
# frozen_string_literal: true module Puppet::Network # :nodoc: # A struct-like class for passing around a client request. It's mostly # just used for validation and authorization. class ClientRequest attr_accessor :name, :ip, :authenticated, :handler, :method def authenticated? authenticated end # A common way of talking about the full call. Individual servers # are responsible for setting the values correctly, but this common # format makes it possible to check rights. def call raise ArgumentError, _("Request is not set up; cannot build call") unless handler and method [handler, method].join(".") end def initialize(name, ip, authenticated) @name = name @ip = ip @authenticated = authenticated end def to_s "#{name}(#{ip})" end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/authorization.rb
lib/puppet/network/authorization.rb
# frozen_string_literal: true module Puppet::Network module Authorization class << self # This method is deprecated and will be removed in a future release. def authconfigloader_class=(klass) @authconfigloader_class = klass end # Verify something external to puppet is authorizing REST requests, so # we don't fail insecurely due to misconfiguration. def check_external_authorization(method, path) if @authconfigloader_class.nil? message = "Forbidden request: #{path} (method #{method})" raise Puppet::Network::HTTP::Error::HTTPNotAuthorizedError.new(message, Puppet::Network::HTTP::Issues::FAILED_AUTHORIZATION) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/format_handler.rb
lib/puppet/network/format_handler.rb
# frozen_string_literal: true require 'yaml' require_relative '../../puppet/network' require_relative '../../puppet/network/format' module Puppet::Network::FormatHandler class FormatError < Puppet::Error; end ALL_MEDIA_TYPES = '*/*' @formats = {} def self.create(*args, &block) instance = Puppet::Network::Format.new(*args, &block) @formats[instance.name] = instance instance end def self.create_serialized_formats(name, options = {}, &block) ["application/x-#{name}", "application/#{name}", "text/x-#{name}", "text/#{name}"].each { |mime_type| create name, { :mime => mime_type }.update(options), &block } end def self.format(name) @formats[name.to_s.downcase.intern] end def self.format_for(name) name = format_to_canonical_name(name) format(name) end def self.format_by_extension(ext) @formats.each do |_name, format| return format if format.extension == ext end nil end # Provide a list of all formats. def self.formats @formats.keys end # Return a format capable of handling the provided mime type. def self.mime(mimetype) mimetype = mimetype.to_s.downcase @formats.values.find { |format| format.mime == mimetype } end # Return a format name given: # * a format name # * a mime-type # * a format instance def self.format_to_canonical_name(format) case format when Puppet::Network::Format out = format when %r{\w+/\w+} out = mime(format) else out = format(format) end if out.nil? raise ArgumentError, _("No format matches the given format name or mime-type (%{format})") % { format: format } end out.name end # Determine which of the accepted formats should be used given what is supported. # # @param accepted [Array<String, Symbol>] the accepted formats in a form a # that generally conforms to an HTTP Accept header. Any quality specifiers # are ignored and instead the formats are simply in strict preference order # (most preferred is first) # @param supported [Array<Symbol>] the names of the supported formats (the # most preferred format is first) # @return [Array<Puppet::Network::Format>] the most suitable formats that # are both accepted and supported # @api private def self.most_suitable_formats_for(accepted, supported) accepted.collect do |format| format.to_s.sub(/;q=.*$/, '') end.filter_map do |format| if format == ALL_MEDIA_TYPES supported.first else format_to_canonical_name_or_nil(format) end end.find_all do |format| supported.include?(format) end.collect do |format| format_for(format) end end # @api private def self.format_to_canonical_name_or_nil(format) format_to_canonical_name(format) rescue ArgumentError nil end end require_relative '../../puppet/network/formats'
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/formats.rb
lib/puppet/network/formats.rb
# frozen_string_literal: true require_relative '../../puppet/network/format_handler' require_relative '../../puppet/util/json' Puppet::Network::FormatHandler.create_serialized_formats(:msgpack, :weight => 20, :mime => "application/x-msgpack", :required_methods => [:render_method, :intern_method], :intern_method => :from_data_hash) do confine :feature => :msgpack def intern(klass, text) data = MessagePack.unpack(text) return data if data.is_a?(klass) klass.from_data_hash(data) end def intern_multiple(klass, text) MessagePack.unpack(text).collect do |data| klass.from_data_hash(data) end end def render_multiple(instances) instances.to_msgpack end end Puppet::Network::FormatHandler.create_serialized_formats(:yaml) do def allowed_yaml_classes @allowed_yaml_classes ||= [ Puppet::Node::Facts, Puppet::Node, Puppet::Transaction::Report, Puppet::Resource, Puppet::Resource::Catalog ] end def intern(klass, text) data = Puppet::Util::Yaml.safe_load(text, allowed_yaml_classes) data_to_instance(klass, data) rescue Puppet::Util::Yaml::YamlLoadError => e raise Puppet::Network::FormatHandler::FormatError, _("Serialized YAML did not contain a valid instance of %{klass}: %{message}") % { klass: klass, message: e.message } end def intern_multiple(klass, text) data = Puppet::Util::Yaml.safe_load(text, allowed_yaml_classes) unless data.respond_to?(:collect) raise Puppet::Network::FormatHandler::FormatError, _("Serialized YAML did not contain a collection of instances when calling intern_multiple") end data.collect do |datum| data_to_instance(klass, datum) end rescue Puppet::Util::Yaml::YamlLoadError => e raise Puppet::Network::FormatHandler::FormatError, _("Serialized YAML did not contain a valid instance of %{klass}: %{message}") % { klass: klass, message: e.message } end def data_to_instance(klass, data) return data if data.is_a?(klass) unless data.is_a? Hash raise Puppet::Network::FormatHandler::FormatError, _("Serialized YAML did not contain a valid instance of %{klass}") % { klass: klass } end klass.from_data_hash(data) end def render(instance) instance.to_yaml end # Yaml monkey-patches Array, so this works. def render_multiple(instances) instances.to_yaml end def supported?(klass) true end end Puppet::Network::FormatHandler.create(:s, :mime => "text/plain", :charset => Encoding::UTF_8, :extension => "txt") # By default, to_binary is called to render and from_binary called to intern. Note unlike # text-based formats (json, yaml, etc), we don't use to_data_hash for binary. Puppet::Network::FormatHandler.create(:binary, :mime => "application/octet-stream", :weight => 1, :required_methods => [:render_method, :intern_method]) do end # PSON is deprecated Puppet::Network::FormatHandler.create_serialized_formats(:pson, :weight => 10, :required_methods => [:render_method, :intern_method], :intern_method => :from_data_hash) do confine :feature => :pson def intern(klass, text) data_to_instance(klass, PSON.parse(text)) end def intern_multiple(klass, text) PSON.parse(text).collect do |data| data_to_instance(klass, data) end end # PSON monkey-patches Array, so this works. def render_multiple(instances) instances.to_pson end # If they pass class information, we want to ignore it. # This is required for compatibility with Puppet 3.x def data_to_instance(klass, data) d = data['data'] if data.is_a?(Hash) if d data = d end return data if data.is_a?(klass) klass.from_data_hash(data) end end Puppet::Network::FormatHandler.create_serialized_formats(:json, :mime => 'application/json', :charset => Encoding::UTF_8, :weight => 15, :required_methods => [:render_method, :intern_method], :intern_method => :from_data_hash) do def intern(klass, text) data_to_instance(klass, Puppet::Util::Json.load(text)) end def intern_multiple(klass, text) Puppet::Util::Json.load(text).collect do |data| data_to_instance(klass, data) end end def render_multiple(instances) Puppet::Util::Json.dump(instances) end # Unlike PSON, we do not need to unwrap the data envelope, because legacy 3.x agents # have never supported JSON def data_to_instance(klass, data) return data if data.is_a?(klass) klass.from_data_hash(data) end end # This is really only ever going to be used for Catalogs. Puppet::Network::FormatHandler.create_serialized_formats(:dot, :required_methods => [:render_method]) Puppet::Network::FormatHandler.create(:console, :mime => 'text/x-console-text', :weight => 0) do def json @json ||= Puppet::Network::FormatHandler.format(:json) end def render(datum) return datum if datum.is_a?(String) || datum.is_a?(Numeric) # Simple hash to table if datum.is_a?(Hash) && datum.keys.all? { |x| x.is_a?(String) || x.is_a?(Numeric) } output = ''.dup column_a = datum.empty? ? 2 : datum.map { |k, _v| k.to_s.length }.max + 2 datum.sort_by { |k, _v| k.to_s }.each do |key, value| output << key.to_s.ljust(column_a) output << json.render(value) .chomp.gsub(/\n */) { |x| x + (' ' * column_a) } output << "\n" end return output end # Print one item per line for arrays if datum.is_a? Array output = ''.dup datum.each do |item| output << item.to_s output << "\n" end return output end # ...or pretty-print the inspect outcome. Puppet::Util::Json.dump(datum, :pretty => true, :quirks_mode => true) end def render_multiple(data) data.collect(&:render).join("\n") end end Puppet::Network::FormatHandler.create(:flat, :mime => 'text/x-flat-text', :weight => 0) do def flatten_hash(hash) hash.each_with_object({}) do |(k, v), h| case v when Hash flatten_hash(v).map do |h_k, h_v| h["#{k}.#{h_k}"] = h_v end when Array v.each_with_index do |el, i| if el.is_a? Hash flatten_hash(el).map do |el_k, el_v| h["#{k}.#{i}.#{el_k}"] = el_v end else h["#{k}.#{i}"] = el end end else h[k] = v end end end def flatten_array(array) a = {} array.each_with_index do |el, i| if el.is_a? Hash flatten_hash(el).map do |el_k, el_v| a["#{i}.#{el_k}"] = el_v end else a[i.to_s] = el end end a end def construct_output(data) output = ''.dup data.each do |key, value| output << "#{key}=#{value}" output << "\n" end output end def render(datum) return datum if datum.is_a?(String) || datum.is_a?(Numeric) # Simple hash case datum when Hash data = flatten_hash(datum) return construct_output(data) when Array data = flatten_array(datum) return construct_output(data) end Puppet::Util::Json.dump(datum, :pretty => true, :quirks_mode => true) end def render_multiple(data) data.collect(&:render).join("\n") end end Puppet::Network::FormatHandler.create(:rich_data_json, mime: 'application/vnd.puppet.rich+json', charset: Encoding::UTF_8, weight: 30) do def intern(klass, text) Puppet.override({ :rich_data => true }) do data_to_instance(klass, Puppet::Util::Json.load(text)) end end def intern_multiple(klass, text) Puppet.override({ :rich_data => true }) do Puppet::Util::Json.load(text).collect do |data| data_to_instance(klass, data) end end end def render(instance) Puppet.override({ :rich_data => true }) do instance.to_json end end def render_multiple(instances) Puppet.override({ :rich_data => true }) do Puppet::Util::Json.dump(instances) end end def data_to_instance(klass, data) Puppet.override({ :rich_data => true }) do return data if data.is_a?(klass) klass.from_data_hash(data) end end def supported?(klass) klass == Puppet::Resource::Catalog && Puppet.lookup(:current_environment).rich_data? end end Puppet::Network::FormatHandler.create_serialized_formats(:rich_data_msgpack, mime: "application/vnd.puppet.rich+msgpack", weight: 35) do confine :feature => :msgpack def intern(klass, text) Puppet.override(rich_data: true) do data = MessagePack.unpack(text) return data if data.is_a?(klass) klass.from_data_hash(data) end end def intern_multiple(klass, text) Puppet.override(rich_data: true) do MessagePack.unpack(text).collect do |data| klass.from_data_hash(data) end end end def render_multiple(instances) Puppet.override(rich_data: true) do instances.to_msgpack end end def render(instance) Puppet.override(rich_data: true) do instance.to_msgpack end end def supported?(klass) suitable? && klass == Puppet::Resource::Catalog && Puppet.lookup(:current_environment).rich_data? end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/issues.rb
lib/puppet/network/http/issues.rb
# frozen_string_literal: true module Puppet::Network::HTTP::Issues NO_INDIRECTION_REMOTE_REQUESTS = :NO_INDIRECTION_REMOTE_REQUESTS HANDLER_NOT_FOUND = :HANDLER_NOT_FOUND RESOURCE_NOT_FOUND = :RESOURCE_NOT_FOUND ENVIRONMENT_NOT_FOUND = :ENVIRONMENT_NOT_FOUND RUNTIME_ERROR = :RUNTIME_ERROR MISSING_HEADER_FIELD = :MISSING_HEADER_FIELD UNSUPPORTED_FORMAT = :UNSUPPORTED_FORMAT UNSUPPORTED_METHOD = :UNSUPPORTED_METHOD FAILED_AUTHORIZATION = :FAILED_AUTHORIZATION UNSUPPORTED_MEDIA_TYPE = :UNSUPPORTED_MEDIA_TYPE end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/response.rb
lib/puppet/network/http/response.rb
# frozen_string_literal: true class Puppet::Network::HTTP::Response def initialize(handler, response) @handler = handler @response = response end def respond_with(code, type, body) format = Puppet::Network::FormatHandler.format_for(type) mime = format.mime charset = format.charset if charset if body.is_a?(String) && body.encoding != charset body.encode!(charset) end mime += "; charset=#{charset.name.downcase}" end @handler.set_content_type(@response, mime) @handler.set_response(@response, body, code) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/route.rb
lib/puppet/network/http/route.rb
# frozen_string_literal: true class Puppet::Network::HTTP::Route MethodNotAllowedHandler = lambda do |req, _res| raise Puppet::Network::HTTP::Error::HTTPMethodNotAllowedError.new("method #{req.method} not allowed for route #{req.path}", Puppet::Network::HTTP::Issues::UNSUPPORTED_METHOD) end NO_HANDLERS = [MethodNotAllowedHandler] attr_reader :path_matcher def self.path(path_matcher) new(path_matcher) end def initialize(path_matcher) @path_matcher = path_matcher @method_handlers = { :GET => NO_HANDLERS, :HEAD => NO_HANDLERS, :OPTIONS => NO_HANDLERS, :POST => NO_HANDLERS, :PUT => NO_HANDLERS, :DELETE => NO_HANDLERS } @chained = [] end def get(*handlers) @method_handlers[:GET] = handlers self end def head(*handlers) @method_handlers[:HEAD] = handlers self end def options(*handlers) @method_handlers[:OPTIONS] = handlers self end def post(*handlers) @method_handlers[:POST] = handlers self end def put(*handlers) @method_handlers[:PUT] = handlers self end def delete(*handlers) @method_handlers[:DELETE] = handlers self end def any(*handlers) @method_handlers.each do |method, _registered_handlers| @method_handlers[method] = handlers end self end def chain(*routes) @chained = routes self end def matches?(request) Puppet.debug { "Evaluating match for #{inspect}" } if match(request.routing_path) return true else Puppet.debug { "Did not match path (#{request.routing_path.inspect})" } end false end def process(request, response) handlers = @method_handlers[request.method.upcase.intern] || NO_HANDLERS handlers.each do |handler| handler.call(request, response) end subrequest = request.route_into(match(request.routing_path).to_s) chained_route = @chained.find { |route| route.matches?(subrequest) } if chained_route chained_route.process(subrequest, response) end end def inspect "Route #{@path_matcher.inspect}" end private def match(path) @path_matcher.match(path) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/api.rb
lib/puppet/network/http/api.rb
# frozen_string_literal: true class Puppet::Network::HTTP::API require_relative '../../../puppet/version' def self.not_found Puppet::Network::HTTP::Route .path(/.*/) .any(lambda do |req, _res| raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new("No route for #{req.method} #{req.path}", Puppet::Network::HTTP::Issues::HANDLER_NOT_FOUND) end) end def self.not_found_upgrade Puppet::Network::HTTP::Route .path(/.*/) .any(lambda do |_req, _res| raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new("Error: Invalid URL - Puppet expects requests that conform to the " \ "/puppet and /puppet-ca APIs.\n\n" \ "Note that Puppet 3 agents aren't compatible with this version; if you're " \ "running Puppet 3, you must either upgrade your agents to match the server " \ "or point them to a server running Puppet 3.\n\n" \ "Server Info:\n" \ " Puppet version: #{Puppet.version}\n" \ " Supported /puppet API versions: #{Puppet::Network::HTTP::SERVER_URL_VERSIONS}\n", Puppet::Network::HTTP::Issues::HANDLER_NOT_FOUND) end) end def self.server_routes server_prefix = Regexp.new("^#{Puppet::Network::HTTP::SERVER_URL_PREFIX}/") Puppet::Network::HTTP::Route.path(server_prefix) .any .chain(Puppet::Network::HTTP::API::Server::V3.routes, Puppet::Network::HTTP::API.not_found) end def self.master_routes server_routes end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/handler.rb
lib/puppet/network/http/handler.rb
# frozen_string_literal: true module Puppet::Network::HTTP end require_relative '../../../puppet/network/http' require_relative '../../../puppet/util/profiler' require_relative '../../../puppet/util/profiler/aggregate' require 'resolv' module Puppet::Network::HTTP::Handler include Puppet::Network::HTTP::Issues # These shouldn't be allowed to be set by clients # in the query string, for security reasons. DISALLOWED_KEYS = %w[node ip] def register(routes) # There's got to be a simpler way to do this, right? dupes = {} routes.each { |r| dupes[r.path_matcher] = (dupes[r.path_matcher] || 0) + 1 } dupes = dupes.filter_map { |pm, count| pm if count > 1 } if dupes.count > 0 raise ArgumentError, _("Given multiple routes with identical path regexes: %{regexes}") % { regexes: dupes.map(&:inspect).join(', ') } end @routes = routes Puppet.debug("Routes Registered:") @routes.each do |route| Puppet.debug(route.inspect) end end # Retrieve all headers from the http request, as a hash with the header names # (lower-cased) as the keys def headers(request) raise NotImplementedError end # The mime type is always passed to the `set_content_type` method, so # it is no longer necessary to retrieve the Format's mime type. # # @deprecated def format_to_mime(format) format.is_a?(Puppet::Network::Format) ? format.mime : format end # Create a generic puppet request from the implementation-specific request # created by the web server def make_generic_request(request) request_path = path(request) Puppet::Network::HTTP::Request.new( headers(request), params(request), http_method(request), request_path, # path request_path, # routing_path client_cert(request), body(request) ) end def with_request_profiling(request) profiler = configure_profiler(request.headers, request.params) Puppet::Util::Profiler.profile( _("Processed request %{request_method} %{request_path}") % { request_method: request.method, request_path: request.path }, [:http, request.method, request.path] ) do yield end ensure remove_profiler(profiler) if profiler end # handle an HTTP request def process(external_request, response) # The response_wrapper stores the response and modifies it as a side effect. # The caller will use the original response response_wrapper = Puppet::Network::HTTP::Response.new(self, response) request = make_generic_request(external_request) set_puppet_version_header(response) respond_to_errors(response_wrapper) do with_request_profiling(request) do find_route_or_raise(request).process(request, response_wrapper) end end end def respond_to_errors(response) yield rescue Puppet::Network::HTTP::Error::HTTPError => e Puppet.info(e.message) respond_with_http_error(response, e) rescue StandardError => e http_e = Puppet::Network::HTTP::Error::HTTPServerError.new(e) Puppet.err([http_e.message, *e.backtrace].join("\n")) respond_with_http_error(response, http_e) end def respond_with_http_error(response, exception) response.respond_with(exception.status, "application/json", exception.to_json) end def find_route_or_raise(request) route = @routes.find { |r| r.matches?(request) } route || raise(Puppet::Network::HTTP::Error::HTTPNotFoundError.new( _("No route for %{request} %{path}") % { request: request.method, path: request.path }, HANDLER_NOT_FOUND )) end def set_puppet_version_header(response) response[Puppet::Network::HTTP::HEADER_PUPPET_VERSION] = Puppet.version end # Set the response up, with the body and status. def set_response(response, body, status = 200) raise NotImplementedError end # Set the specified format as the content type of the response. def set_content_type(response, format) raise NotImplementedError end # resolve node name from peer's ip address # this is used when the request is unauthenticated def resolve_node(result) begin return Resolv.getname(result[:ip]) rescue => detail Puppet.err _("Could not resolve %{ip}: %{detail}") % { ip: result[:ip], detail: detail } end result[:ip] end private # methods to be overridden by the including web server class def http_method(request) raise NotImplementedError end def path(request) raise NotImplementedError end def request_key(request) raise NotImplementedError end def body(request) raise NotImplementedError end def params(request) raise NotImplementedError end def client_cert(request) raise NotImplementedError end def decode_params(params) params.select { |key, _| allowed_parameter?(key) }.each_with_object({}) do |ary, result| param, value = ary result[param.to_sym] = parse_parameter_value(param, value) end end def allowed_parameter?(name) !(name.nil? || name.empty? || DISALLOWED_KEYS.include?(name)) end def parse_parameter_value(param, value) if value.is_a?(Array) value.collect { |v| parse_primitive_parameter_value(v) } else parse_primitive_parameter_value(value) end end def parse_primitive_parameter_value(value) case value when "true" true when "false" false when /^\d+$/ Integer(value) when /^\d+\.\d+$/ value.to_f else value end end def configure_profiler(request_headers, request_params) if request_headers.has_key?(Puppet::Network::HTTP::HEADER_ENABLE_PROFILING.downcase) or Puppet[:profile] Puppet::Util::Profiler.add_profiler(Puppet::Util::Profiler::Aggregate.new(Puppet.method(:info), request_params.object_id)) end end def remove_profiler(profiler) profiler.shutdown Puppet::Util::Profiler.remove_profiler(profiler) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/connection.rb
lib/puppet/network/http/connection.rb
# frozen_string_literal: true require_relative '../../../puppet/http' # This will be raised if too many redirects happen for a given HTTP request class Puppet::Network::HTTP::RedirectionLimitExceededException < Puppet::Error; end # This class provides simple methods for issuing various types of HTTP # requests. It's interface is intended to mirror Ruby's Net::HTTP # object, but it provides a few important bits of additional # functionality. Notably: # # * Any HTTPS requests made using this class will use Puppet's SSL # certificate configuration for their authentication, and # * Provides some useful error handling for any SSL errors that occur # during a request. # # @deprecated Use {Puppet.runtime[:http]} # @api public class Puppet::Network::HTTP::Connection include Puppet::HTTP::ResponseConverter OPTION_DEFAULTS = { :use_ssl => true, :verifier => nil, :redirect_limit => 10, } # Creates a new HTTP client connection to `host`:`port`. # @param host [String] the host to which this client will connect to # @param port [Integer] the port to which this client will connect to # @param options [Hash] options influencing the properties of the created # connection, # @option options [Boolean] :use_ssl true to connect with SSL, false # otherwise, defaults to true # @option options [Puppet::SSL::Verifier] :verifier An object that will configure # any verification to do on the connection # @option options [Integer] :redirect_limit the number of allowed # redirections, defaults to 10 passing any other option in the options # hash results in a Puppet::Error exception # # @note the HTTP connection itself happens lazily only when {#request}, or # one of the {#get}, {#post}, {#delete}, {#head} or {#put} is called # @note The correct way to obtain a connection is to use one of the factory # methods on {Puppet::Network::HttpPool} # @api private def initialize(host, port, options = {}) unknown_options = options.keys - OPTION_DEFAULTS.keys raise Puppet::Error, _("Unrecognized option(s): %{opts}") % { opts: unknown_options.map(&:inspect).sort.join(', ') } unless unknown_options.empty? options = OPTION_DEFAULTS.merge(options) @use_ssl = options[:use_ssl] if @use_ssl unless options[:verifier].is_a?(Puppet::SSL::Verifier) raise ArgumentError, _("Expected an instance of Puppet::SSL::Verifier but was passed a %{klass}") % { klass: options[:verifier].class } end @verifier = options[:verifier] end @redirect_limit = options[:redirect_limit] @site = Puppet::HTTP::Site.new(@use_ssl ? 'https' : 'http', host, port) @client = Puppet.runtime[:http] end # The address to connect to. def address @site.host end # The port to connect to. def port @site.port end # Whether to use ssl def use_ssl? @site.use_ssl? end # @api private def verifier @verifier end # @!macro [new] common_options # @param options [Hash] options influencing the request made. Any # options not recognized by this class will be ignored - no error will # be thrown. # @option options [Hash{Symbol => String}] :basic_auth The basic auth # :username and :password to use for the request, :metric_id Ignored # by this class - used by Puppet Server only. The metric id by which # to track metrics on requests. # @param path [String] # @param headers [Hash{String => String}] # @!macro common_options # @api public def get(path, headers = {}, options = {}) headers ||= {} options[:ssl_context] ||= resolve_ssl_context options[:redirect_limit] ||= @redirect_limit with_error_handling do to_ruby_response(@client.get(to_url(path), headers: headers, options: options)) end end # @param path [String] # @param data [String] # @param headers [Hash{String => String}] # @!macro common_options # @api public def post(path, data, headers = nil, options = {}) headers ||= {} headers['Content-Type'] ||= "application/x-www-form-urlencoded" data ||= '' options[:ssl_context] ||= resolve_ssl_context options[:redirect_limit] ||= @redirect_limit with_error_handling do to_ruby_response(@client.post(to_url(path), data, headers: headers, options: options)) end end # @param path [String] # @param headers [Hash{String => String}] # @!macro common_options # @api public def head(path, headers = {}, options = {}) headers ||= {} options[:ssl_context] ||= resolve_ssl_context options[:redirect_limit] ||= @redirect_limit with_error_handling do to_ruby_response(@client.head(to_url(path), headers: headers, options: options)) end end # @param path [String] # @param headers [Hash{String => String}] # @!macro common_options # @api public def delete(path, headers = { 'Depth' => 'Infinity' }, options = {}) headers ||= {} options[:ssl_context] ||= resolve_ssl_context options[:redirect_limit] ||= @redirect_limit with_error_handling do to_ruby_response(@client.delete(to_url(path), headers: headers, options: options)) end end # @param path [String] # @param data [String] # @param headers [Hash{String => String}] # @!macro common_options # @api public def put(path, data, headers = nil, options = {}) headers ||= {} headers['Content-Type'] ||= "application/x-www-form-urlencoded" data ||= '' options[:ssl_context] ||= resolve_ssl_context options[:redirect_limit] ||= @redirect_limit with_error_handling do to_ruby_response(@client.put(to_url(path), data, headers: headers, options: options)) end end def request_get(*args, &block) path, headers = *args headers ||= {} options = { ssl_context: resolve_ssl_context, redirect_limit: @redirect_limit } ruby_response = nil @client.get(to_url(path), headers: headers, options: options) do |response| ruby_response = to_ruby_response(response) yield ruby_response if block_given? end ruby_response end def request_head(*args, &block) path, headers = *args headers ||= {} options = { ssl_context: resolve_ssl_context, redirect_limit: @redirect_limit } response = @client.head(to_url(path), headers: headers, options: options) ruby_response = to_ruby_response(response) yield ruby_response if block_given? ruby_response end def request_post(*args, &block) path, data, headers = *args headers ||= {} headers['Content-Type'] ||= "application/x-www-form-urlencoded" options = { ssl_context: resolve_ssl_context, redirect_limit: @redirect_limit } ruby_response = nil @client.post(to_url(path), data, headers: headers, options: options) do |response| ruby_response = to_ruby_response(response) yield ruby_response if block_given? end ruby_response end private # Resolve the ssl_context based on the verifier associated with this # connection or load the available set of certs and key on disk. # Don't try to bootstrap the agent, as we only want that to be triggered # when running `puppet ssl` or `puppet agent`. def resolve_ssl_context # don't need an ssl context for http connections return nil unless @site.use_ssl? # if our verifier has an ssl_context, use that ctx = @verifier.ssl_context return ctx if ctx # load available certs cert = Puppet::X509::CertProvider.new ssl = Puppet::SSL::SSLProvider.new begin password = cert.load_private_key_password ssl.load_context(certname: Puppet[:certname], password: password) rescue Puppet::SSL::SSLError => e Puppet.log_exception(e) # if we don't have cacerts, then create a root context that doesn't # trust anything. The old code used to fallback to VERIFY_NONE, # which we don't want to emulate. ssl.create_root_context(cacerts: []) end end def to_url(path) if path =~ %r{^https?://} # The old Connection class accepts a URL as the request path, and sends # it in "absolute-form" in the request line, e.g. GET https://puppet:8140/. # See https://httpwg.org/specs/rfc7230.html#absolute-form. It just so happens # to work because HTTP 1.1 servers are required to accept absolute-form even # though clients are only supposed to send them to proxies, so the proxy knows # what upstream server to CONNECT to. This method creates a URL using the # scheme/host/port that the connection was created with, and appends the path # and query portions of the absolute-form. The resulting request will use "origin-form" # as it should have done all along. abs_form = URI(path) url = URI("#{@site.addr}/#{normalize_path(abs_form.path)}") url.query = abs_form.query if abs_form.query url else URI("#{@site.addr}/#{normalize_path(path)}") end end def normalize_path(path) if path[0] == '/' path[1..] else path end end def with_error_handling(&block) yield rescue Puppet::HTTP::TooManyRedirects => e raise Puppet::Network::HTTP::RedirectionLimitExceededException.new(_("Too many HTTP redirections for %{host}:%{port}") % { host: @host, port: @port }, e) rescue Puppet::HTTP::HTTPError => e Puppet.log_exception(e, e.message) case e.cause when Net::OpenTimeout, Net::ReadTimeout, Net::HTTPError, EOFError raise e.cause else raise e end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/memory_response.rb
lib/puppet/network/http/memory_response.rb
# frozen_string_literal: true class Puppet::Network::HTTP::MemoryResponse attr_reader :code, :type, :body def initialize @body = ''.dup end def respond_with(code, type, body) @code = code @type = type @body += body end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/request.rb
lib/puppet/network/http/request.rb
# frozen_string_literal: true # This class is effectively public API, because a Request object is passed as a # parameter to the current Handler subclass. Puppetserver implements its own # Handler # https://github.com/puppetlabs/puppetserver/blob/8.3.0/src/ruby/puppetserver-lib/puppet/server/network/http/handler.rb#L9 # and the Request object is passed to its Handler#body method # https://github.com/puppetlabs/puppetserver/blob/8.3.0/src/ruby/puppetserver-lib/puppet/server/network/http/handler.rb#L36 Puppet::Network::HTTP::Request = Struct.new(:headers, :params, :method, :path, :routing_path, :client_cert, :body) do # rubocop:disable Lint/StructNewOverride def self.from_hash(hash) symbol_members = members.collect(&:intern) unknown = hash.keys - symbol_members if unknown.empty? new(hash[:headers] || {}, hash[:params] || {}, hash[:method] || "GET", hash[:path], hash[:routing_path] || hash[:path], hash[:client_cert], hash[:body]) else raise ArgumentError, _("Unknown arguments: %{args}") % { args: unknown.collect(&:inspect).join(', ') } end end def route_into(prefix) self.class.new(headers, params, method, path, routing_path.sub(prefix, ''), client_cert, body) end def formatter header = headers['content-type'] if header header.gsub!(/\s*;.*$/, '') # strip any charset format = Puppet::Network::FormatHandler.mime(header) return format if valid_network_format?(format) # TRANSLATORS "mime-type" is a keyword and should not be translated raise Puppet::Network::HTTP::Error::HTTPUnsupportedMediaTypeError.new( _("Client sent a mime-type (%{header}) that doesn't correspond to a format we support") % { header: headers['content-type'] }, Puppet::Network::HTTP::Issues::UNSUPPORTED_MEDIA_TYPE ) end raise Puppet::Network::HTTP::Error::HTTPBadRequestError.new( _("No Content-Type header was received, it isn't possible to unserialize the request"), Puppet::Network::HTTP::Issues::MISSING_HEADER_FIELD ) end def response_formatters_for(supported_formats, default_accepted_formats = nil) accepted_formats = headers['accept'] || default_accepted_formats if accepted_formats.nil? raise Puppet::Network::HTTP::Error::HTTPBadRequestError.new(_("Missing required Accept header"), Puppet::Network::HTTP::Issues::MISSING_HEADER_FIELD) end formats = Puppet::Network::FormatHandler.most_suitable_formats_for( accepted_formats.split(/\s*,\s*/), supported_formats ) formats.find_all do |format| # we are only passed supported_formats that are suitable # and whose klass implements the required_methods valid_network_format?(format) end return formats unless formats.empty? raise Puppet::Network::HTTP::Error::HTTPNotAcceptableError.new( _("No supported formats are acceptable (Accept: %{accepted_formats})") % { accepted_formats: accepted_formats }, Puppet::Network::HTTP::Issues::UNSUPPORTED_FORMAT ) end private def valid_network_format?(format) # YAML in network requests is not supported. See http://links.puppet.com/deprecate_yaml_on_network !format.nil? && format.name != :yaml && format.name != :b64_zlib_yaml end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/error.rb
lib/puppet/network/http/error.rb
# frozen_string_literal: true require_relative '../../../puppet/util/json' module Puppet::Network::HTTP::Error Issues = Puppet::Network::HTTP::Issues class HTTPError < Exception # rubocop:disable Lint/InheritException attr_reader :status, :issue_kind def initialize(message, status, issue_kind) super(message) @status = status @issue_kind = issue_kind end def to_json Puppet::Util::Json.dump({ :message => message, :issue_kind => @issue_kind }) end end class HTTPNotAcceptableError < HTTPError CODE = 406 def initialize(message, issue_kind = Issues::RUNTIME_ERROR) super(_("Not Acceptable: %{message}") % { message: message }, CODE, issue_kind) end end class HTTPNotFoundError < HTTPError CODE = 404 def initialize(message, issue_kind = Issues::RUNTIME_ERROR) super(_("Not Found: %{message}") % { message: message }, CODE, issue_kind) end end class HTTPNotAuthorizedError < HTTPError CODE = 403 def initialize(message, issue_kind = Issues::RUNTIME_ERROR) super(_("Not Authorized: %{message}") % { message: message }, CODE, issue_kind) end end class HTTPBadRequestError < HTTPError CODE = 400 def initialize(message, issue_kind = Issues::RUNTIME_ERROR) super(_("Bad Request: %{message}") % { message: message }, CODE, issue_kind) end end class HTTPMethodNotAllowedError < HTTPError CODE = 405 def initialize(message, issue_kind = Issues::RUNTIME_ERROR) super(_("Method Not Allowed: %{message}") % { message: message }, CODE, issue_kind) end end class HTTPUnsupportedMediaTypeError < HTTPError CODE = 415 def initialize(message, issue_kind = Issues::RUNTIME_ERROR) super(_("Unsupported Media Type: %{message}") % { message: message }, CODE, issue_kind) end end class HTTPServerError < HTTPError CODE = 500 def initialize(original_error, issue_kind = Issues::RUNTIME_ERROR) super(_("Server Error: %{message}") % { message: original_error.message }, CODE, issue_kind) end def to_json Puppet::Util::Json.dump({ :message => message, :issue_kind => @issue_kind }) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/api/master.rb
lib/puppet/network/http/api/master.rb
# frozen_string_literal: true require_relative '../../../../puppet/network/http/api/server' Puppet::Network::HTTP::API::Master = Puppet::Network::HTTP::API::Server
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/api/indirection_type.rb
lib/puppet/network/http/api/indirection_type.rb
# frozen_string_literal: true class Puppet::Network::HTTP::API::IndirectionType INDIRECTION_TYPE_MAP = { "certificate" => :ca, "certificate_request" => :ca, "certificate_revocation_list" => :ca, "certificate_status" => :ca } def self.master_url_prefix "#{Puppet::Network::HTTP::MASTER_URL_PREFIX}/v3" end def self.ca_url_prefix "#{Puppet::Network::HTTP::CA_URL_PREFIX}/v1" end def self.type_for(indirection) INDIRECTION_TYPE_MAP[indirection] || :master end def self.url_prefix_for(indirection_name) case type_for(indirection_name) when :ca ca_url_prefix when :master master_url_prefix else raise ArgumentError, _("Not a valid indirection type") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/api/server.rb
lib/puppet/network/http/api/server.rb
# frozen_string_literal: true module Puppet module Network module HTTP class API module Server end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/api/indirected_routes.rb
lib/puppet/network/http/api/indirected_routes.rb
# frozen_string_literal: true require_relative '../../../../puppet/network/http/api/indirection_type' class Puppet::Network::HTTP::API::IndirectedRoutes # How we map http methods and the indirection name in the URI # to an indirection method. METHOD_MAP = { "GET" => { :plural => :search, :singular => :find }, "POST" => { :singular => :find, }, "PUT" => { :singular => :save }, "DELETE" => { :singular => :destroy }, "HEAD" => { :singular => :head } } IndirectionType = Puppet::Network::HTTP::API::IndirectionType def self.routes Puppet::Network::HTTP::Route.path(/.*/).any(new) end # Handle an HTTP request. The request has already been authenticated prior # to calling this method. def call(request, response) indirection, method, key, params = uri2indirection(request.method, request.path, request.params) certificate = request.client_cert unless indirection.allow_remote_requests? # TODO: should we tell the user we found an indirection but it doesn't # allow remote requests, or just pretend there's no handler at all? what # are the security implications for the former? raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new(_("No handler for %{indirection}") % { indirection: indirection.name }, :NO_INDIRECTION_REMOTE_REQUESTS) end overrides = { trusted_information: Puppet::Context::TrustedInformation.remote(params[:authenticated], params[:node], certificate), } if params[:environment] overrides[:current_environment] = params[:environment] end Puppet.override(overrides) do send("do_#{method}", indirection, key, params, request, response) end end def uri2indirection(http_method, uri, params) # the first field is always nil because of the leading slash, indirection_type, version, indirection_name, key = uri.split("/", 5)[1..] url_prefix = "/#{indirection_type}/#{version}" environment = params.delete(:environment) if indirection_name !~ /^\w+$/ raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("The indirection name must be purely alphanumeric, not '%{indirection_name}'") % { indirection_name: indirection_name } end # this also depluralizes the indirection_name if it is a search method = indirection_method(http_method, indirection_name) # check whether this indirection matches the prefix and version in the # request if url_prefix != IndirectionType.url_prefix_for(indirection_name) raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("Indirection '%{indirection_name}' does not match url prefix '%{url_prefix}'") % { indirection_name: indirection_name, url_prefix: url_prefix } end indirection = Puppet::Indirector::Indirection.instance(indirection_name.to_sym) unless indirection raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new( _("Could not find indirection '%{indirection_name}'") % { indirection_name: indirection_name }, Puppet::Network::HTTP::Issues::HANDLER_NOT_FOUND ) end unless environment raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("An environment parameter must be specified") end unless Puppet::Node::Environment.valid_name?(environment) raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("The environment must be purely alphanumeric, not '%{environment}'") % { environment: environment } end configured_environment = Puppet.lookup(:environments).get(environment) unless configured_environment.nil? configured_environment = configured_environment.override_from_commandline(Puppet.settings) params[:environment] = configured_environment end if configured_environment.nil? && indirection.terminus.require_environment? raise Puppet::Network::HTTP::Error::HTTPNotFoundError, _("Could not find environment '%{environment}'") % { environment: environment } end params.delete(:bucket_path) if key == "" or key.nil? raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("No request key specified in %{uri}") % { uri: uri } end [indirection, method, key, params] end private # Execute our find. def do_find(indirection, key, params, request, response) result = indirection.find(key, params) unless result raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new(_("Could not find %{value0} %{key}") % { value0: indirection.name, key: key }, Puppet::Network::HTTP::Issues::RESOURCE_NOT_FOUND) end rendered_result = result rendered_format = first_response_formatter_for(indirection.model, request, key) do |format| if result.respond_to?(:render) Puppet::Util::Profiler.profile(_("Rendered result in %{format}") % { format: format }, [:http, :v3_render, format]) do rendered_result = result.render(format) end end end Puppet::Util::Profiler.profile(_("Sent response"), [:http, :v3_response]) do response.respond_with(200, rendered_format, rendered_result) end end # Execute our head. def do_head(indirection, key, params, request, response) unless indirection.head(key, params) raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new(_("Could not find %{indirection} %{key}") % { indirection: indirection.name, key: key }, Puppet::Network::HTTP::Issues::RESOURCE_NOT_FOUND) end # No need to set a response because no response is expected from a # HEAD request. All we need to do is not die. end # Execute our search. def do_search(indirection, key, params, request, response) result = indirection.search(key, params) if result.nil? raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new(_("Could not find instances in %{indirection} with '%{key}'") % { indirection: indirection.name, key: key }, Puppet::Network::HTTP::Issues::RESOURCE_NOT_FOUND) end rendered_result = nil rendered_format = first_response_formatter_for(indirection.model, request, key) do |format| rendered_result = indirection.model.render_multiple(format, result) end response.respond_with(200, rendered_format, rendered_result) end # Execute our destroy. def do_destroy(indirection, key, params, request, response) formatter = accepted_response_formatter_or_json_for(indirection.model, request) result = indirection.destroy(key, params) response.respond_with(200, formatter, formatter.render(result)) end # Execute our save. def do_save(indirection, key, params, request, response) formatter = accepted_response_formatter_or_json_for(indirection.model, request) sent_object = read_body_into_model(indirection.model, request) result = indirection.save(sent_object, key) response.respond_with(200, formatter, formatter.render(result)) end # Return the first response formatter that didn't cause the yielded # block to raise a FormatError. def first_response_formatter_for(model, request, key, &block) formats = accepted_response_formatters_for(model, request) formatter = formats.find do |format| yield format true rescue Puppet::Network::FormatHandler::FormatError => err msg = _("Failed to serialize %{model} for '%{key}': %{detail}") % { model: model, key: key, detail: err } if Puppet[:allow_pson_serialization] Puppet.warning(msg) else raise Puppet::Network::FormatHandler::FormatError, msg end false end return formatter if formatter raise Puppet::Network::HTTP::Error::HTTPNotAcceptableError.new( _("No supported formats are acceptable (Accept: %{accepted_formats})") % { accepted_formats: formats.map(&:mime).join(', ') }, Puppet::Network::HTTP::Issues::UNSUPPORTED_FORMAT ) end # Return an array of response formatters that the client accepts and # the server supports. def accepted_response_formatters_for(model_class, request) request.response_formatters_for(model_class.supported_formats) end # Return the first response formatter that the client accepts and # the server supports, or default to 'application/json'. def accepted_response_formatter_or_json_for(model_class, request) request.response_formatters_for(model_class.supported_formats, "application/json").first end def read_body_into_model(model_class, request) data = request.body.to_s formatter = request.formatter if formatter.supported?(model_class) begin return model_class.convert_from(formatter.name.to_s, data) rescue => e raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("The request body is invalid: %{message}") % { message: e.message } end end # TRANSLATORS "mime-type" is a keyword and should not be translated raise Puppet::Network::HTTP::Error::HTTPUnsupportedMediaTypeError.new( _("Client sent a mime-type (%{header}) that doesn't correspond to a format we support") % { header: request.headers['content-type'] }, Puppet::Network::HTTP::Issues::UNSUPPORTED_MEDIA_TYPE ) end def indirection_method(http_method, indirection) raise Puppet::Network::HTTP::Error::HTTPMethodNotAllowedError, _("No support for http method %{http_method}") % { http_method: http_method } unless METHOD_MAP[http_method] method = METHOD_MAP[http_method][plurality(indirection)] unless method raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("No support for plurality %{indirection} for %{http_method} operations") % { indirection: plurality(indirection), http_method: http_method } end method end def self.pluralize(indirection) (indirection == "status" ? "statuses" : indirection + "s") end private_class_method :pluralize def plurality(indirection) # NOTE These specific hooks for paths are ridiculous, but it's a *many*-line # fix to not need this, and our goal is to move away from the complication # that leads to the fix being too long. return :singular if indirection == "facts" return :singular if indirection == "status" return :singular if indirection == "certificate_status" result = (indirection =~ /s$|_search$/) ? :plural : :singular indirection.sub!(/s$|_search$/, '') indirection.sub!(/statuse$/, 'status') result end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/api/server/v3.rb
lib/puppet/network/http/api/server/v3.rb
# frozen_string_literal: true require_relative 'v3/environments' require_relative '../../../../../puppet/network/http/api/indirected_routes' module Puppet module Network module HTTP class API module Server class V3 def self.wrap(&block) lambda do |request, response| Puppet::Network::Authorization .check_external_authorization(request.method, request.path) block.call.call(request, response) end end INDIRECTED = Puppet::Network::HTTP::Route .path(/.*/) .any(wrap { Puppet::Network::HTTP::API::IndirectedRoutes.new }) ENVIRONMENTS = Puppet::Network::HTTP::Route .path(%r{^/environments$}) .get(wrap { Environments.new(Puppet.lookup(:environments)) }) def self.routes Puppet::Network::HTTP::Route.path(/v3/) .any .chain(ENVIRONMENTS, INDIRECTED) end end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/api/server/v3/environments.rb
lib/puppet/network/http/api/server/v3/environments.rb
# frozen_string_literal: true require_relative '../../../../../../puppet/util/json' module Puppet module Network module HTTP class API module Server class V3 class Environments def initialize(env_loader) @env_loader = env_loader end def call(request, response) response .respond_with( 200, "application/json", Puppet::Util::Json .dump({ "search_paths" => @env_loader.search_paths, "environments" => @env_loader.list.to_h do |env| [env.name, { "settings" => { "modulepath" => env.full_modulepath, "manifest" => env.manifest, "environment_timeout" => timeout(env), "config_version" => env.config_version || '', } }] end }) ) end private def timeout(env) ttl = @env_loader.get_conf(env.name).environment_timeout if ttl == Float::INFINITY "unlimited" else ttl end end end end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/api/master/v3.rb
lib/puppet/network/http/api/master/v3.rb
# frozen_string_literal: true require_relative '../../../../../puppet/network/http/api/master' require_relative '../../../../../puppet/network/http/api/server/v3'
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/network/http/api/master/v3/environments.rb
lib/puppet/network/http/api/master/v3/environments.rb
# frozen_string_literal: true require_relative '../../../../../../puppet/network/http/api/master' require_relative '../../../../../../puppet/network/http/api/server/v3/environments'
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/content.rb
lib/puppet/file_serving/content.rb
# frozen_string_literal: true require_relative '../../puppet/indirector' require_relative '../../puppet/file_serving' require_relative '../../puppet/file_serving/base' # A class that handles retrieving file contents. # It only reads the file when its content is specifically # asked for. class Puppet::FileServing::Content < Puppet::FileServing::Base extend Puppet::Indirector indirects :file_content, :terminus_class => :selector attr_writer :content def self.supported_formats [:binary] end def self.from_binary(content) instance = new("/this/is/a/fake/path") instance.content = content instance end # This is no longer used, but is still called by the file server implementations when interacting # with their model abstraction. def collect(source_permissions = nil) end # Read the content of our file in. def content unless @content # This stat can raise an exception, too. raise(ArgumentError, _("Cannot read the contents of links unless following links")) if stat.ftype == "symlink" @content = Puppet::FileSystem.binread(full_path) end @content end def to_binary File.new(full_path, "rb") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false