validate_legacy.rb 2.2 KB

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