clutils 0.0.11

A common library for building interpreter and compiler
Documentation
pub(crate) mod utils;

use std::{fs, ops::Range, path::PathBuf};

pub struct SnapshotTest {
    pub(crate) name: String,
    pub(crate) path: PathBuf,
}

pub type Changes = Vec<Range<usize>>;

impl SnapshotTest {
    /// `path` takes the path to the file that clu
    /// should create a snapshot of.
    pub fn new(name: &str, path: PathBuf) -> Self {
        Self {
            name: name.into(),
            path,
        }
    }

    pub fn setup_dir(&self) {
        if fs::metadata("snapshots").is_err() {
            fs::create_dir("snapshots").unwrap_or_else(|_| {
                panic!("Could not create directory for snapshots");
            });
        }
    }

    pub fn create_snapshot(&self) {
        // path to file for the new snapshot
        let snapshot_path: PathBuf = format!("snapshots/{}.snap", &self.name).into();
        // contents of file that user pointed to
        let provided_file = fs::read_to_string(&self.path).unwrap_or_else(|_| {
            panic!("Could not read file at path: {:?}", &self.path);
        });
        // Create snapshot if it does not exist
        let content_snapshot = Self::try_create_snapshot(&snapshot_path, &provided_file);
        // If snapshot exists, compare it with the provided file
        match content_snapshot {
            Some(content_snapshot) => {
                Self::compare_snapshots(&snapshot_path, &provided_file, &content_snapshot);
            }
            None => return,
        }
    }

    fn compare_snapshots(snapshot_path: &PathBuf, provided_file: &str, content_snapshot: &str) -> () /*Option<Changes>*/ {
        if provided_file != content_snapshot {
            fs::write(&snapshot_path, provided_file).unwrap_or_else(|_| {
                panic!("Could not write snapshot to file");
            });
            utils::stdout_changes();
        }
    }

    fn try_create_snapshot(path: &PathBuf, content_file: &str) -> Option<String> {
        if path.exists() {
            Some(fs::read_to_string(&path).unwrap_or_else(|_| {
                panic!("Could not read snapshot file");
            }))
        } else {
            fs::write(path, content_file).unwrap_or_else(|_| {
                panic!("Could not write snapshot to file");
            });
            None
        }
    }
}