use std::path::{Path, PathBuf};
pub const TOUR_JSON: &str = include_str!("../assets/tour/tour.json");
pub const SCRATCH_MARKER: &str = ".croft-demo";
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TourAction {
Open(String),
QuickOpen,
FindFile(String),
SplitEditor,
Terminal,
Run(String),
JumpToError,
CommandPalette,
Palette(String),
ThemePicker,
Done,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub struct TourStep {
pub action: TourAction,
pub caption: String,
}
impl TourStep {
pub fn caption_text(&self) -> String {
expand_caption(&self.caption, crate::keymap::mod_key_name())
}
}
pub fn expand_caption(caption: &str, modifier: &str) -> String {
caption.replace("{mod}", modifier)
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub struct Tour {
pub steps: Vec<TourStep>,
#[serde(skip)]
pub index: usize,
}
impl Tour {
pub fn parse(json: &str) -> Result<Tour, String> {
let tour: Tour = serde_json::from_str(json).map_err(|e| format!("tour.json: {e}"))?;
if tour.steps.is_empty() {
return Err(String::from("tour.json has no steps"));
}
Ok(tour)
}
pub fn current(&self) -> Option<&TourStep> {
self.steps.get(self.index)
}
pub fn advance(&mut self) -> Option<&TourStep> {
self.index = (self.index + 1).min(self.steps.len());
self.current()
}
pub fn progress(&self) -> String {
format!(
"{}/{}",
(self.index + 1).min(self.steps.len()),
self.steps.len()
)
}
}
static CUSTOM_TOUR: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
pub fn set_custom_tour(json: String) {
if let Ok(mut slot) = CUSTOM_TOUR.lock() {
*slot = Some(json);
}
}
pub fn tour_source() -> String {
CUSTOM_TOUR
.lock()
.ok()
.and_then(|slot| slot.clone())
.unwrap_or_else(|| TOUR_JSON.to_string())
}
static STARTUP_DEMO: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn request_startup_demo() {
STARTUP_DEMO.store(true, std::sync::atomic::Ordering::SeqCst);
}
pub fn take_startup_demo() -> bool {
STARTUP_DEMO.swap(false, std::sync::atomic::Ordering::SeqCst)
}
pub fn sample_files() -> Vec<(&'static str, &'static str)> {
vec![
(
"README.md",
"# croft tour\n\nA throwaway sample project. It is deleted when the tour ends.\n",
),
(
"src/main.rs",
"fn main() {\n let who = \"croft\";\n println!(\"hello from {who}\");\n}\n",
),
(
"app.py",
"def greet(name):\n return f\"hello, {name}\"\n\nprint(greet(\"croft\")\n",
),
(
"web/index.html",
"<!doctype html>\n<title>croft tour</title>\n<p>Hello from the sample project.</p>\n",
),
]
}
pub fn create_scratch(parent: &Path) -> std::io::Result<PathBuf> {
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let dir = parent.join(format!("croft-demo-{}-{stamp}", std::process::id()));
std::fs::create_dir_all(&dir)?;
std::fs::write(
dir.join(SCRATCH_MARKER),
"croft demo scratch; safe to delete\n",
)?;
for (rel, text) in sample_files() {
let path = dir.join(rel);
if let Some(p) = path.parent() {
std::fs::create_dir_all(p)?;
}
std::fs::write(path, text)?;
}
Ok(dir)
}
pub fn sweep_dead_scratch(parent: &Path, is_alive: impl Fn(u32) -> bool) -> usize {
let Ok(entries) = std::fs::read_dir(parent) else {
return 0;
};
let me = std::process::id();
let mut removed = 0;
for entry in entries.flatten() {
let Some(pid) = entry.file_name().to_str().and_then(scratch_pid) else {
continue;
};
if pid == me || is_alive(pid) || !entry.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
if remove_scratch(&entry.path()).is_ok() {
removed += 1;
}
}
removed
}
fn scratch_pid(name: &str) -> Option<u32> {
let (pid, stamp) = name.strip_prefix("croft-demo-")?.split_once('-')?;
if stamp.is_empty() || !stamp.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
pid.parse().ok()
}
pub fn remove_scratch(dir: &Path) -> Result<(), String> {
if !dir.join(SCRATCH_MARKER).is_file() {
return Err(format!(
"{} is not a croft demo folder (no {SCRATCH_MARKER}); not deleting it",
dir.display()
));
}
std::fs::remove_dir_all(dir).map_err(|e| e.to_string())
}
pub fn first_error_ref(lines: &[String]) -> Option<(String, usize)> {
for line in lines {
if let Some(rest) = line.split("File \"").nth(1)
&& let Some((file, tail)) = rest.split_once("\", line ")
&& let Some(n) = tail
.split(|c: char| !c.is_ascii_digit())
.next()
.and_then(|d| d.parse().ok())
{
return Some((file.to_string(), n));
}
for token in line.split_whitespace() {
let mut parts = token.split(':');
let (Some(file), Some(n)) = (parts.next(), parts.next()) else {
continue;
};
if file.contains('.')
&& !file.contains("//")
&& let Ok(n) = n.parse::<usize>()
{
return Some((file.to_string(), n));
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_built_in_tour_parses_and_covers_the_issue_s_sequence() {
let tour = Tour::parse(TOUR_JSON).unwrap();
let actions: Vec<&TourAction> = tour.steps.iter().map(|s| &s.action).collect();
assert_eq!(actions[0], &TourAction::Open("src/main.rs".into()));
for want in [
TourAction::FindFile("app".into()),
TourAction::SplitEditor,
TourAction::Terminal,
TourAction::JumpToError,
TourAction::Palette("color theme".into()),
] {
assert!(actions.contains(&&want), "{want:?} in the tour");
}
assert_eq!(actions.last(), Some(&&TourAction::Done));
assert!(tour.steps.iter().all(|s| !s.caption.is_empty()));
for s in &tour.steps {
assert!(
!s.caption.contains("Cmd"),
"spell the modifier {{mod}}: {}",
s.caption
);
assert!(!s.caption_text().contains('{'), "{}", s.caption_text());
}
let files: Vec<&str> = sample_files().iter().map(|(p, _)| *p).collect();
for s in &tour.steps {
if let TourAction::Open(p) = &s.action {
assert!(files.contains(&p.as_str()), "{p} is in the sample");
}
}
}
#[test]
fn captions_name_the_platform_s_command_modifier() {
assert_eq!(expand_caption("{mod}+P finds", "Cmd"), "Cmd+P finds");
assert_eq!(
expand_caption("{mod}+Shift+P, or {mod}+click", "Ctrl"),
"Ctrl+Shift+P, or Ctrl+click"
);
let want = if cfg!(target_os = "macos") {
"Cmd+P"
} else {
"Ctrl+P"
};
let step = TourStep {
action: TourAction::QuickOpen,
caption: String::from("{mod}+P"),
};
assert_eq!(step.caption_text(), want);
let tour = Tour::parse(TOUR_JSON).unwrap();
assert!(
tour.steps
.iter()
.any(|s| s.caption_text().contains(&format!("{want} "))),
"the built-in tour teaches {want}"
);
}
#[test]
fn a_caption_without_the_placeholder_is_left_as_written() {
for caption in [
"Ctrl+J opens a real terminal inside croft.",
"{modifier} and {MOD} are not the placeholder",
"",
] {
assert_eq!(expand_caption(caption, "Cmd"), caption);
}
assert_eq!(expand_caption("{mod}{mod}", "Ctrl"), "CtrlCtrl");
}
fn scratch_like(parent: &Path, name: &str, marked: bool) -> PathBuf {
let dir = parent.join(name);
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(dir.join("src/main.rs"), "fn main() {}\n").unwrap();
if marked {
std::fs::write(dir.join(SCRATCH_MARKER), "croft demo scratch\n").unwrap();
}
dir
}
#[test]
fn a_dead_tour_s_marked_scratch_folder_is_swept() {
let parent = tempfile::tempdir().unwrap();
let dead = scratch_like(parent.path(), "croft-demo-585-1790000000000", true);
assert_eq!(sweep_dead_scratch(parent.path(), |_| false), 1);
assert!(!dead.exists());
}
#[cfg(unix)]
#[test]
fn the_sweep_keeps_live_unmarked_and_foreign_folders() {
let parent = tempfile::tempdir().unwrap();
let p = parent.path();
let me = std::process::id();
let mine = scratch_like(p, &format!("croft-demo-{me}-1"), true);
let live = scratch_like(p, "croft-demo-4242-1", true);
let unmarked = scratch_like(p, "croft-demo-585-2", false);
let foreign = [
scratch_like(p, "croft-demo-585", true),
scratch_like(p, "croft-demo-585-x1", true),
scratch_like(p, "croft-demo-pid-1", true),
scratch_like(p, "my-project", true),
];
let elsewhere = tempfile::tempdir().unwrap();
let target = scratch_like(elsewhere.path(), "real", true);
std::os::unix::fs::symlink(&target, p.join("croft-demo-586-1")).unwrap();
let removed = sweep_dead_scratch(p, |pid| pid == 4242);
assert_eq!(removed, 0);
for dir in [&mine, &live, &unmarked] {
assert!(dir.is_dir(), "{} kept", dir.display());
}
for dir in &foreign {
assert!(dir.is_dir(), "{} kept", dir.display());
}
assert!(
target.join(SCRATCH_MARKER).is_file(),
"a link's target kept"
);
assert_eq!(sweep_dead_scratch(&p.join("missing"), |_| false), 0);
}
#[test]
fn the_startup_demo_request_is_taken_once() {
request_startup_demo();
assert!(take_startup_demo());
assert!(!take_startup_demo());
}
#[test]
fn a_tour_steps_forward_and_ends() {
let mut t = Tour::parse(
r#"{"steps":[{"action":"quick_open","caption":"a"},{"action":"done","caption":"b"}]}"#,
)
.unwrap();
assert_eq!(t.current().unwrap().caption, "a");
assert_eq!(t.progress(), "1/2");
assert_eq!(t.advance().unwrap().caption, "b");
assert_eq!(t.progress(), "2/2");
assert!(t.advance().is_none());
assert!(t.current().is_none(), "past the end");
}
#[test]
fn a_malformed_tour_is_an_error() {
assert!(Tour::parse("{}").is_err());
assert!(Tour::parse(r#"{"steps":[{"action":"fly","caption":"x"}]}"#).is_err());
assert!(
Tour::parse(r#"{"steps":[]}"#).is_err(),
"an empty tour is not a tour"
);
}
#[test]
fn scratch_is_created_marked_and_only_marked_folders_are_removed() {
let parent = tempfile::tempdir().unwrap();
let dir = create_scratch(parent.path()).unwrap();
assert!(dir.join(SCRATCH_MARKER).is_file());
for (p, _) in sample_files() {
assert!(dir.join(p).is_file(), "{p} written");
}
remove_scratch(&dir).unwrap();
assert!(!dir.exists());
let real = tempfile::tempdir().unwrap();
std::fs::write(real.path().join("important.txt"), "keep").unwrap();
assert!(remove_scratch(real.path()).is_err(), "unmarked: refused");
assert!(
real.path().join("important.txt").exists(),
"nothing deleted"
);
}
#[test]
fn the_sample_build_fails_and_the_tour_can_find_the_line() {
let parent = tempfile::tempdir().unwrap();
let dir = create_scratch(parent.path()).unwrap();
let out = std::process::Command::new("python3")
.args(["-m", "py_compile", "app.py"])
.current_dir(&dir)
.output()
.expect("python3 is available");
assert!(!out.status.success(), "the sample build fails on purpose");
let text = String::from_utf8_lossy(&out.stderr);
let lines: Vec<String> = text.lines().map(str::to_string).collect();
let (file, line) = first_error_ref(&lines).expect("an error location");
assert!(file.ends_with("app.py"), "{file}");
assert!(line >= 1);
}
#[test]
fn errors_are_found_in_python_and_path_line_forms() {
let py = vec![
"$ python3 -m py_compile app.py".to_string(),
" File \"app.py\", line 3".to_string(),
" print(\"hello\"".to_string(),
];
assert_eq!(first_error_ref(&py), Some(("app.py".into(), 3)));
let rust = vec![
"error[E0425]: nope".to_string(),
" --> src/main.rs:12:5".to_string(),
];
assert_eq!(first_error_ref(&rust), Some(("src/main.rs".into(), 12)));
let gcc = vec!["main.c:7:3: error: expected ';'".to_string()];
assert_eq!(first_error_ref(&gcc), Some(("main.c".into(), 7)));
assert_eq!(first_error_ref(&["all good".to_string()]), None);
}
}