rustlings/src/embedded.rs

92 lines
2.4 KiB
Rust
Raw Normal View History

2024-03-28 16:06:36 -04:00
use std::{
fs::{create_dir, OpenOptions},
2024-03-28 16:06:36 -04:00
io::{self, Write},
};
use crate::info_file::ExerciseInfo;
2024-03-28 16:06:36 -04:00
pub static EMBEDDED_FILES: EmbeddedFiles = rustlings_macros::include_files!();
#[derive(Clone, Copy)]
pub enum WriteStrategy {
IfNotExists,
Overwrite,
}
impl WriteStrategy {
fn write(self, path: &str, content: &[u8]) -> io::Result<()> {
let file = match self {
2024-03-28 16:06:36 -04:00
Self::IfNotExists => OpenOptions::new().create_new(true).write(true).open(path),
Self::Overwrite => OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(path),
};
file?.write_all(content)
2024-03-28 16:06:36 -04:00
}
}
struct ExerciseFiles {
exercise: &'static [u8],
solution: &'static [u8],
2024-03-28 16:06:36 -04:00
}
struct ExerciseDir {
name: &'static str,
readme: &'static [u8],
2024-03-28 16:06:36 -04:00
}
impl ExerciseDir {
2024-03-28 16:06:36 -04:00
fn init_on_disk(&self) -> io::Result<()> {
if let Err(e) = create_dir(format!("exercises/{}", self.name)) {
if e.kind() == io::ErrorKind::AlreadyExists {
return Ok(());
2024-03-28 16:06:36 -04:00
}
return Err(e);
2024-03-28 16:06:36 -04:00
}
WriteStrategy::Overwrite.write(&format!("exercises/{}/README.md", self.name), self.readme)
2024-03-28 16:06:36 -04:00
}
}
pub struct EmbeddedFiles {
exercise_files: &'static [ExerciseFiles],
exercise_dirs: &'static [ExerciseDir],
2024-03-28 16:06:36 -04:00
}
impl EmbeddedFiles {
pub fn init_exercises_dir(&self, exercise_infos: &[ExerciseInfo]) -> io::Result<()> {
2024-03-28 16:06:36 -04:00
create_dir("exercises")?;
2024-03-28 17:11:16 -04:00
WriteStrategy::IfNotExists.write(
"exercises/README.md",
include_bytes!("../exercises/README.md"),
)?;
2024-03-28 17:11:16 -04:00
for dir in self.exercise_dirs {
2024-03-28 17:11:16 -04:00
dir.init_on_disk()?;
}
2024-03-28 17:11:16 -04:00
for (exercise_info, exercise_files) in exercise_infos.iter().zip(self.exercise_files) {
WriteStrategy::IfNotExists.write(&exercise_info.path(), exercise_files.exercise)?;
2024-03-28 17:11:16 -04:00
}
Ok(())
2024-03-28 16:06:36 -04:00
}
pub fn write_exercise_to_disk(&self, exercise_ind: usize, dir_name: &str, path: &str) -> io::Result<()> {
let Some(dir) = self.exercise_dirs.iter().find(|dir| dir.name == dir_name) else {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("`{dir_name}` not found in the embedded directories"),
));
};
2024-03-28 16:06:36 -04:00
dir.init_on_disk()?;
WriteStrategy::Overwrite.write(path, self.exercise_files[exercise_ind].exercise)
2024-03-28 16:06:36 -04:00
}
}