diff --git a/doc/utils/filesystem.rst b/doc/utils/filesystem.rst index c58c3367..6ae30928 100644 --- a/doc/utils/filesystem.rst +++ b/doc/utils/filesystem.rst @@ -3,6 +3,7 @@ File system operation utils .. autofunction:: moulinette.utils.filesystem.read_file .. autofunction:: moulinette.utils.filesystem.read_json +.. autofunction:: moulinette.utils.filesystem.read_yaml .. autofunction:: moulinette.utils.filesystem.write_to_file .. autofunction:: moulinette.utils.filesystem.append_to_file .. autofunction:: moulinette.utils.filesystem.write_to_json diff --git a/locales/en.json b/locales/en.json index 77ea7c2b..5adaab5b 100644 --- a/locales/en.json +++ b/locales/en.json @@ -41,6 +41,7 @@ "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}", "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_removing": "Error when removing {path:s}: {error:s}", "error_changing_file_permissions": "Error when changing permissions for {path:s}: {error:s}", diff --git a/moulinette/utils/filesystem.py b/moulinette/utils/filesystem.py index 1740a7a6..07da4bf7 100644 --- a/moulinette/utils/filesystem.py +++ b/moulinette/utils/filesystem.py @@ -1,4 +1,5 @@ import os +import yaml import errno import shutil import json @@ -64,6 +65,28 @@ def read_json(file_path): 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"): """ Write a single string or a list of string to a text file.