diff --git a/proxmox/src/tools/fs.rs b/proxmox/src/tools/fs.rs index a2dd2804..e0905401 100644 --- a/proxmox/src/tools/fs.rs +++ b/proxmox/src/tools/fs.rs @@ -26,6 +26,54 @@ pub fn file_get_contents>(path: P) -> Result, Error> { std::fs::read(path).map_err(|err| format_err!("unable to read {:?} - {}", path, err)) } +/// Read the entire contents of a file into a bytes vector if the file exists +/// +/// Same as file_get_contents(), but returns 'Ok(None)' instead of +/// 'Err' if the file dose not exist. +pub fn file_get_optional_contents>(path: P) -> Result>, Error> { + let path = path.as_ref(); + + match std::fs::read(path) { + Ok(content) => Ok(Some(content)), + Err(err) => { + if err.kind() == std::io::ErrorKind::NotFound { + Ok(None) + } else { + bail!("unable to read '{:?}' - {}", path, err); + } + } + } +} + +/// Read the entire contents of a file into a String +/// +/// This basically call ``std::fs::read_to_string``, but provides more elaborate +/// error messages including the path. +pub fn file_read_string>(path: P) -> Result { + let path = path.as_ref(); + + std::fs::read_to_string(path).map_err(|err| format_err!("unable to read {:?} - {}", path, err)) +} + +/// Read the entire contents of a file into a String if the file exists +/// +/// Same as file_read_string(), but returns 'Ok(None)' instead of +/// 'Err' if the file dose not exist. +pub fn file_read_optional_string>(path: P) -> Result, Error> { + let path = path.as_ref(); + + match std::fs::read_to_string(path) { + Ok(content) => Ok(Some(content)), + Err(err) => { + if err.kind() == std::io::ErrorKind::NotFound { + Ok(None) + } else { + bail!("unable to read '{:?}' - {}", path, err); + } + } + } +} + /// Read .json file into a ``Value`` /// /// The optional ``default`` is used when the file does not exist.