Method: ChefAPI::Util#safe_read

Defined in:
lib/chef-api/util.rb

#safe_read(path) ⇒ Array<String>

“Safely” read the contents of a file on disk, catching any permission errors or not found errors and raising a nicer exception.

Examples:

Reading a file that does not exist

safe_read('/non-existent/file') #=> Error::FileNotFound

Reading a file with improper permissions

safe_read('/bad-permissions') #=> Error::InsufficientFilePermissions

Reading a regular file

safe_read('my-file.txt') #=> ["my-file", "..."]

Parameters:

  • path (String)

    the path to the file on disk

Returns:

  • (Array<String>)

    A array where the first value is the basename of the file and the second value is the literal contents from File.read.



78
79
80
81
82
83
84
85
86
87
88
# File 'lib/chef-api/util.rb', line 78

def safe_read(path)
  path     = File.expand_path(path)
  name     = File.basename(path, '.*')
  contents = File.read(path)

  [name, contents]
rescue Errno::EACCES
  raise Error::InsufficientFilePermissions.new(path: path)
rescue Errno::ENOENT
  raise Error::FileNotFound.new(path: path)
end