renvy/io.rs
1use std::{fs, io};
2
3/// Reads a file from disk and returns its contents as a [`std::io::Result<String>`].
4///
5/// You would use this function to read both the settings and defaults file, before
6/// passing their contents to [`crate::deserialize()`] and [`crate::merge()`].
7///
8/// ## Reading a file into a String
9///
10/// This shows how to obtain a [`std::io::Result`] that wraps a `String`.
11/// ```no_run
12/// if let Ok(file_contents) = renvy::read_file("/path/to/my/.env") {
13/// println!("File contents: {}", &file_contents);
14/// }
15/// ```
16///
17/// You can reuse the same function for reading the settings file as well as the defaults file.
18pub fn read_file(filepath: &str) -> io::Result<String> {
19 fs::read_to_string(filepath)
20}
21
22/// Writes a String data `contents` into the file at `filepath` and returns
23/// the result as [`std::io::Result`].
24///
25/// You would use this function to write the deserialized settings back to the file after merging.
26///
27/// ## Writing a String into a file
28///
29/// This shows how to write a `String` which returns a [`std::io::Result`].
30/// ```no_run
31/// # let deserialized_contents = "key=value";
32/// if let Ok(_) = renvy::write_file(&"/path/to/my/.env", deserialized_contents) {
33/// println!("File written successfully.");
34/// }
35/// ```
36pub fn write_file(filepath: &str, contents: &str) -> io::Result<()> {
37 fs::write(filepath, contents)
38}