Module: Puppet::Util::Yaml

Defined in:
lib/puppet/util/yaml.rb

Defined Under Namespace

Classes: YamlLoadError

Constant Summary collapse

YamlLoadExceptions =
[::StandardError, ::Psych::Exception]

Class Method Summary collapse

Class Method Details

.dump(structure, filename) ⇒ Object



62
63
64
65
66
# File 'lib/puppet/util/yaml.rb', line 62

def self.dump(structure, filename)
  Puppet::FileSystem.replace_file(filename, 0o660) do |fh|
    YAML.dump(structure, fh)
  end
end

.safe_load(yaml, allowed_classes = [], filename = nil) ⇒ Object

Safely load the content as YAML. By default only the following classes can be deserialized:

  • TrueClass

  • FalseClass

  • NilClass

  • Numeric

  • String

  • Array

  • Hash

Attempting to deserialize other classes will raise an YamlLoadError exception unless they are specified in the array of allowed_classes.

Parameters:

  • yaml (String)

    The yaml content to parse.

  • allowed_classes (Array) (defaults to: [])

    Additional list of classes that can be deserialized.

  • filename (String) (defaults to: nil)

    The filename to load from, used if an exception is raised.

Returns:

  • The parsed YAML, which can be Hash, Array or scalar types.

Raises:

  • (YamlLoadException)

    If deserialization fails.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/puppet/util/yaml.rb', line 28

def self.safe_load(yaml, allowed_classes = [], filename = nil)
  if Gem::Version.new(Psych::VERSION) >= Gem::Version.new('3.1.0')
    data = YAML.safe_load(yaml, permitted_classes: allowed_classes, aliases: true, filename: filename)
  else
    data = YAML.safe_load(yaml, allowed_classes, [], true, filename)
  end
  data = false if data.nil?
  data
rescue ::Psych::DisallowedClass => detail
  path = filename ? "(#{filename})" : "(<unknown>)"
  raise YamlLoadError.new("#{path}: #{detail.message}", detail)
rescue *YamlLoadExceptions => detail
  raise YamlLoadError.new(detail.message, detail)
end

.safe_load_file(filename, allowed_classes = []) ⇒ Object

Safely load the content from a file as YAML.

See Also:



46
47
48
49
# File 'lib/puppet/util/yaml.rb', line 46

def self.safe_load_file(filename, allowed_classes = [])
  yaml = Puppet::FileSystem.read(filename, :encoding => 'bom|utf-8')
  safe_load(yaml, allowed_classes, filename)
end

.safe_load_file_if_valid(filename, allowed_classes = []) ⇒ Object

Safely load the content from a file as YAML if contents are in valid format. This method does not raise error but returns ‘nil` when invalid file is given.



55
56
57
58
59
60
# File 'lib/puppet/util/yaml.rb', line 55

def self.safe_load_file_if_valid(filename, allowed_classes = [])
  safe_load_file(filename, allowed_classes)
rescue YamlLoadError, ArgumentError, Errno::ENOENT => detail
  Puppet.debug("Could not retrieve YAML content from '#{filename}': #{detail.message}")
  nil
end