Compare commits

Author SHA1 Message Date
adamfandClaude Code a81b1ace96 Normalise staged paths and reject staging on an ended tour
`tour rm ./f.txt` recorded "./f.txt", which never matched carry-forward's
"f.txt", so the file silently survived into the next step; unstage had the
same mismatch. normalize_path is now shared by add/rm/unstage/commit and
also strips the leading "." that components() keeps.

add/rm/unstage gain the ended-tour check commit already had, via a shared
require_active, so a finalised tour can't accumulate uncommittable staging.
rm now warns instead of silently accepting paths no step tracks.

Co-Authored-By: Claude Code <[email protected]>
2026-09-22 22:16:40 +01:00
adamfandClaude Code cbfb51f7c8 Treat an unreadable session file as corruption
get_current_step swallowed a bad STEP= value into None, which callers read
as "tour not started". It now returns Result<Option<u32>>: Ok(None) means no
session, a malformed STEP= means CorruptedTour.

Co-Authored-By: Claude Code <[email protected]>
2026-09-22 22:16:26 +01:00
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
adamfandClaude Fable 5 8c2d1df03f Update readme for new commands and storage model
Document aliases, clamping, rm/reset, color behavior, and hardlinked
snapshots (including the archiving caveat).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-07 13:42:57 +01:00
11 changed files with 155 additions and 46 deletions
+22 -13
View File
@@ -58,6 +58,8 @@ tour next 2
tour step 1 # jump to any step by number
```
Navigation clamps at the ends: `tour next` on the last step (or `tour prev` on the first) just tells you where you are instead of failing, and overshooting with `tour next 100` lands on the last step.
## Commands
### Author workflow
@@ -69,33 +71,40 @@ tour step 1 # jump to any step by number
| `tour unstage <files...>` | Remove files from staging |
| `tour commit -m <msg>` | Commit staged files as a new step |
| `tour commit <files...> -m <msg>` | Stage and commit files in one step |
| `tour rm <files...>` | Mark files for removal in the next commit |
| `tour end -m <msg>` | Finalize the tour |
### Reader workflow
| Command | Description |
|---------|-------------|
| `tour start` | Load the first step |
| `tour next [n]` | Advance n steps (default 1) |
| `tour prev [n]` | Go back n steps (default 1) |
| `tour step <n>` | Jump to step n |
| Command | Alias | Description |
|---------|-------|-------------|
| `tour start` | | Load the first step |
| `tour next [n]` | `n` | Advance n steps (default 1) |
| `tour prev [n]` | `p` | Go back n steps (default 1) |
| `tour step <n>` | `s` | Jump to step n |
| `tour reset [--force]` | | Remove tracked files and clear the session (asks first) |
### Other
| Command | Description |
|---------|-------------|
| `tour info` | Show tour metadata |
| `tour status` | Show current step and staged files |
| `tour list` | List all steps with messages |
| `tour help` | Show help message |
| Command | Alias | Description |
|---------|-------|-------------|
| `tour info` | | Show tour metadata |
| `tour status` | `st` | Show current step and staged files |
| `tour list` | `ls` | List all steps, marking the current one |
| `tour help` | | Show help message |
Colored output is automatic: it's disabled when output is piped or when the `NO_COLOR` environment variable is set.
## How it works
Each step is stored as a complete file snapshot in `.tour/steps/<N>/`. When navigating between steps, `tour` replaces tracked files in your working directory and shows a diff of what changed — new files, modified files (with line-level diffs), and deleted files.
Each step is stored as a complete file snapshot in `.tour/steps/<N>/`. When navigating between steps, `tour` touches only the files that differ between the current and target step, and shows a diff of what changed — new files, modified files (with line-level diffs), and deleted files.
Files that don't change between steps are hardlinked rather than copied, so a step only costs disk space for its changes. This is transparent — a tour looks and behaves like plain directories — but note that archiving `.tour/` with a tool that doesn't preserve hardlinks will expand it to full copies (correctness is unaffected).
The `.tour/` directory contains:
- `steps/` — numbered directories, each holding the full file state for that step plus a `message` file
- `session` — tracks the reader's current position
- `info` — tour metadata (author, description, language, dates)
- `staged` — files staged for the next commit
- `removed` — files marked for removal in the next commit
- `ended` — marker indicating the tour is finalized
+3 -3
View File
@@ -1,6 +1,6 @@
use crate::error::TourError;
use crate::style::{green, reset};
use crate::utils::{require_tour, validate_paths};
use crate::utils::{normalize_path, require_active, validate_paths};
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
@@ -8,7 +8,7 @@ use std::path::PathBuf;
pub const STAGED_PATH: &str = "./.tour/staged";
pub fn add(files: Vec<PathBuf>) -> Result<(), TourError> {
require_tour()?;
require_active()?;
validate_paths(&files)?;
let existing = get_staged()?;
@@ -20,7 +20,7 @@ pub fn add(files: Vec<PathBuf>) -> Result<(), TourError> {
.open(STAGED_PATH)?;
for file in &files {
let normalized: PathBuf = file.components().collect();
let normalized = normalize_path(file);
if existing_set.contains(&normalized) {
println!("already staged: {}", normalized.display());
} else {
+3 -7
View File
@@ -2,20 +2,16 @@ use crate::add::{clear_staged, get_staged};
use crate::error::TourError;
use crate::rm::{clear_removed, get_removed};
use crate::style::{bold, reset};
use crate::utils::{copy_path, get_tour_step, require_tour, validate_paths};
use crate::utils::{copy_path, get_tour_step, normalize_path, require_active, validate_paths};
use crate::TOUR_DIR;
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
pub fn commit(files: Vec<PathBuf>, message: String) -> Result<(), TourError> {
require_tour()?;
require_active()?;
let tour_dir = Path::new(TOUR_DIR);
if tour_dir.join("ended").exists() {
return Err(TourError::TourEnded);
}
let used_staging = files.is_empty();
let files = if used_staging {
let staged = get_staged()?;
@@ -24,7 +20,7 @@ pub fn commit(files: Vec<PathBuf>, message: String) -> Result<(), TourError> {
}
staged
} else {
files
files.iter().map(|f| normalize_path(f)).collect()
};
validate_paths(&files)?;
+6 -2
View File
@@ -17,8 +17,12 @@ pub fn init() -> Result<(), TourError> {
fs::File::create(tour_dir.join("session"))?;
crate::info::set_info()?;
update_gitignore()?;
// 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(())
}
+1 -1
View File
@@ -8,7 +8,7 @@ use std::path::Path;
pub fn list() -> Result<(), TourError> {
require_tour()?;
let total = get_tour_step()?;
let current = get_current_step();
let current = get_current_step()?;
if total == 0 {
println!("No steps yet.");
+14 -6
View File
@@ -1,6 +1,6 @@
use crate::error::TourError;
use crate::style::{red, reset};
use crate::utils::require_tour;
use crate::utils::{normalize_path, require_active};
use std::collections::HashSet;
use std::fs::{self, OpenOptions};
use std::io::Write;
@@ -9,7 +9,7 @@ use std::path::PathBuf;
pub const REMOVED_PATH: &str = "./.tour/removed";
pub fn rm(files: Vec<PathBuf>) -> Result<(), TourError> {
require_tour()?;
require_active()?;
let existing = get_removed()?;
let existing_set: HashSet<PathBuf> = existing.into_iter().collect();
@@ -19,13 +19,21 @@ pub fn rm(files: Vec<PathBuf>) -> Result<(), TourError> {
.create(true)
.open(REMOVED_PATH)?;
// Removal only has an effect on files a previous step actually snapshotted.
let tracked = crate::step::get_tracked_files()?;
for file in &files {
if existing_set.contains(file) {
let file = normalize_path(file);
if existing_set.contains(&file) {
println!("already marked for removal: {}", file.display());
} else {
writeln!(removed_file, "{}", file.display())?;
println!("{}marked for removal:{} {}", red(), reset(), file.display());
continue;
}
if !tracked.contains(&file) {
println!("not tracked by any step, ignoring: {}", file.display());
continue;
}
writeln!(removed_file, "{}", file.display())?;
println!("{}marked for removal:{} {}", red(), reset(), file.display());
}
Ok(())
+1 -1
View File
@@ -9,7 +9,7 @@ pub fn status() -> Result<(), TourError> {
let total = get_tour_step()?;
let ended = Path::new(TOUR_DIR).join("ended").exists();
let current = get_current_step();
let current = get_current_step()?;
println!("Tour: {} steps{}", total, if ended { " (ended)" } else { "" });
+3 -3
View File
@@ -31,7 +31,7 @@ pub fn next(n: Option<u32>) -> Result<(), TourError> {
}
let delta = n.unwrap_or(1);
let last = total - 1;
match get_current_step() {
match get_current_step()? {
Some(current) if current >= last => {
println!("Already at the last step ({total}/{total}).");
Ok(())
@@ -48,7 +48,7 @@ pub fn prev(n: Option<u32>) -> Result<(), TourError> {
return Err(TourError::NoStepsToNavigate);
}
let delta = n.unwrap_or(1);
let current = get_current_step().ok_or(TourError::NotStarted)?;
let current = get_current_step()?.ok_or(TourError::NotStarted)?;
if current == 0 {
println!("Already at the first step (1/{total}).");
return Ok(());
@@ -72,7 +72,7 @@ fn go_to_step(target: u32, total: u32) -> Result<(), TourError> {
// Files the tour owns in the working directory: the current step's set if a
// session exists, otherwise every file any step tracks (conservative).
let current_files = match get_current_step() {
let current_files = match get_current_step()? {
Some(current) if steps_dir.join(current.to_string()).is_dir() => {
let dir = steps_dir.join(current.to_string());
let mut set = BTreeSet::new();
+3 -2
View File
@@ -1,13 +1,14 @@
use crate::add::{get_staged, STAGED_PATH};
use crate::error::TourError;
use crate::utils::require_tour;
use crate::utils::{normalize_path, require_active};
use std::collections::HashSet;
use std::fs;
use std::path::PathBuf;
pub fn unstage(files: Vec<PathBuf>) -> Result<(), TourError> {
require_tour()?;
require_active()?;
let staged = get_staged()?;
let files: Vec<PathBuf> = files.iter().map(|f| normalize_path(f)).collect();
let to_remove: HashSet<&PathBuf> = files.iter().collect();
let remaining: Vec<&PathBuf> = staged.iter().filter(|f| !to_remove.contains(f)).collect();
+36 -8
View File
@@ -13,14 +13,42 @@ pub fn require_tour() -> Result<(), TourError> {
Ok(())
}
pub fn get_current_step() -> Option<u32> {
fs::read_to_string(SESSION_PATH)
.ok()
.and_then(|s| {
s.lines()
.find_map(|l| l.strip_prefix("STEP="))
.and_then(|v| v.trim().parse::<u32>().ok())
})
/// Fails the command if the tour is missing or already ended. Use for any
/// command that mutates authoring state.
pub fn require_active() -> Result<(), TourError> {
require_tour()?;
if Path::new(TOUR_DIR).join("ended").exists() {
return Err(TourError::TourEnded);
}
Ok(())
}
/// Collapses `./a/./b` to `a/b` so the same file always has one spelling in
/// the staged/removed lists and in step snapshots.
pub fn normalize_path(p: &Path) -> PathBuf {
// components() drops interior "." but keeps a leading one, so filter it out.
p.components()
.filter(|c| !matches!(c, std::path::Component::CurDir))
.collect()
}
/// `Ok(None)` means no session yet; a session file with an unreadable STEP is
/// corruption, not "not started".
pub fn get_current_step() -> Result<Option<u32>, TourError> {
let content = match fs::read_to_string(SESSION_PATH) {
Ok(c) => c,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e.into()),
};
match content.lines().find_map(|l| l.strip_prefix("STEP=")) {
None if content.trim().is_empty() => Ok(None),
None => Err(TourError::CorruptedTour(
"session file has no STEP= entry".into(),
)),
Some(v) => v.trim().parse::<u32>().map(Some).map_err(|_| {
TourError::CorruptedTour(format!("session step {:?} is not a number", v.trim()))
}),
}
}
pub fn get_tour_step() -> Result<u32, TourError> {
+63
View File
@@ -698,3 +698,66 @@ fn test_old_format_tour_still_navigates() {
tour_cmd().arg("prev").current_dir(dir.path()).output().unwrap();
assert_eq!(fs::read_to_string(dir.path().join("f.txt")).unwrap(), "v0");
}
// -- path normalisation, ended-tour guards, corrupt session --
#[test]
fn test_unstage_and_rm_normalize_paths() {
let dir = setup_dir();
init_tour(dir.path());
create_test_file(dir.path(), "f.txt", "a");
// Staged as "f.txt"; unstaging the "./f.txt" spelling must match it.
tour_cmd().args(["add", "f.txt"]).current_dir(dir.path()).output().unwrap();
let out = tour_cmd().args(["unstage", "./f.txt"]).current_dir(dir.path()).output().unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("unstaged: f.txt"), "got: {stdout}");
assert_eq!(fs::read_to_string(dir.path().join(".tour/staged")).unwrap(), "");
// Same for rm: "./f.txt" must match the tracked "f.txt" and be recorded normalized.
tour_cmd().args(["commit", "f.txt", "-m", "one"]).current_dir(dir.path()).output().unwrap();
let out = tour_cmd().args(["rm", "./f.txt"]).current_dir(dir.path()).output().unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("marked for removal: f.txt"), "got: {stdout}");
assert_eq!(fs::read_to_string(dir.path().join(".tour/removed")).unwrap(), "f.txt\n");
}
#[test]
fn test_rm_ignores_untracked_file() {
let dir = setup_dir();
init_tour(dir.path());
create_test_file(dir.path(), "f.txt", "a");
let out = tour_cmd().args(["rm", "f.txt"]).current_dir(dir.path()).output().unwrap();
assert!(String::from_utf8_lossy(&out.stdout).contains("not tracked"));
assert!(!dir.path().join(".tour/removed").exists()
|| fs::read_to_string(dir.path().join(".tour/removed")).unwrap().is_empty());
}
#[test]
fn test_staging_rejected_after_end() {
let dir = setup_dir();
init_tour(dir.path());
create_test_file(dir.path(), "f.txt", "a");
tour_cmd().args(["commit", "f.txt", "-m", "one"]).current_dir(dir.path()).output().unwrap();
tour_cmd().args(["end", "-m", "done"]).current_dir(dir.path()).output().unwrap();
for args in [vec!["add", "f.txt"], vec!["rm", "f.txt"], vec!["unstage", "f.txt"]] {
let out = tour_cmd().args(&args).current_dir(dir.path()).output().unwrap();
assert!(!out.status.success(), "{args:?} should fail on an ended tour");
assert!(String::from_utf8_lossy(&out.stderr).contains("already been ended"));
}
}
#[test]
fn test_corrupt_session_is_an_error() {
let dir = setup_dir();
init_tour(dir.path());
create_test_file(dir.path(), "f.txt", "a");
tour_cmd().args(["commit", "f.txt", "-m", "one"]).current_dir(dir.path()).output().unwrap();
fs::write(dir.path().join(".tour/session"), "STEP=banana").unwrap();
let out = tour_cmd().arg("status").current_dir(dir.path()).output().unwrap();
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("corrupted"));
}