[enh] new utils to read yaml files

This commit is contained in:
Laurent Peuch 2018-05-12 05:58:00 +02:00
parent 7f9cc03f3f
commit f8a1a6aabb
3 changed files with 25 additions and 0 deletions

View file

@ -3,6 +3,7 @@ File system operation utils
.. autofunction:: moulinette.utils.filesystem.read_file .. autofunction:: moulinette.utils.filesystem.read_file
.. autofunction:: moulinette.utils.filesystem.read_json .. autofunction:: moulinette.utils.filesystem.read_json
.. autofunction:: moulinette.utils.filesystem.read_yaml
.. autofunction:: moulinette.utils.filesystem.write_to_file .. autofunction:: moulinette.utils.filesystem.write_to_file
.. autofunction:: moulinette.utils.filesystem.append_to_file .. autofunction:: moulinette.utils.filesystem.append_to_file
.. autofunction:: moulinette.utils.filesystem.write_to_json .. autofunction:: moulinette.utils.filesystem.write_to_json

View file

@ -41,6 +41,7 @@
"cannot_write_file": "Could not write file {file:s} (reason: {error:s})", "cannot_write_file": "Could not write file {file:s} (reason: {error:s})",
"unknown_error_reading_file": "Unknown error while trying to read file {file:s}", "unknown_error_reading_file": "Unknown error while trying to read file {file:s}",
"corrupted_json": "Corrupted json read from {ressource:s} (reason: {error:s})", "corrupted_json": "Corrupted json read from {ressource:s} (reason: {error:s})",
"corrupted_yaml": "Corrupted yaml read from {ressource:s} (reason: {error:s})",
"error_writing_file": "Error when writing file {file:s}: {error:s}", "error_writing_file": "Error when writing file {file:s}: {error:s}",
"error_removing": "Error when removing {path:s}: {error:s}", "error_removing": "Error when removing {path:s}: {error:s}",
"error_changing_file_permissions": "Error when changing permissions for {path:s}: {error:s}", "error_changing_file_permissions": "Error when changing permissions for {path:s}: {error:s}",

View file

@ -1,4 +1,5 @@
import os import os
import yaml
import errno import errno
import shutil import shutil
import json import json
@ -64,6 +65,28 @@ def read_json(file_path):
return loaded_json return loaded_json
def read_yaml(file_path):
"""
Safely read a yaml file
Keyword argument:
file_path -- Path to the yaml file
"""
# Read file
file_content = read_file(file_path)
# Try to load yaml to check if it's syntaxically correct
try:
loaded_yaml = yaml.safe_load(file_content)
except ValueError as e:
raise MoulinetteError(errno.EINVAL,
m18n.g('corrupted_yaml',
ressource=file_path, error=str(e)))
return loaded_yaml
def write_to_file(file_path, data, file_mode="w"): def write_to_file(file_path, data, file_mode="w"):
""" """
Write a single string or a list of string to a text file. Write a single string or a list of string to a text file.