aboutsummaryrefslogtreecommitdiffstats
path: root/src/content.rs
blob: 4dce0e7fadf809b69b60114932e15fc4aa87a993 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//! The entries of one channel, by slot, and the records in keyed ones.

use std::collections::BTreeMap;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
use std::path::Path;

use anyhow::{Context, Result, bail};
use serde_json::{Map, Value};

use crate::name;

/// Entries by slot name, each exactly as stored.
pub type Content = BTreeMap<String, Vec<u8>>;

/// The entries in `dir`: one file per slot.  A missing directory holds none.
pub fn read_dir(dir: &Path) -> Result<Content> {
    let mut content = Content::new();
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(content),
        Err(error) => return Err(error).with_context(|| format!("reading {}", dir.display())),
    };
    for entry in entries {
        let entry = entry?;
        let slot = entry
            .file_name()
            .into_string()
            .ok()
            .filter(|slot| name::is_name(slot));
        let Some(slot) = slot else {
            bail!("{}: not a slot's name", entry.path().display());
        };
        if !entry.file_type()?.is_file() {
            bail!("{}: not a regular file", entry.path().display());
        }
        let bytes = std::fs::read(entry.path())
            .with_context(|| format!("reading {}", entry.path().display()))?;
        content.insert(slot, bytes);
    }
    Ok(content)
}

/// Writes `content` into `dir`, which is created, with files of `mode` (and
/// directories that can be entered where the files can be read).
pub fn write_dir(content: &Content, dir: &Path, mode: u32) -> Result<()> {
    std::fs::DirBuilder::new()
        .recursive(true)
        .mode(directory_mode(mode))
        .create(dir)
        .with_context(|| format!("creating {}", dir.display()))?;
    for (slot, bytes) in content {
        write_file(&dir.join(slot), bytes, mode)?;
    }
    Ok(())
}

pub fn write_file(path: &Path, bytes: &[u8], mode: u32) -> Result<()> {
    use std::io::Write;
    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(mode)
        .open(path)
        .with_context(|| format!("creating {}", path.display()))?;
    file.write_all(bytes)
        .with_context(|| format!("writing {}", path.display()))
}

/// The mode of a directory holding files of `mode`: searchable by whoever can read.
pub fn directory_mode(mode: u32) -> u32 {
    mode | ((mode & 0o444) >> 2)
}

/// The records of a keyed entry.
pub fn records(bytes: &[u8]) -> Result<Map<String, Value>> {
    match serde_json::from_slice(bytes).context("not JSON")? {
        Value::Object(records) => Ok(records),
        _ => bail!("not a JSON object, whose keys would be records"),
    }
}

/// A keyed entry holding `records`, in a normal form: keys sorted, indented, a line
/// break at the end.
pub fn from_records(records: &Map<String, Value>) -> Vec<u8> {
    let mut bytes = serde_json::to_vec_pretty(records).expect("JSON values serialize");
    bytes.push(b'\n');
    bytes
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn records_in_normal_form() {
        let records = records(br#"{"b": 1, "a": {"x": [1]}}"#).unwrap();
        assert_eq!(
            String::from_utf8(from_records(&records)).unwrap(),
            "{\n  \"a\": {\n    \"x\": [\n      1\n    ]\n  },\n  \"b\": 1\n}\n"
        );
        assert!(super::records(b"[1]").is_err());
        assert_eq!(directory_mode(0o600), 0o700);
        assert_eq!(directory_mode(0o644), 0o755);
    }
}