Update stdlib
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / base64.rb
1
2 #  Please note: This function is an implementation of a Ruby class 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.
3
4 module Puppet::Parser::Functions
5
6   newfunction(:base64, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args|
7
8     Base64 encode or decode a string based on the command and the string submitted
9
10     Usage:
11
12       $encodestring = base64('encode', 'thestring')
13       $decodestring = base64('decode', 'dGhlc3RyaW5n')
14
15       # explicitly define encode/decode method: default, strict, urlsafe
16       $method = 'default'
17       $encodestring = base64('encode', 'thestring', $method)
18       $decodestring = base64('decode', 'dGhlc3RyaW5n', $method)
19
20     ENDHEREDOC
21
22     require 'base64'
23
24     raise Puppet::ParseError, ("base64(): Wrong number of arguments (#{args.length}; must be >= 2)") unless args.length >= 2
25
26     actions = ['encode','decode']
27
28     unless actions.include?(args[0])
29       raise Puppet::ParseError, ("base64(): the first argument must be one of 'encode' or 'decode'")
30     end
31
32     unless args[1].is_a?(String)
33       raise Puppet::ParseError, ("base64(): the second argument must be a string to base64")
34     end
35
36     method = ['default','strict','urlsafe']
37
38     if args.length <= 2
39       chosenMethod = 'default'
40     else
41       chosenMethod = args[2]
42     end
43
44     unless method.include?(chosenMethod)
45       raise Puppet::ParseError, ("base64(): the third argument must be one of 'default', 'strict', or 'urlsafe'")
46     end
47
48     case args[0]
49       when 'encode'
50         case chosenMethod
51           when 'default'
52             result = Base64.encode64(args[1])
53           when 'strict'
54             result = Base64.strict_encode64(args[1])
55           when 'urlsafe'
56             result = Base64.urlsafe_encode64(args[1])
57         end
58       when 'decode'
59         case chosenMethod
60           when 'default'
61             result = Base64.decode64(args[1])
62           when 'strict'
63             result = Base64.strict_decode64(args[1])
64           when 'urlsafe'
65             result = Base64.urlsafe_decode64(args[1])
66         end
67     end
68
69     return result
70   end
71 end