Files
tour/src/init.rs
T
adamfandClaude Code 45da723d49 Clean up .tour on failed init
Aborting the metadata prompts (Ctrl-C/EOF) left a half-built .tour behind,
so every later `tour init` failed with TourAlreadyExists and no recovery.

Co-Authored-By: Claude Code <[email protected]>
2026-09-22 22:16:16 +01:00

56 lines
1.5 KiB
Rust

use crate::error::TourError;
use crate::TOUR_DIR;
use std::fs::{self, DirBuilder, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
pub fn init() -> Result<(), TourError> {
let tour_dir = PathBuf::from(TOUR_DIR);
if tour_dir.exists() {
return Err(TourError::TourAlreadyExists);
}
DirBuilder::new()
.recursive(true)
.create(tour_dir.join("steps"))?;
fs::File::create(tour_dir.join("session"))?;
// A prompt aborted with Ctrl-C/EOF must not leave a half-built .tour behind,
// which would make every later `tour init` fail with TourAlreadyExists.
if let Err(e) = crate::info::set_info().and_then(|_| update_gitignore()) {
let _ = fs::remove_dir_all(&tour_dir);
return Err(e.into());
}
Ok(())
}
fn update_gitignore() -> Result<(), std::io::Error> {
let gitignore = Path::new(".gitignore");
let entries = [".tour/session", ".tour/staged", ".tour/removed"];
let existing = fs::read_to_string(gitignore).unwrap_or_default();
let mut to_add = Vec::new();
for entry in &entries {
if !existing.lines().any(|l| l.trim() == *entry) {
to_add.push(*entry);
}
}
if !to_add.is_empty() {
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open(gitignore)?;
if !existing.is_empty() && !existing.ends_with('\n') {
writeln!(file)?;
}
for entry in to_add {
writeln!(file, "{}", entry)?;
}
}
Ok(())
}