Skip to main content

elph_core/layout/
files.rs

1use std::fs;
2use std::path::Path;
3
4use anyhow::{Context, Result};
5use serde::Serialize;
6
7/// Write a pretty-printed JSON file with mode `0600` on Unix.
8pub fn write_json_file<T: Serialize>(path: &Path, value: &T) -> Result<()> {
9    if let Some(parent) = path.parent() {
10        fs::create_dir_all(parent).with_context(|| format!("failed to create {}", parent.display()))?;
11    }
12
13    let mut payload = serde_json::to_string_pretty(value).context("failed to serialize json")?;
14    payload.push('\n');
15    write_private_file(path, payload.as_bytes())
16}
17
18/// Write a private file with mode `0600` on Unix.
19pub fn write_private_file(path: &Path, contents: &[u8]) -> Result<()> {
20    #[cfg(unix)]
21    {
22        use std::fs::OpenOptions;
23        use std::io::Write;
24        use std::os::unix::fs::OpenOptionsExt;
25
26        let mut file = OpenOptions::new()
27            .write(true)
28            .create_new(true)
29            .mode(0o600)
30            .open(path)
31            .with_context(|| format!("failed to write {}", path.display()))?;
32        file.write_all(contents)?;
33        return Ok(());
34    }
35
36    #[cfg(not(unix))]
37    {
38        fs::write(path, contents).with_context(|| format!("failed to write {}", path.display()))?;
39        Ok(())
40    }
41}