Compare commits

11 changed files with 46 additions and 155 deletions
+13 -22
View File
@@ -58,8 +58,6 @@ tour next 2
tour step 1 # jump to any step by number 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 ## Commands
### Author workflow ### Author workflow
@@ -71,40 +69,33 @@ Navigation clamps at the ends: `tour next` on the last step (or `tour prev` on t
| `tour unstage <files...>` | Remove files from staging | | `tour unstage <files...>` | Remove files from staging |
| `tour commit -m <msg>` | Commit staged files as a new step | | `tour commit -m <msg>` | Commit staged files as a new step |
| `tour commit <files...> -m <msg>` | Stage and commit files in one 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 | | `tour end -m <msg>` | Finalize the tour |
### Reader workflow ### Reader workflow
| Command | Alias | Description | | Command | Description |
|---------|-------|-------------| |---------|-------------|
| `tour start` | | Load the first step | | `tour start` | Load the first step |
| `tour next [n]` | `n` | Advance n steps (default 1) | | `tour next [n]` | Advance n steps (default 1) |
| `tour prev [n]` | `p` | Go back n steps (default 1) | | `tour prev [n]` | Go back n steps (default 1) |
| `tour step <n>` | `s` | Jump to step n | | `tour step <n>` | Jump to step n |
| `tour reset [--force]` | | Remove tracked files and clear the session (asks first) |
### Other ### Other
| Command | Alias | Description | | Command | Description |
|---------|-------|-------------| |---------|-------------|
| `tour info` | | Show tour metadata | | `tour info` | Show tour metadata |
| `tour status` | `st` | Show current step and staged files | | `tour status` | Show current step and staged files |
| `tour list` | `ls` | List all steps, marking the current one | | `tour list` | List all steps with messages |
| `tour help` | | Show help message | | `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 ## How it works
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. 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.
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: The `.tour/` directory contains:
- `steps/` — numbered directories, each holding the full file state for that step plus a `message` file - `steps/` — numbered directories, each holding the full file state for that step plus a `message` file
- `session` — tracks the reader's current position - `session` — tracks the reader's current position
- `info` — tour metadata (author, description, language, dates) - `info` — tour metadata (author, description, language, dates)
- `staged` — files staged for the next commit - `staged` — files staged for the next commit
- `removed` — files marked for removal in the next commit
- `ended` — marker indicating the tour is finalized - `ended` — marker indicating the tour is finalized
+3 -3
View File
@@ -1,6 +1,6 @@
use crate::error::TourError; use crate::error::TourError;
use crate::style::{green, reset}; use crate::style::{green, reset};
use crate::utils::{normalize_path, require_active, validate_paths}; use crate::utils::{require_tour, validate_paths};
use std::fs::{self, OpenOptions}; use std::fs::{self, OpenOptions};
use std::io::Write; use std::io::Write;
use std::path::PathBuf; use std::path::PathBuf;
@@ -8,7 +8,7 @@ use std::path::PathBuf;
pub const STAGED_PATH: &str = "./.tour/staged"; pub const STAGED_PATH: &str = "./.tour/staged";
pub fn add(files: Vec<PathBuf>) -> Result<(), TourError> { pub fn add(files: Vec<PathBuf>) -> Result<(), TourError> {
require_active()?; require_tour()?;
validate_paths(&files)?; validate_paths(&files)?;
let existing = get_staged()?; let existing = get_staged()?;
@@ -20,7 +20,7 @@ pub fn add(files: Vec<PathBuf>) -> Result<(), TourError> {
.open(STAGED_PATH)?; .open(STAGED_PATH)?;
for file in &files { for file in &files {
let normalized = normalize_path(file); let normalized: PathBuf = file.components().collect();
if existing_set.contains(&normalized) { if existing_set.contains(&normalized) {
println!("already staged: {}", normalized.display()); println!("already staged: {}", normalized.display());
} else { } else {
+7 -3
View File
@@ -2,16 +2,20 @@ use crate::add::{clear_staged, get_staged};
use crate::error::TourError; use crate::error::TourError;
use crate::rm::{clear_removed, get_removed}; use crate::rm::{clear_removed, get_removed};
use crate::style::{bold, reset}; use crate::style::{bold, reset};
use crate::utils::{copy_path, get_tour_step, normalize_path, require_active, validate_paths}; use crate::utils::{copy_path, get_tour_step, require_tour, validate_paths};
use crate::TOUR_DIR; use crate::TOUR_DIR;
use std::collections::HashSet; use std::collections::HashSet;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
pub fn commit(files: Vec<PathBuf>, message: String) -> Result<(), TourError> { pub fn commit(files: Vec<PathBuf>, message: String) -> Result<(), TourError> {
require_active()?; require_tour()?;
let tour_dir = Path::new(TOUR_DIR); let tour_dir = Path::new(TOUR_DIR);
if tour_dir.join("ended").exists() {
return Err(TourError::TourEnded);
}
let used_staging = files.is_empty(); let used_staging = files.is_empty();
let files = if used_staging { let files = if used_staging {
let staged = get_staged()?; let staged = get_staged()?;
@@ -20,7 +24,7 @@ pub fn commit(files: Vec<PathBuf>, message: String) -> Result<(), TourError> {
} }
staged staged
} else { } else {
files.iter().map(|f| normalize_path(f)).collect() files
}; };
validate_paths(&files)?; validate_paths(&files)?;
+2 -6
View File
@@ -17,12 +17,8 @@ pub fn init() -> Result<(), TourError> {
fs::File::create(tour_dir.join("session"))?; fs::File::create(tour_dir.join("session"))?;
// A prompt aborted with Ctrl-C/EOF must not leave a half-built .tour behind, crate::info::set_info()?;
// which would make every later `tour init` fail with TourAlreadyExists. update_gitignore()?;
if let Err(e) = crate::info::set_info().and_then(|_| update_gitignore()) {
let _ = fs::remove_dir_all(&tour_dir);
return Err(e.into());
}
Ok(()) Ok(())
} }
+1 -1
View File
@@ -8,7 +8,7 @@ use std::path::Path;
pub fn list() -> Result<(), TourError> { pub fn list() -> Result<(), TourError> {
require_tour()?; require_tour()?;
let total = get_tour_step()?; let total = get_tour_step()?;
let current = get_current_step()?; let current = get_current_step();
if total == 0 { if total == 0 {
println!("No steps yet."); println!("No steps yet.");
+6 -14
View File
@@ -1,6 +1,6 @@
use crate::error::TourError; use crate::error::TourError;
use crate::style::{red, reset}; use crate::style::{red, reset};
use crate::utils::{normalize_path, require_active}; use crate::utils::require_tour;
use std::collections::HashSet; use std::collections::HashSet;
use std::fs::{self, OpenOptions}; use std::fs::{self, OpenOptions};
use std::io::Write; use std::io::Write;
@@ -9,7 +9,7 @@ use std::path::PathBuf;
pub const REMOVED_PATH: &str = "./.tour/removed"; pub const REMOVED_PATH: &str = "./.tour/removed";
pub fn rm(files: Vec<PathBuf>) -> Result<(), TourError> { pub fn rm(files: Vec<PathBuf>) -> Result<(), TourError> {
require_active()?; require_tour()?;
let existing = get_removed()?; let existing = get_removed()?;
let existing_set: HashSet<PathBuf> = existing.into_iter().collect(); let existing_set: HashSet<PathBuf> = existing.into_iter().collect();
@@ -19,21 +19,13 @@ pub fn rm(files: Vec<PathBuf>) -> Result<(), TourError> {
.create(true) .create(true)
.open(REMOVED_PATH)?; .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 { for file in &files {
let file = normalize_path(file); if existing_set.contains(file) {
if existing_set.contains(&file) {
println!("already marked for removal: {}", file.display()); println!("already marked for removal: {}", file.display());
continue; } else {
writeln!(removed_file, "{}", file.display())?;
println!("{}marked for removal:{} {}", red(), reset(), file.display());
} }
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(()) Ok(())
+1 -1
View File
@@ -9,7 +9,7 @@ pub fn status() -> Result<(), TourError> {
let total = get_tour_step()?; let total = get_tour_step()?;
let ended = Path::new(TOUR_DIR).join("ended").exists(); 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 { "" }); 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 delta = n.unwrap_or(1);
let last = total - 1; let last = total - 1;
match get_current_step()? { match get_current_step() {
Some(current) if current >= last => { Some(current) if current >= last => {
println!("Already at the last step ({total}/{total})."); println!("Already at the last step ({total}/{total}).");
Ok(()) Ok(())
@@ -48,7 +48,7 @@ pub fn prev(n: Option<u32>) -> Result<(), TourError> {
return Err(TourError::NoStepsToNavigate); return Err(TourError::NoStepsToNavigate);
} }
let delta = n.unwrap_or(1); 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 { if current == 0 {
println!("Already at the first step (1/{total})."); println!("Already at the first step (1/{total}).");
return Ok(()); 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 // Files the tour owns in the working directory: the current step's set if a
// session exists, otherwise every file any step tracks (conservative). // 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() => { Some(current) if steps_dir.join(current.to_string()).is_dir() => {
let dir = steps_dir.join(current.to_string()); let dir = steps_dir.join(current.to_string());
let mut set = BTreeSet::new(); let mut set = BTreeSet::new();
+2 -3
View File
@@ -1,14 +1,13 @@
use crate::add::{get_staged, STAGED_PATH}; use crate::add::{get_staged, STAGED_PATH};
use crate::error::TourError; use crate::error::TourError;
use crate::utils::{normalize_path, require_active}; use crate::utils::require_tour;
use std::collections::HashSet; use std::collections::HashSet;
use std::fs; use std::fs;
use std::path::PathBuf; use std::path::PathBuf;
pub fn unstage(files: Vec<PathBuf>) -> Result<(), TourError> { pub fn unstage(files: Vec<PathBuf>) -> Result<(), TourError> {
require_active()?; require_tour()?;
let staged = get_staged()?; 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 to_remove: HashSet<&PathBuf> = files.iter().collect();
let remaining: Vec<&PathBuf> = staged.iter().filter(|f| !to_remove.contains(f)).collect(); let remaining: Vec<&PathBuf> = staged.iter().filter(|f| !to_remove.contains(f)).collect();
+8 -36
View File
@@ -13,42 +13,14 @@ pub fn require_tour() -> Result<(), TourError> {
Ok(()) Ok(())
} }
/// Fails the command if the tour is missing or already ended. Use for any pub fn get_current_step() -> Option<u32> {
/// command that mutates authoring state. fs::read_to_string(SESSION_PATH)
pub fn require_active() -> Result<(), TourError> { .ok()
require_tour()?; .and_then(|s| {
if Path::new(TOUR_DIR).join("ended").exists() { s.lines()
return Err(TourError::TourEnded); .find_map(|l| l.strip_prefix("STEP="))
} .and_then(|v| v.trim().parse::<u32>().ok())
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> { pub fn get_tour_step() -> Result<u32, TourError> {
-63
View File
@@ -698,66 +698,3 @@ fn test_old_format_tour_still_navigates() {
tour_cmd().arg("prev").current_dir(dir.path()).output().unwrap(); tour_cmd().arg("prev").current_dir(dir.path()).output().unwrap();
assert_eq!(fs::read_to_string(dir.path().join("f.txt")).unwrap(), "v0"); 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"));
}