Skip to main content

yog_cli/
files.rs

1//! A project's files: those of a Yog format under a folder, sources read
2//! and written as text, and files removed.
3
4use std::path::{Path, PathBuf};
5
6use yog_ids::Format;
7
8/// Every file of `format` under `dir`, sorted.
9pub(crate) fn of(dir: &Path, format: Format) -> Vec<PathBuf> {
10    yog_analysis::files::with_ext(dir, &[format.ext()])
11}
12
13/// A source file of a Yog format, as text: kept binary on disk (what the
14/// editor saves), read as the text the editor shows (`yog_data::source`).
15pub fn read_source(path: impl AsRef<Path>) -> std::io::Result<String> {
16    let bytes = std::fs::read(path)?;
17    yog_data::source::text(&bytes)
18        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
19}
20
21/// Writes `text` as the source file at `path`: binary, its comments kept as notes.
22pub fn write_source(path: &Path, text: &str) -> Result<(), String> {
23    let bytes = yog_data::source::binary(text).map_err(|e| format!("{}: {e}", path.display()))?;
24    std::fs::write(path, bytes).map_err(|e| format!("{}: {e}", path.display()))
25}
26
27/// Removes `path` (a file, or a folder and all in it) that's no longer
28/// wanted: already gone is fine; anything else is said, as the files stay.
29pub fn remove(path: &Path) {
30    let removed = if path.is_dir() {
31        std::fs::remove_dir_all(path)
32    } else {
33        std::fs::remove_file(path)
34    };
35    if let Err(e) = removed
36        && e.kind() != std::io::ErrorKind::NotFound
37    {
38        yog_logging::warn!("couldn't remove {}: {e}", path.display());
39    }
40}