Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / fqdn_rand_string.rb
1 Puppet::Parser::Functions.newfunction(
2   :fqdn_rand_string,
3   :arity => -2,
4   :type => :rvalue,
5   :doc => <<-DOC
6   @summary
7     Generates a random alphanumeric string. Combining the `$fqdn` fact and an
8     optional seed for repeatable randomness.
9
10   Optionally, you can specify a character set for the function (defaults to alphanumeric).
11
12   Arguments
13   * An integer, specifying the length of the resulting string.
14   * Optionally, a string specifying the character set.
15   * Optionally, a string specifying the seed for repeatable randomness.
16
17   @return [String]
18
19   @example Example Usage:
20     fqdn_rand_string(10)
21     fqdn_rand_string(10, 'ABCDEF!@$%^')
22     fqdn_rand_string(10, '', 'custom seed')
23   DOC
24 ) do |args|
25   raise(ArgumentError, 'fqdn_rand_string(): wrong number of arguments (0 for 1)') if args.empty?
26   Puppet::Parser::Functions.function('is_integer')
27   raise(ArgumentError, 'fqdn_rand_string(): first argument must be a positive integer') unless function_is_integer([args[0]]) && args[0].to_i > 0
28   raise(ArgumentError, 'fqdn_rand_string(): second argument must be undef or a string') unless args[1].nil? || args[1].is_a?(String)
29
30   Puppet::Parser::Functions.function('fqdn_rand')
31
32   length = args.shift.to_i
33   charset = args.shift.to_s.chars.to_a
34
35   charset = (0..9).map { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a if charset.empty?
36
37   rand_string = ''
38   for current in 1..length # rubocop:disable Style/For : An each loop would not work correctly in this circumstance
39     rand_string << charset[function_fqdn_rand([charset.size, (args + [current.to_s]).join(':')]).to_i]
40   end
41
42   rand_string
43 end