21646ade3ad08cc52bbedd096def28beba95e198
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / functions / validate_legacy.rb
1 Puppet::Functions.create_function(:validate_legacy) do
2   # The function checks a value against both the target_type (new) and the previous_validation function (old).
3
4   dispatch :validate_legacy do
5     param 'Any', :scope
6     param 'Type', :target_type
7     param 'String', :function_name
8     param 'Any', :value
9     repeated_param 'Any', :args
10   end
11
12   dispatch :validate_legacy_s do
13     param 'Any', :scope
14     param 'String', :type_string
15     param 'String', :function_name
16     param 'Any', :value
17     repeated_param 'Any', :args
18   end
19
20   # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-
21   #   c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1.
22   def call(scope, *args)
23     manipulated_args = [scope] + args
24     self.class.dispatcher.dispatch(self, scope, manipulated_args)
25   end
26
27   def validate_legacy_s(scope, type_string, *args)
28     t = Puppet::Pops::Types::TypeParser.new.parse(type_string, scope)
29     validate_legacy(scope, t, *args)
30   end
31
32   def validate_legacy(scope, target_type, function_name, value, *prev_args)
33     if assert_type(target_type, value)
34       if previous_validation(scope, function_name, value, *prev_args)
35         # Silently passes
36       else
37         Puppet.notice("Accepting previously invalid value for target type '#{target_type}'")
38       end
39     else
40       inferred_type = Puppet::Pops::Types::TypeCalculator.infer_set(value)
41       error_msg = Puppet::Pops::Types::TypeMismatchDescriber.new.describe_mismatch("validate_legacy(#{function_name})", target_type, inferred_type)
42       if previous_validation(scope, function_name, value, *prev_args)
43         call_function('deprecation', 'validate_legacy', error_msg)
44       else
45         call_function('fail', error_msg)
46       end
47     end
48   end
49
50   def previous_validation(scope, function_name, value, *prev_args)
51     # Call the previous validation function and catch any errors. Return true if no errors are thrown.
52
53     scope.send("function_#{function_name}".to_s, [value, *prev_args])
54     true
55   rescue Puppet::ParseError
56     false
57   end
58
59   def assert_type(type, value)
60     Puppet::Pops::Types::TypeCalculator.instance?(type, value)
61   end
62 end