use crate::compiler::CompilerKind;
use crate::exercise::Exercise;
use crate::info_file::{ExerciseInfo, InfoFile};
use crate::term::{self, write_stdout};
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
static CURRICULUM_TGZ: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/curriculum.tar.gz"));
fn unpack_curriculum(dest: &Path) -> Result<()> {
let decoder = flate2::read::GzDecoder::new(CURRICULUM_TGZ);
tar::Archive::new(decoder)
.unpack(dest)
.context("Failed to extract the embedded curriculum")
}
fn write_manifest(meta_dir: &Path) -> Result<()> {
std::fs::create_dir_all(meta_dir)?;
std::fs::write(
meta_dir.join("manifest.json"),
format!(
"{{\n \"curriculum_version\": \"{}\",\n \"format_version\": 1\n}}\n",
env!("CARGO_PKG_VERSION")
),
)?;
Ok(())
}
fn manifest_field<'a>(content: &'a str, key: &str) -> Option<&'a str> {
let pat = format!("\"{key}\":");
let rest = content[content.find(&pat)? + pat.len()..].trim_start();
if let Some(stripped) = rest.strip_prefix('"') {
stripped.split('"').next()
} else {
rest.split(|c: char| c == ',' || c == '}' || c.is_whitespace())
.next()
}
}
fn semver_triple(v: &str) -> Option<(u64, u64, u64)> {
let mut it = v.split('.').map(|p| p.parse::<u64>().ok());
Some((it.next()??, it.next()??, it.next()??))
}
pub fn init(dir: Option<PathBuf>) -> Result<()> {
let target = dir.unwrap_or_else(|| PathBuf::from("cmetal-workspace"));
if target.exists() {
let mut entries = std::fs::read_dir(&target)
.with_context(|| format!("Failed to inspect {}", target.display()))?;
if entries.next().transpose()?.is_some() {
anyhow::bail!("{} already exists and is not empty", target.display());
}
} else {
std::fs::create_dir_all(&target)
.with_context(|| format!("Failed to create {}", target.display()))?;
}
let result = unpack_curriculum(&target).and_then(|()| write_manifest(&target.join(".cmetal")));
if let Err(e) = result {
let _ = std::fs::remove_dir_all(&target);
return Err(e.context(format!(
"init failed; {} was removed so you can retry",
target.display()
)));
}
write_stdout("\n")?;
term::print_success(&format!("Workspace created in {}", target.display()))?;
write_stdout("\n")?;
write_stdout(" Next steps:\n")?;
write_stdout(&format!(" cd {}\n", target.display()))?;
write_stdout(" cmetal\n")?;
write_stdout("\n")?;
write_stdout(" cmetal copies the exercises into my_exercises/ on first run —\n")?;
write_stdout(" that's where you work. Your progress lives in this directory.\n")?;
write_stdout("\n")?;
Ok(())
}
fn recover_interrupted_update(base_dir: &Path, backup: &Path) -> Result<()> {
if !backup.exists() {
return Ok(());
}
term::print_warning("Found leftovers of an interrupted update — recovering.")?;
for entry in std::fs::read_dir(backup)? {
let entry = entry?.path();
let name = entry.file_name().expect("backup entries have names");
let dest = base_dir.join(name);
if !dest.exists() {
std::fs::rename(&entry, &dest)
.with_context(|| format!("Failed to restore {} from backup", dest.display()))?;
}
}
std::fs::remove_dir_all(backup)?;
Ok(())
}
fn rollback_renames(pairs: &[(PathBuf, PathBuf)]) {
for (from, to) in pairs {
let _ = std::fs::rename(from, to);
}
}
fn remove_if_empty(dir: &Path) {
if let Ok(mut entries) = std::fs::read_dir(dir) {
if entries.next().is_none() {
let _ = std::fs::remove_dir(dir);
}
}
}
fn swap_curriculum(base_dir: &Path, staging: &Path, backup: &Path) -> Result<()> {
let mut parts: Vec<std::ffi::OsString> = std::fs::read_dir(staging)?
.map(|e| e.map(|e| e.file_name()))
.collect::<std::io::Result<_>>()?;
parts.sort();
std::fs::create_dir_all(backup)?;
let mut undo_moves = Vec::new();
for part in &parts {
let old = base_dir.join(part);
if old.exists() {
if let Err(e) = std::fs::rename(&old, backup.join(part)) {
rollback_renames(&undo_moves);
remove_if_empty(backup);
return Err(e).context(format!("Failed to back up {}", part.to_string_lossy()));
}
undo_moves.push((backup.join(part), old));
}
}
let mut undo_installs = Vec::new();
for part in &parts {
let install = if std::env::var_os("CMETAL_TEST_FAIL_INSTALL")
.is_some_and(|v| v.as_os_str() == part.as_os_str())
{
Err(std::io::Error::other("injected failure (test seam)"))
} else {
std::fs::rename(staging.join(part), base_dir.join(part))
};
if let Err(e) = install {
rollback_renames(&undo_installs);
rollback_renames(&undo_moves);
remove_if_empty(backup);
return Err(e).context(format!(
"Failed to install {} — the update was rolled back; if \
anything is left in {}, the next `cmetal update` recovers it",
part.to_string_lossy(),
backup.display()
));
}
undo_installs.push((base_dir.join(part), staging.join(part)));
}
std::fs::remove_dir_all(backup)?;
Ok(())
}
pub fn update(base_dir: &Path) -> Result<()> {
let meta_dir = base_dir.join(".cmetal");
let legacy_meta = base_dir.join(".clings");
if !meta_dir.exists() && legacy_meta.join("manifest.json").exists() {
std::fs::rename(&legacy_meta, &meta_dir)
.context("Failed to migrate the pre-rename .clings directory")?;
term::print_info("Migrated workspace metadata from .clings/ to .cmetal/.")?;
}
if !meta_dir.join("manifest.json").exists() {
anyhow::bail!(
"No .cmetal/manifest.json here — this looks like a git checkout.\n\
Update a checkout with `git pull`; `cmetal update` is for \
workspaces created by `cmetal init`."
);
}
let backup = meta_dir.join("backup");
recover_interrupted_update(base_dir, &backup)?;
let manifest = std::fs::read_to_string(meta_dir.join("manifest.json"))?;
let format = manifest_field(&manifest, "format_version").and_then(|v| v.parse::<u32>().ok());
if format != Some(1) {
anyhow::bail!(
"This workspace uses manifest format {} — this cmetal only \
understands format 1. Upgrade cmetal and retry.",
format.map_or_else(|| "?".to_string(), |f| f.to_string())
);
}
let bin_version = env!("CARGO_PKG_VERSION");
let ws_version = manifest_field(&manifest, "curriculum_version").unwrap_or("0.0.0");
match (semver_triple(ws_version), semver_triple(bin_version)) {
(Some(ws), Some(bin)) if ws > bin => anyhow::bail!(
"Workspace curriculum {ws_version} is NEWER than this binary's \
({bin_version}) — updating would downgrade it. Upgrade cmetal instead."
),
(Some(ws), Some(bin)) if ws == bin => {
write_stdout("\n")?;
term::print_info(&format!(
"Workspace already on curriculum {bin_version}; nothing to update."
))?;
write_stdout("\n")?;
return Ok(());
}
_ => {}
}
let staging = meta_dir.join("staging");
if staging.exists() {
std::fs::remove_dir_all(&staging)?;
}
std::fs::create_dir_all(&staging)?;
unpack_curriculum(&staging)?;
let staged_info = InfoFile::parse(&staging.join("info.toml"))?;
let mut new_exercises = Vec::new();
let mut kept = Vec::new();
let mut pending_refresh: Vec<(PathBuf, Vec<u8>, String)> = Vec::new();
for ei in &staged_info.exercises {
let rel = Path::new("exercises").join(ei.rel_path());
let staged = staging.join(&rel);
let old_pristine = base_dir.join(&rel);
if !old_pristine.exists() {
new_exercises.push(ei.name.clone());
continue; }
let new_bytes = std::fs::read(&staged)?;
let old_bytes = std::fs::read(&old_pristine)?;
if new_bytes == old_bytes {
continue; }
let my_copy = base_dir.join("my_exercises").join(ei.rel_path());
if !my_copy.exists() {
continue; }
if std::fs::read(&my_copy)? == old_bytes {
pending_refresh.push((my_copy, new_bytes, ei.name.clone()));
} else {
kept.push(ei.name.clone());
}
}
swap_curriculum(base_dir, &staging, &backup)?;
let mut refreshed = Vec::new();
for (my_copy, new_bytes, display_name) in pending_refresh {
std::fs::write(&my_copy, &new_bytes)?;
refreshed.push(display_name);
}
std::fs::remove_dir_all(&staging)?;
write_manifest(&meta_dir)?;
write_stdout("\n")?;
term::print_success(&format!(
"Workspace updated to curriculum {}.",
env!("CARGO_PKG_VERSION")
))?;
if !new_exercises.is_empty() {
term::print_info(&format!(
"{} new exercise(s) — they appear in my_exercises/ on the next run: {}",
new_exercises.len(),
new_exercises.join(", ")
))?;
}
if !refreshed.is_empty() {
term::print_info(&format!(
"{} untouched working cop(ies) refreshed: {}",
refreshed.len(),
refreshed.join(", ")
))?;
}
for name in &kept {
term::print_warning(&format!(
"{name} changed upstream but you have edits — your copy is kept. \
Compare with `cmetal diff {name}`, or take the new version with \
`cmetal reset {name}`."
))?;
}
if new_exercises.is_empty() && refreshed.is_empty() && kept.is_empty() {
term::print_info("Curriculum files updated; no working-copy changes to reconcile.")?;
}
write_stdout("\n")?;
Ok(())
}
fn find_upwards(marker: impl Fn(&Path) -> bool) -> Result<Option<PathBuf>> {
let mut dir = std::env::current_dir().context("Failed to read the working directory")?;
loop {
if marker(&dir) {
return Ok(Some(dir));
}
if !dir.pop() {
return Ok(None);
}
}
}
pub fn resolve_base_dir() -> Result<PathBuf> {
find_upwards(|dir| dir.join("info.toml").exists())?
.context("Could not find info.toml. Are you in a cmetal project directory?")
}
pub fn resolve_workspace_dir() -> Result<PathBuf> {
find_upwards(|dir| {
dir.join("info.toml").exists()
|| dir.join(".cmetal").join("manifest.json").exists()
|| dir.join(".clings").join("manifest.json").exists()
})?
.context("Could not find a cmetal workspace here (no info.toml or .cmetal/manifest.json).")
}
pub fn load_exercises(
info: &InfoFile,
base_dir: &Path,
work_dir: &Path,
compiler: CompilerKind,
) -> Vec<Exercise> {
let solutions_dir = base_dir.join("solutions");
info.exercises
.iter()
.map(|ei| {
Exercise::new(
ei.clone(),
work_dir,
&solutions_dir,
compiler.command_name(),
)
})
.collect()
}
pub fn work_dir(base_dir: &Path) -> PathBuf {
base_dir.join("my_exercises")
}
pub fn prepare_workspace(info: &InfoFile, base_dir: &Path) -> Result<PathBuf> {
let pristine_dir = base_dir.join("exercises");
let work = work_dir(base_dir);
for ei in &info.exercises {
let rel = ei.rel_path();
let src = pristine_dir.join(&rel);
let dst = work.join(&rel);
if src.exists() && !dst.exists() {
std::fs::create_dir_all(dst.parent().unwrap())?;
std::fs::copy(&src, &dst)
.with_context(|| format!("Failed to copy {} into the workspace", src.display()))?;
}
}
Ok(work)
}
pub fn restore_exercise(base_dir: &Path, ei: &ExerciseInfo) -> Result<()> {
let rel = ei.rel_path();
let src = base_dir.join("exercises").join(&rel);
let dst = base_dir.join("my_exercises").join(&rel);
if src.exists() {
std::fs::create_dir_all(dst.parent().unwrap())?;
std::fs::copy(&src, &dst)
.with_context(|| format!("Failed to restore {}", rel.display()))?;
}
Ok(())
}
pub fn edited_among<'a>(
base_dir: &Path,
exercises: impl IntoIterator<Item = &'a ExerciseInfo>,
) -> Vec<String> {
let pristine_dir = base_dir.join("exercises");
let work = work_dir(base_dir);
exercises
.into_iter()
.filter(|ei| {
let rel = ei.rel_path();
differs(&pristine_dir.join(&rel), &work.join(&rel))
})
.map(|ei| ei.name.clone())
.collect()
}
fn differs(pristine: &Path, mine: &Path) -> bool {
let (Ok(a), Ok(b)) = (std::fs::metadata(pristine), std::fs::metadata(mine)) else {
return false;
};
if a.len() != b.len() {
return true;
}
match (std::fs::read(pristine), std::fs::read(mine)) {
(Ok(a), Ok(b)) => a != b,
_ => false,
}
}