Improve usability and efficiency
Usability: - Command aliases (n, p, s, ls, st) and positional step counts for next/prev - next/prev clamp at the tour ends instead of erroring - Color only when stdout is a TTY and NO_COLOR is unset (new style.rs) - reset asks for confirmation; --force required when non-interactive - IO errors carry operation context; friendlier not-started/no-steps errors - list marks the current step; consistent lowercase verb output - Handle SIGPIPE like other CLI tools instead of panicking when piped Efficiency: - Carry-forward hardlinks unchanged files between steps (copy fallback), so a step only costs disk for its changes; copy_path unlinks before overwriting so overlays can't write through a link - Navigation installs only files that differ (inode/size/byte compare) instead of two full-tree copies through a temp dir - Change report reads only changed files; LCS diff trims common prefix/suffix; path validation canonicalizes anchors once Adds 10 integration tests (rm carry-forward, reset --force, clamping, aliases, binary files, piped output, inode sharing, old-format compat, unchanged-file mtimes). Old tours need no migration. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
@@ -40,16 +40,18 @@ Entry point is `main.rs`, which uses clap's derive macro to parse subcommands an
|
||||
- `commit.rs` — commits staged files as a new step with carry-forward from previous step; only clears staging when staging was used
|
||||
- `rm.rs` — marks files for removal in the next commit (skipped during carry-forward)
|
||||
- `end.rs` — finalizes the tour (writes `.tour/ended` marker)
|
||||
- `step.rs` — navigation: `next`, `prev`, `step_n`; handles file replacement, diff display, binary detection
|
||||
- `reset.rs` — resets tour session and removes tracked files from working directory
|
||||
- `step.rs` — navigation: `next`, `prev`, `step_n`; installs only files that differ between steps, diff display, binary detection; `next`/`prev` clamp at the ends instead of erroring
|
||||
- `reset.rs` — resets tour session and removes tracked files from working directory; prompts for confirmation (or `--force` when non-interactive)
|
||||
- `status.rs` — shows current step position and staged files
|
||||
- `list.rs` — lists all steps with their messages
|
||||
- `list.rs` — lists all steps with their messages, marking the current one
|
||||
- `info.rs` — tour metadata (author, description, language, dates)
|
||||
- `utils.rs` — shared helpers: `require_tour`, `get_current_step`, `get_tour_step`, `copy_tree`, path validation
|
||||
- `error.rs` — unified `TourError` enum with `Display` impl for user-facing messages; includes `CorruptedTour` for integrity checks
|
||||
- `utils.rs` — shared helpers: `require_tour`, `get_current_step`, `get_tour_step`, `copy_path`, `validate_paths`
|
||||
- `error.rs` — unified `TourError` enum with `Display` impl for user-facing messages; includes `CorruptedTour` for integrity checks and an `IoResultExt::context` helper for annotating IO errors
|
||||
- `style.rs` — ANSI color helpers; emit color only when stdout is a TTY and `NO_COLOR` is unset
|
||||
|
||||
**Key design decisions:**
|
||||
- Each step is a **complete snapshot** — `commit.rs` carries forward files from the previous step before overlaying new ones
|
||||
- Each step is a **complete snapshot** — `commit.rs` carries forward files from the previous step before overlaying new ones. Carried-forward files are **hardlinked** (copy fallback), so a step only costs disk for its changes; because of this, anything overwriting a file inside `.tour/steps/` must unlink it first (see `copy_path`), and files installed into the working directory are always real copies, never links into the store
|
||||
- Navigation compares working-dir files against the target step (inode, then size, then bytes) and touches only files that differ
|
||||
- `TourError` is the unified error type across all modules, with `From<io::Error>` for automatic conversion
|
||||
- `main()` catches errors and prints them with `Display` format (not `Debug`) for user-friendly messages
|
||||
- Constants `TOUR_DIR` and `SESSION_PATH` are defined in `main.rs` and imported via `crate::`
|
||||
|
||||
Generated
+1
@@ -380,6 +380,7 @@ name = "tour"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"libc",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
|
||||
@@ -6,5 +6,8 @@ edition = "2024"
|
||||
[dependencies]
|
||||
clap = { version = "4.5.59", features = ["derive"] }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.26.0"
|
||||
|
||||
+5
-17
@@ -1,27 +1,15 @@
|
||||
use crate::error::TourError;
|
||||
use crate::utils::{is_descendant_of_current_dir, is_file_in_dir, require_tour};
|
||||
use crate::TOUR_DIR;
|
||||
use crate::style::{green, reset};
|
||||
use crate::utils::{require_tour, validate_paths};
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub const STAGED_PATH: &str = "./.tour/staged";
|
||||
|
||||
pub fn add(files: Vec<PathBuf>) -> Result<(), TourError> {
|
||||
require_tour()?;
|
||||
let tour_dir = Path::new(TOUR_DIR);
|
||||
|
||||
for file in &files {
|
||||
if !file.exists() {
|
||||
return Err(TourError::FileNotFound(file.clone()));
|
||||
}
|
||||
if !is_descendant_of_current_dir(file)? {
|
||||
return Err(TourError::NotADescendant(file.clone()));
|
||||
}
|
||||
if is_file_in_dir(file, tour_dir)? {
|
||||
return Err(TourError::InsideTourDir(file.clone()));
|
||||
}
|
||||
}
|
||||
validate_paths(&files)?;
|
||||
|
||||
let existing = get_staged()?;
|
||||
let existing_set: std::collections::HashSet<PathBuf> = existing.into_iter().collect();
|
||||
@@ -37,7 +25,7 @@ pub fn add(files: Vec<PathBuf>) -> Result<(), TourError> {
|
||||
println!("already staged: {}", normalized.display());
|
||||
} else {
|
||||
writeln!(staged, "{}", normalized.display())?;
|
||||
println!("staged: {}", normalized.display());
|
||||
println!("{}staged:{} {}", green(), reset(), normalized.display());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+9
-14
@@ -1,7 +1,8 @@
|
||||
use crate::add::{clear_staged, get_staged};
|
||||
use crate::error::TourError;
|
||||
use crate::rm::{clear_removed, get_removed};
|
||||
use crate::utils::{copy_path, get_tour_step, is_descendant_of_current_dir, is_file_in_dir, require_tour};
|
||||
use crate::style::{bold, reset};
|
||||
use crate::utils::{copy_path, get_tour_step, require_tour, validate_paths};
|
||||
use crate::TOUR_DIR;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
@@ -26,17 +27,7 @@ pub fn commit(files: Vec<PathBuf>, message: String) -> Result<(), TourError> {
|
||||
files
|
||||
};
|
||||
|
||||
for file in &files {
|
||||
if !file.exists() {
|
||||
return Err(TourError::FileNotFound(file.clone()));
|
||||
}
|
||||
if !is_descendant_of_current_dir(file)? {
|
||||
return Err(TourError::NotADescendant(file.clone()));
|
||||
}
|
||||
if is_file_in_dir(file, tour_dir)? {
|
||||
return Err(TourError::InsideTourDir(file.clone()));
|
||||
}
|
||||
}
|
||||
validate_paths(&files)?;
|
||||
|
||||
let removed = get_removed()?;
|
||||
let removed_set: HashSet<PathBuf> = removed.into_iter().collect();
|
||||
@@ -68,7 +59,7 @@ pub fn commit(files: Vec<PathBuf>, message: String) -> Result<(), TourError> {
|
||||
clear_removed()?;
|
||||
crate::info::update_last_modified()?;
|
||||
|
||||
println!("Step {}: {}", step_num + 1, message);
|
||||
println!("{}committed step {}{}: {}", bold(), step_num + 1, reset(), message);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -102,7 +93,11 @@ fn carry_forward(
|
||||
if let Some(parent) = dest.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::copy(entry.path(), &dest)?;
|
||||
// Unchanged files are hardlinked so a step costs only its changes;
|
||||
// fall back to a copy on filesystems without hardlink support.
|
||||
if fs::hard_link(entry.path(), &dest).is_err() {
|
||||
fs::copy(entry.path(), &dest)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -12,8 +12,12 @@ pub enum TourError {
|
||||
InsideTourDir(PathBuf),
|
||||
FileNotFound(PathBuf),
|
||||
StepOutOfRange { step: u32, total: u32 },
|
||||
NoStepsToNavigate,
|
||||
NotStarted,
|
||||
ResetNeedsForce,
|
||||
CorruptedTour(String),
|
||||
Io(io::Error),
|
||||
IoContext { context: String, source: io::Error },
|
||||
}
|
||||
|
||||
impl std::fmt::Display for TourError {
|
||||
@@ -40,12 +44,36 @@ impl std::fmt::Display for TourError {
|
||||
Self::StepOutOfRange { step, total } => {
|
||||
write!(f, "Step {} is out of range (1-{}).", step, total)
|
||||
}
|
||||
Self::NoStepsToNavigate => {
|
||||
write!(f, "This tour has no steps yet. Use `tour commit` to create one.")
|
||||
}
|
||||
Self::NotStarted => {
|
||||
write!(f, "Tour not started. Run `tour start` first.")
|
||||
}
|
||||
Self::ResetNeedsForce => {
|
||||
write!(f, "Refusing to reset without confirmation. Re-run with `--force`.")
|
||||
}
|
||||
Self::CorruptedTour(msg) => write!(f, "Tour data is corrupted: {}", msg),
|
||||
Self::Io(e) => write!(f, "{}", e),
|
||||
Self::IoContext { context, source } => write!(f, "{}: {}", context, source),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Attaches a human-readable operation description to an io::Error.
|
||||
pub trait IoResultExt<T> {
|
||||
fn context(self, ctx: impl Into<String>) -> Result<T, TourError>;
|
||||
}
|
||||
|
||||
impl<T> IoResultExt<T> for Result<T, io::Error> {
|
||||
fn context(self, ctx: impl Into<String>) -> Result<T, TourError> {
|
||||
self.map_err(|e| TourError::IoContext {
|
||||
context: ctx.into(),
|
||||
source: e,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TourError {}
|
||||
|
||||
impl From<io::Error> for TourError {
|
||||
|
||||
+8
-2
@@ -1,5 +1,6 @@
|
||||
use crate::error::TourError;
|
||||
use crate::utils::{get_tour_step, require_tour};
|
||||
use crate::style::{bold, reset};
|
||||
use crate::utils::{get_current_step, get_tour_step, require_tour};
|
||||
use crate::TOUR_DIR;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
@@ -7,6 +8,7 @@ use std::path::Path;
|
||||
pub fn list() -> Result<(), TourError> {
|
||||
require_tour()?;
|
||||
let total = get_tour_step()?;
|
||||
let current = get_current_step();
|
||||
|
||||
if total == 0 {
|
||||
println!("No steps yet.");
|
||||
@@ -17,7 +19,11 @@ pub fn list() -> Result<(), TourError> {
|
||||
let step_dir = Path::new(TOUR_DIR).join("steps").join(i.to_string());
|
||||
let message = fs::read_to_string(step_dir.join("message"))
|
||||
.unwrap_or_else(|_| "(no message)".into());
|
||||
println!(" {}. {}", i + 1, message.trim());
|
||||
if current == Some(i) {
|
||||
println!("{}> {}. {}{}", bold(), i + 1, message.trim(), reset());
|
||||
} else {
|
||||
println!(" {}. {}", i + 1, message.trim());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+29
-6
@@ -12,6 +12,7 @@ mod reset;
|
||||
mod rm;
|
||||
mod status;
|
||||
mod step;
|
||||
mod style;
|
||||
mod unstage;
|
||||
mod utils;
|
||||
|
||||
@@ -60,18 +61,27 @@ enum Commands {
|
||||
},
|
||||
|
||||
/// Advance n steps (default 1)
|
||||
#[command(visible_alias = "n")]
|
||||
Next {
|
||||
#[arg(short, value_name = "NUM STEPS")]
|
||||
#[arg(value_name = "N")]
|
||||
count: Option<u32>,
|
||||
|
||||
#[arg(short, value_name = "NUM STEPS", hide = true, conflicts_with = "count")]
|
||||
n: Option<u32>,
|
||||
},
|
||||
|
||||
/// Go back n steps (default 1)
|
||||
#[command(visible_alias = "p")]
|
||||
Prev {
|
||||
#[arg(short, value_name = "NUM STEPS")]
|
||||
#[arg(value_name = "N")]
|
||||
count: Option<u32>,
|
||||
|
||||
#[arg(short, value_name = "NUM STEPS", hide = true, conflicts_with = "count")]
|
||||
n: Option<u32>,
|
||||
},
|
||||
|
||||
/// Jump to step n
|
||||
#[command(visible_alias = "s")]
|
||||
Step {
|
||||
#[arg(value_name = "STEP")]
|
||||
n: u32,
|
||||
@@ -84,16 +94,29 @@ enum Commands {
|
||||
Info,
|
||||
|
||||
/// Show current step and staged files
|
||||
#[command(visible_alias = "st")]
|
||||
Status,
|
||||
|
||||
/// List all steps with messages
|
||||
#[command(visible_alias = "ls")]
|
||||
List,
|
||||
|
||||
/// Reset tour session and remove tracked files
|
||||
Reset,
|
||||
Reset {
|
||||
/// Skip the confirmation prompt
|
||||
#[arg(short, long)]
|
||||
force: bool,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Die quietly on a closed pipe (e.g. `tour list | head`) like other CLI
|
||||
// tools, instead of panicking; Rust ignores SIGPIPE by default.
|
||||
#[cfg(unix)]
|
||||
unsafe {
|
||||
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
|
||||
}
|
||||
|
||||
let args = Args::parse();
|
||||
let result = match args.command {
|
||||
Some(Commands::Init) => crate::init::init(),
|
||||
@@ -102,14 +125,14 @@ fn main() {
|
||||
Some(Commands::Commit { files, message }) => crate::commit::commit(files, message),
|
||||
Some(Commands::Rm { files }) => crate::rm::rm(files),
|
||||
Some(Commands::End { message }) => crate::end::end(message),
|
||||
Some(Commands::Next { n }) => crate::step::next(n),
|
||||
Some(Commands::Prev { n }) => crate::step::prev(n),
|
||||
Some(Commands::Next { count, n }) => crate::step::next(count.or(n)),
|
||||
Some(Commands::Prev { count, n }) => crate::step::prev(count.or(n)),
|
||||
Some(Commands::Step { n }) => crate::step::step_n(n),
|
||||
Some(Commands::Start) => crate::step::step_n(1),
|
||||
Some(Commands::Info) => crate::info::info(),
|
||||
Some(Commands::Status) => crate::status::status(),
|
||||
Some(Commands::List) => crate::list::list(),
|
||||
Some(Commands::Reset) => crate::reset::reset(),
|
||||
Some(Commands::Reset { force }) => crate::reset::reset(force),
|
||||
None => Ok(()),
|
||||
};
|
||||
if let Err(e) = result {
|
||||
|
||||
+22
-1
@@ -3,12 +3,33 @@ use crate::step;
|
||||
use crate::utils::require_tour;
|
||||
use crate::SESSION_PATH;
|
||||
use std::fs;
|
||||
use std::io::{self, IsTerminal, Write};
|
||||
|
||||
pub fn reset() -> Result<(), TourError> {
|
||||
pub fn reset(force: bool) -> Result<(), TourError> {
|
||||
require_tour()?;
|
||||
|
||||
let cwd = std::env::current_dir()?;
|
||||
let tracked = step::get_tracked_files()?;
|
||||
let count = tracked.iter().filter(|f| cwd.join(f).is_file()).count();
|
||||
|
||||
if !force && count > 0 {
|
||||
if !io::stdin().is_terminal() {
|
||||
return Err(TourError::ResetNeedsForce);
|
||||
}
|
||||
print!(
|
||||
"Remove {} tracked file{} from the working directory? [y/N] ",
|
||||
count,
|
||||
if count == 1 { "" } else { "s" }
|
||||
);
|
||||
io::stdout().flush()?;
|
||||
let mut answer = String::new();
|
||||
io::stdin().read_line(&mut answer)?;
|
||||
if !matches!(answer.trim(), "y" | "Y" | "yes") {
|
||||
println!("Aborted.");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
step::remove_tracked_files(&cwd, &tracked)?;
|
||||
|
||||
let _ = fs::remove_file(SESSION_PATH);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::error::TourError;
|
||||
use crate::style::{red, reset};
|
||||
use crate::utils::require_tour;
|
||||
use std::collections::HashSet;
|
||||
use std::fs::{self, OpenOptions};
|
||||
@@ -23,7 +24,7 @@ pub fn rm(files: Vec<PathBuf>) -> Result<(), TourError> {
|
||||
println!("already marked for removal: {}", file.display());
|
||||
} else {
|
||||
writeln!(removed_file, "{}", file.display())?;
|
||||
println!("marked for removal: {}", file.display());
|
||||
println!("{}marked for removal:{} {}", red(), reset(), file.display());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+158
-93
@@ -1,23 +1,21 @@
|
||||
use crate::error::TourError;
|
||||
use crate::utils::{copy_tree, get_current_step, get_tour_step, require_tour};
|
||||
use crate::error::{IoResultExt, TourError};
|
||||
use crate::style::{bold, cyan, green, red, reset};
|
||||
use crate::utils::{get_current_step, get_tour_step, require_tour};
|
||||
use crate::SESSION_PATH;
|
||||
use crate::TOUR_DIR;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const RED: &str = "\x1b[31m";
|
||||
const GREEN: &str = "\x1b[32m";
|
||||
const CYAN: &str = "\x1b[36m";
|
||||
const BOLD: &str = "\x1b[1m";
|
||||
const RESET: &str = "\x1b[0m";
|
||||
|
||||
/// Jump to step `n` (1-based, as shown to the user).
|
||||
pub fn step_n(n: u32) -> Result<(), TourError> {
|
||||
require_tour()?;
|
||||
let total = get_tour_step()?;
|
||||
|
||||
if total == 0 {
|
||||
return Err(TourError::NoStepsToNavigate);
|
||||
}
|
||||
if n < 1 || n > total {
|
||||
return Err(TourError::StepOutOfRange { step: n, total });
|
||||
}
|
||||
@@ -28,77 +26,142 @@ pub fn step_n(n: u32) -> Result<(), TourError> {
|
||||
pub fn next(n: Option<u32>) -> Result<(), TourError> {
|
||||
require_tour()?;
|
||||
let total = get_tour_step()?;
|
||||
if total == 0 {
|
||||
return Err(TourError::NoStepsToNavigate);
|
||||
}
|
||||
let delta = n.unwrap_or(1);
|
||||
let target = match get_current_step() {
|
||||
Some(c) => c.saturating_add(delta),
|
||||
None if delta > 0 => delta - 1,
|
||||
None => return Err(TourError::StepOutOfRange { step: 0, total }),
|
||||
};
|
||||
if target >= total {
|
||||
return Err(TourError::StepOutOfRange {
|
||||
step: target + 1,
|
||||
total,
|
||||
});
|
||||
let last = total - 1;
|
||||
match get_current_step() {
|
||||
Some(current) if current >= last => {
|
||||
println!("Already at the last step ({total}/{total}).");
|
||||
Ok(())
|
||||
}
|
||||
Some(current) => go_to_step(current.saturating_add(delta).min(last), total),
|
||||
None => go_to_step(delta.saturating_sub(1).min(last), total),
|
||||
}
|
||||
go_to_step(target, total)
|
||||
}
|
||||
|
||||
pub fn prev(n: Option<u32>) -> Result<(), TourError> {
|
||||
require_tour()?;
|
||||
let total = get_tour_step()?;
|
||||
if total == 0 {
|
||||
return Err(TourError::NoStepsToNavigate);
|
||||
}
|
||||
let delta = n.unwrap_or(1);
|
||||
let current = get_current_step().ok_or(TourError::StepOutOfRange { step: 0, total })?;
|
||||
let target = current
|
||||
.checked_sub(delta)
|
||||
.ok_or(TourError::StepOutOfRange { step: 0, total })?;
|
||||
go_to_step(target, total)
|
||||
let current = get_current_step().ok_or(TourError::NotStarted)?;
|
||||
if current == 0 {
|
||||
println!("Already at the first step (1/{total}).");
|
||||
return Ok(());
|
||||
}
|
||||
go_to_step(current.saturating_sub(delta), total)
|
||||
}
|
||||
|
||||
enum FileChange {
|
||||
Added,
|
||||
Modified { old: Option<String>, new: Option<String> },
|
||||
Removed,
|
||||
}
|
||||
|
||||
fn go_to_step(target: u32, total: u32) -> Result<(), TourError> {
|
||||
let cwd = std::env::current_dir()?;
|
||||
let tracked = get_tracked_files()?;
|
||||
let old_files = snapshot_tracked_files(&cwd, &tracked)?;
|
||||
let steps_dir = Path::new(TOUR_DIR).join("steps");
|
||||
let target_dir = steps_dir.join(target.to_string());
|
||||
|
||||
// Stage new step files to a temp dir first — if this fails, working files are untouched
|
||||
let step_dir = Path::new(TOUR_DIR).join("steps").join(target.to_string());
|
||||
let tmp_dir = Path::new(TOUR_DIR).join("tmp_step");
|
||||
if tmp_dir.exists() {
|
||||
fs::remove_dir_all(&tmp_dir)?;
|
||||
let mut target_files = BTreeSet::new();
|
||||
collect_step_files(&target_dir, &target_dir, &mut target_files)?;
|
||||
|
||||
// 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() {
|
||||
Some(current) if steps_dir.join(current.to_string()).is_dir() => {
|
||||
let dir = steps_dir.join(current.to_string());
|
||||
let mut set = BTreeSet::new();
|
||||
collect_step_files(&dir, &dir, &mut set)?;
|
||||
set
|
||||
}
|
||||
_ => get_tracked_files()?,
|
||||
};
|
||||
|
||||
// Work out the full change set before touching the working directory
|
||||
let mut changes: Vec<(PathBuf, FileChange)> = Vec::new();
|
||||
let mut to_install: Vec<PathBuf> = Vec::new();
|
||||
for relative in &target_files {
|
||||
let wd_file = cwd.join(relative);
|
||||
let step_file = target_dir.join(relative);
|
||||
if !wd_file.is_file() {
|
||||
changes.push((relative.clone(), FileChange::Added));
|
||||
to_install.push(relative.clone());
|
||||
} else if !files_equal(&wd_file, &step_file)? {
|
||||
changes.push((
|
||||
relative.clone(),
|
||||
FileChange::Modified {
|
||||
old: fs::read_to_string(&wd_file).ok(),
|
||||
new: fs::read_to_string(&step_file).ok(),
|
||||
},
|
||||
));
|
||||
to_install.push(relative.clone());
|
||||
}
|
||||
}
|
||||
fs::create_dir_all(&tmp_dir)?;
|
||||
for entry in fs::read_dir(&step_dir)? {
|
||||
let entry = entry?;
|
||||
if entry.file_name() == "message" {
|
||||
continue;
|
||||
let to_delete: BTreeSet<PathBuf> = current_files
|
||||
.difference(&target_files)
|
||||
.cloned()
|
||||
.collect();
|
||||
for relative in &to_delete {
|
||||
if cwd.join(relative).is_file() {
|
||||
changes.push((relative.clone(), FileChange::Removed));
|
||||
}
|
||||
copy_tree(&entry.path(), &tmp_dir.join(entry.file_name()))?;
|
||||
}
|
||||
|
||||
// Now safe to remove old tracked files and install the new ones
|
||||
remove_tracked_files(&cwd, &tracked)?;
|
||||
for entry in fs::read_dir(&tmp_dir)? {
|
||||
let entry = entry?;
|
||||
copy_tree(&entry.path(), &cwd.join(entry.file_name()))?;
|
||||
// Install only the files that differ. Always copy — never link into the
|
||||
// snapshot store — so user edits can't write through to step data.
|
||||
for relative in &to_install {
|
||||
let dest = cwd.join(relative);
|
||||
if let Some(parent) = dest.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
if dest.exists() {
|
||||
fs::remove_file(&dest)?;
|
||||
}
|
||||
fs::copy(target_dir.join(relative), &dest)
|
||||
.context(format!("failed to install {}", relative.display()))?;
|
||||
}
|
||||
fs::remove_dir_all(&tmp_dir)?;
|
||||
remove_tracked_files(&cwd, &to_delete)?;
|
||||
|
||||
// Persist the new step
|
||||
fs::write(SESSION_PATH, format!("STEP={}", target))?;
|
||||
fs::write(SESSION_PATH, format!("STEP={}", target))
|
||||
.context("failed to save session")?;
|
||||
|
||||
let new_files = snapshot_tracked_files(&cwd, &tracked)?;
|
||||
print_changes(&old_files, &new_files);
|
||||
print_changes(&changes);
|
||||
|
||||
let message = fs::read_to_string(step_dir.join("message"))
|
||||
let message = fs::read_to_string(target_dir.join("message"))
|
||||
.unwrap_or_else(|_| "(no message)".into());
|
||||
println!(
|
||||
"\n{BOLD}Step {}/{total}:{RESET} {}",
|
||||
"\n{}Step {}/{total}:{} {}",
|
||||
bold(),
|
||||
target + 1,
|
||||
reset(),
|
||||
message.trim()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fast equality check: same inode, then size, then contents.
|
||||
fn files_equal(a: &Path, b: &Path) -> Result<bool, io::Error> {
|
||||
let meta_a = fs::metadata(a)?;
|
||||
let meta_b = fs::metadata(b)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
if meta_a.dev() == meta_b.dev() && meta_a.ino() == meta_b.ino() {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
if meta_a.len() != meta_b.len() {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(fs::read(a)? == fs::read(b)?)
|
||||
}
|
||||
|
||||
pub fn get_tracked_files() -> Result<BTreeSet<PathBuf>, io::Error> {
|
||||
let steps_dir = Path::new(TOUR_DIR).join("steps");
|
||||
let mut tracked = BTreeSet::new();
|
||||
@@ -161,41 +224,22 @@ fn collect_step_files(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Snapshots tracked files from root. Returns None for binary files (invalid UTF-8).
|
||||
fn snapshot_tracked_files(
|
||||
root: &Path,
|
||||
tracked: &BTreeSet<PathBuf>,
|
||||
) -> Result<BTreeMap<PathBuf, Option<String>>, io::Error> {
|
||||
let mut files = BTreeMap::new();
|
||||
for relative in tracked {
|
||||
let full = root.join(relative);
|
||||
if full.is_file() {
|
||||
files.insert(relative.clone(), fs::read_to_string(&full).ok());
|
||||
}
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn print_changes(
|
||||
old: &BTreeMap<PathBuf, Option<String>>,
|
||||
new: &BTreeMap<PathBuf, Option<String>>,
|
||||
) {
|
||||
for (path, new_content) in new {
|
||||
match old.get(path) {
|
||||
None => println!("{GREEN} new: {}{RESET}", path.display()),
|
||||
Some(old_content) if old_content != new_content => {
|
||||
println!("{CYAN} modified: {}{RESET}", path.display());
|
||||
match (old_content, new_content) {
|
||||
fn print_changes(changes: &[(PathBuf, FileChange)]) {
|
||||
for (path, change) in changes {
|
||||
match change {
|
||||
FileChange::Added => {
|
||||
println!("{} new: {}{}", green(), path.display(), reset())
|
||||
}
|
||||
FileChange::Modified { old, new } => {
|
||||
println!("{} modified: {}{}", cyan(), path.display(), reset());
|
||||
match (old, new) {
|
||||
(Some(o), Some(n)) => print_diff(o, n),
|
||||
_ => println!(" (binary file)"),
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for path in old.keys() {
|
||||
if !new.contains_key(path) {
|
||||
println!("{RED} deleted: {}{RESET}", path.display());
|
||||
FileChange::Removed => {
|
||||
println!("{} deleted: {}{}", red(), path.display(), reset())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -204,19 +248,36 @@ fn print_diff(old: &str, new: &str) {
|
||||
let old_lines: Vec<&str> = old.lines().collect();
|
||||
let new_lines: Vec<&str> = new.lines().collect();
|
||||
|
||||
let m = old_lines.len();
|
||||
let n = new_lines.len();
|
||||
// Trim the common prefix and suffix so the LCS table only covers the
|
||||
// changed middle of the file.
|
||||
let mut start = 0;
|
||||
while start < old_lines.len()
|
||||
&& start < new_lines.len()
|
||||
&& old_lines[start] == new_lines[start]
|
||||
{
|
||||
start += 1;
|
||||
}
|
||||
let (mut old_end, mut new_end) = (old_lines.len(), new_lines.len());
|
||||
while old_end > start && new_end > start && old_lines[old_end - 1] == new_lines[new_end - 1] {
|
||||
old_end -= 1;
|
||||
new_end -= 1;
|
||||
}
|
||||
|
||||
let old_mid = &old_lines[start..old_end];
|
||||
let new_mid = &new_lines[start..new_end];
|
||||
let m = old_mid.len();
|
||||
let n = new_mid.len();
|
||||
|
||||
if m > 1000 || n > 1000 {
|
||||
println!(" (file changed)");
|
||||
return;
|
||||
}
|
||||
|
||||
// LCS table
|
||||
// LCS table over the changed middle
|
||||
let mut dp = vec![vec![0usize; n + 1]; m + 1];
|
||||
for i in 1..=m {
|
||||
for j in 1..=n {
|
||||
if old_lines[i - 1] == new_lines[j - 1] {
|
||||
if old_mid[i - 1] == new_mid[j - 1] {
|
||||
dp[i][j] = dp[i - 1][j - 1] + 1;
|
||||
} else {
|
||||
dp[i][j] = dp[i - 1][j].max(dp[i][j - 1]);
|
||||
@@ -225,22 +286,26 @@ fn print_diff(old: &str, new: &str) {
|
||||
}
|
||||
|
||||
// Backtrack
|
||||
let mut ops: Vec<(char, &str)> = Vec::new();
|
||||
let mut mid_ops: Vec<(char, &str)> = Vec::new();
|
||||
let (mut i, mut j) = (m, n);
|
||||
while i > 0 || j > 0 {
|
||||
if i > 0 && j > 0 && old_lines[i - 1] == new_lines[j - 1] {
|
||||
ops.push((' ', old_lines[i - 1]));
|
||||
if i > 0 && j > 0 && old_mid[i - 1] == new_mid[j - 1] {
|
||||
mid_ops.push((' ', old_mid[i - 1]));
|
||||
i -= 1;
|
||||
j -= 1;
|
||||
} else if j > 0 && (i == 0 || dp[i][j - 1] >= dp[i - 1][j]) {
|
||||
ops.push(('+', new_lines[j - 1]));
|
||||
mid_ops.push(('+', new_mid[j - 1]));
|
||||
j -= 1;
|
||||
} else {
|
||||
ops.push(('-', old_lines[i - 1]));
|
||||
mid_ops.push(('-', old_mid[i - 1]));
|
||||
i -= 1;
|
||||
}
|
||||
}
|
||||
ops.reverse();
|
||||
mid_ops.reverse();
|
||||
|
||||
let mut ops: Vec<(char, &str)> = old_lines[..start].iter().map(|l| (' ', *l)).collect();
|
||||
ops.extend(mid_ops);
|
||||
ops.extend(old_lines[old_end..].iter().map(|l| (' ', *l)));
|
||||
|
||||
// Print with context: only show changed lines and up to 2 surrounding context lines
|
||||
const CTX: usize = 2;
|
||||
@@ -275,8 +340,8 @@ fn print_diff(old: &str, new: &str) {
|
||||
}
|
||||
prev_visible = true;
|
||||
match op {
|
||||
'+' => println!("{GREEN} + {line}{RESET}"),
|
||||
'-' => println!("{RED} - {line}{RESET}"),
|
||||
'+' => println!("{} + {line}{}", green(), reset()),
|
||||
'-' => println!("{} - {line}{}", red(), reset()),
|
||||
_ => println!(" {line}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
use std::io::IsTerminal;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// Color is emitted only when stdout is a terminal and NO_COLOR is unset.
|
||||
fn enabled() -> bool {
|
||||
static ENABLED: OnceLock<bool> = OnceLock::new();
|
||||
*ENABLED.get_or_init(|| {
|
||||
std::env::var_os("NO_COLOR").is_none() && std::io::stdout().is_terminal()
|
||||
})
|
||||
}
|
||||
|
||||
fn code(c: &'static str) -> &'static str {
|
||||
if enabled() { c } else { "" }
|
||||
}
|
||||
|
||||
pub fn red() -> &'static str {
|
||||
code("\x1b[31m")
|
||||
}
|
||||
|
||||
pub fn green() -> &'static str {
|
||||
code("\x1b[32m")
|
||||
}
|
||||
|
||||
pub fn cyan() -> &'static str {
|
||||
code("\x1b[36m")
|
||||
}
|
||||
|
||||
pub fn bold() -> &'static str {
|
||||
code("\x1b[1m")
|
||||
}
|
||||
|
||||
pub fn reset() -> &'static str {
|
||||
code("\x1b[0m")
|
||||
}
|
||||
+23
-25
@@ -1,8 +1,8 @@
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::error::TourError;
|
||||
use crate::error::{IoResultExt, TourError};
|
||||
use crate::SESSION_PATH;
|
||||
use crate::TOUR_DIR;
|
||||
|
||||
@@ -25,7 +25,8 @@ pub fn get_current_step() -> Option<u32> {
|
||||
|
||||
pub fn get_tour_step() -> Result<u32, TourError> {
|
||||
let steps_dir = Path::new(TOUR_DIR).join("steps");
|
||||
let mut indices: Vec<u32> = fs::read_dir(&steps_dir)?
|
||||
let mut indices: Vec<u32> = fs::read_dir(&steps_dir)
|
||||
.context(format!("failed to read steps directory {}", steps_dir.display()))?
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| e.path().is_dir())
|
||||
.filter_map(|e| e.file_name().to_str()?.parse::<u32>().ok())
|
||||
@@ -75,35 +76,32 @@ pub fn copy_path(src: &Path, dest_dir: &Path) -> Result<(), io::Error> {
|
||||
if let Some(parent) = dest.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
// Unlink first: the destination may be hardlinked into a previous
|
||||
// step's snapshot, and copying in place would write through the link.
|
||||
if dest.exists() {
|
||||
fs::remove_file(&dest)?;
|
||||
}
|
||||
fs::copy(src, &dest)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Recursively copies src to dest. If src is a directory, copies its contents
|
||||
/// into dest. If src is a file, copies it to dest.
|
||||
pub fn copy_tree(src: &Path, dest: &Path) -> Result<(), io::Error> {
|
||||
if src.is_dir() {
|
||||
fs::create_dir_all(dest)?;
|
||||
for entry in fs::read_dir(src)? {
|
||||
let entry = entry?;
|
||||
copy_tree(&entry.path(), &dest.join(entry.file_name()))?;
|
||||
/// Validates that every path exists, lives under the working directory, and is
|
||||
/// not inside the .tour directory. Canonicalizes the anchors once, not per file.
|
||||
pub fn validate_paths(files: &[PathBuf]) -> Result<(), TourError> {
|
||||
let cwd = std::env::current_dir()?.canonicalize()?;
|
||||
let tour_canon = Path::new(TOUR_DIR).canonicalize()?;
|
||||
for file in files {
|
||||
if !file.exists() {
|
||||
return Err(TourError::FileNotFound(file.clone()));
|
||||
}
|
||||
} else {
|
||||
if let Some(parent) = dest.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
let canon = file.canonicalize()?;
|
||||
if !canon.starts_with(&cwd) {
|
||||
return Err(TourError::NotADescendant(file.clone()));
|
||||
}
|
||||
if canon.starts_with(&tour_canon) {
|
||||
return Err(TourError::InsideTourDir(file.clone()));
|
||||
}
|
||||
fs::copy(src, dest)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_descendant_of_current_dir(file: &Path) -> Result<bool, io::Error> {
|
||||
is_file_in_dir(file, &std::env::current_dir()?)
|
||||
}
|
||||
|
||||
pub fn is_file_in_dir(file: &Path, dir: &Path) -> Result<bool, io::Error> {
|
||||
let file_canon = file.canonicalize()?;
|
||||
let dir_canon = dir.canonicalize()?;
|
||||
Ok(file_canon.starts_with(&dir_canon))
|
||||
}
|
||||
|
||||
+227
-2
@@ -7,8 +7,7 @@ fn tour_cmd() -> Command {
|
||||
}
|
||||
|
||||
fn setup_dir() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().expect("failed to create temp dir");
|
||||
dir
|
||||
tempfile::tempdir().expect("failed to create temp dir")
|
||||
}
|
||||
|
||||
fn init_tour(dir: &Path) {
|
||||
@@ -473,3 +472,229 @@ fn test_status_shows_info() {
|
||||
assert!(stdout.contains("1 steps"), "expected step count in: {}", stdout);
|
||||
assert!(stdout.contains("not started"), "expected 'not started' in: {}", stdout);
|
||||
}
|
||||
|
||||
// -- rm tests --
|
||||
|
||||
#[test]
|
||||
fn test_rm_excludes_file_from_carry_forward() {
|
||||
let dir = setup_dir();
|
||||
init_tour(dir.path());
|
||||
|
||||
create_test_file(dir.path(), "a.txt", "aaa");
|
||||
create_test_file(dir.path(), "b.txt", "bbb");
|
||||
tour_cmd().args(["commit", "a.txt", "b.txt", "-m", "s1"]).current_dir(dir.path()).output().unwrap();
|
||||
|
||||
tour_cmd().args(["rm", "b.txt"]).current_dir(dir.path()).output().unwrap();
|
||||
create_test_file(dir.path(), "a.txt", "aaa v2");
|
||||
tour_cmd().args(["commit", "a.txt", "-m", "s2"]).current_dir(dir.path()).output().unwrap();
|
||||
|
||||
assert!(dir.path().join(".tour/steps/1/a.txt").exists());
|
||||
assert!(!dir.path().join(".tour/steps/1/b.txt").exists(), "b.txt should not carry forward after rm");
|
||||
|
||||
// Navigating from step 2 back to step 1 restores b.txt; forward removes it
|
||||
tour_cmd().arg("start").current_dir(dir.path()).output().unwrap();
|
||||
assert!(dir.path().join("b.txt").exists());
|
||||
tour_cmd().arg("next").current_dir(dir.path()).output().unwrap();
|
||||
assert!(!dir.path().join("b.txt").exists(), "b.txt should be deleted at step 2");
|
||||
}
|
||||
|
||||
// -- reset tests --
|
||||
|
||||
#[test]
|
||||
fn test_reset_requires_force_when_not_interactive() {
|
||||
let dir = setup_dir();
|
||||
init_tour(dir.path());
|
||||
create_test_file(dir.path(), "f.txt", "data");
|
||||
tour_cmd().args(["commit", "f.txt", "-m", "s1"]).current_dir(dir.path()).output().unwrap();
|
||||
tour_cmd().arg("start").current_dir(dir.path()).output().unwrap();
|
||||
|
||||
// Without --force and stdin not a tty, reset must refuse
|
||||
let output = tour_cmd().arg("reset").current_dir(dir.path()).output().unwrap();
|
||||
assert!(!output.status.success(), "reset without --force should fail non-interactively");
|
||||
assert!(dir.path().join("f.txt").exists(), "files must be untouched after refused reset");
|
||||
|
||||
// With --force it proceeds
|
||||
let output = tour_cmd().args(["reset", "--force"]).current_dir(dir.path()).output().unwrap();
|
||||
assert!(output.status.success(), "reset --force failed: {}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(!dir.path().join("f.txt").exists(), "tracked file should be removed");
|
||||
assert!(!dir.path().join(".tour/session").exists(), "session should be cleared");
|
||||
}
|
||||
|
||||
// -- navigation clamping and count tests --
|
||||
|
||||
#[test]
|
||||
fn test_next_clamps_at_last_step() {
|
||||
let dir = setup_dir();
|
||||
init_tour(dir.path());
|
||||
create_test_file(dir.path(), "f.txt", "v0");
|
||||
tour_cmd().args(["commit", "f.txt", "-m", "s0"]).current_dir(dir.path()).output().unwrap();
|
||||
create_test_file(dir.path(), "f.txt", "v1");
|
||||
tour_cmd().args(["commit", "f.txt", "-m", "s1"]).current_dir(dir.path()).output().unwrap();
|
||||
tour_cmd().arg("start").current_dir(dir.path()).output().unwrap();
|
||||
|
||||
// Overshooting clamps to the last step
|
||||
let output = tour_cmd().args(["next", "10"]).current_dir(dir.path()).output().unwrap();
|
||||
assert!(output.status.success(), "next 10 should clamp, not fail");
|
||||
assert_eq!(fs::read_to_string(dir.path().join("f.txt")).unwrap(), "v1");
|
||||
|
||||
// At the last step, next is a friendly no-op
|
||||
let output = tour_cmd().arg("next").current_dir(dir.path()).output().unwrap();
|
||||
assert!(output.status.success());
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("Already at the last step"), "got: {}", stdout);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prev_clamps_at_first_step() {
|
||||
let dir = setup_dir();
|
||||
init_tour(dir.path());
|
||||
create_test_file(dir.path(), "f.txt", "v0");
|
||||
tour_cmd().args(["commit", "f.txt", "-m", "s0"]).current_dir(dir.path()).output().unwrap();
|
||||
create_test_file(dir.path(), "f.txt", "v1");
|
||||
tour_cmd().args(["commit", "f.txt", "-m", "s1"]).current_dir(dir.path()).output().unwrap();
|
||||
|
||||
tour_cmd().args(["step", "2"]).current_dir(dir.path()).output().unwrap();
|
||||
|
||||
// Overshooting backwards clamps to the first step
|
||||
let output = tour_cmd().args(["prev", "10"]).current_dir(dir.path()).output().unwrap();
|
||||
assert!(output.status.success(), "prev 10 should clamp, not fail");
|
||||
assert_eq!(fs::read_to_string(dir.path().join("f.txt")).unwrap(), "v0");
|
||||
|
||||
let output = tour_cmd().arg("prev").current_dir(dir.path()).output().unwrap();
|
||||
assert!(output.status.success());
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("Already at the first step"), "got: {}", stdout);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_command_aliases() {
|
||||
let dir = setup_dir();
|
||||
init_tour(dir.path());
|
||||
create_test_file(dir.path(), "f.txt", "v0");
|
||||
tour_cmd().args(["commit", "f.txt", "-m", "s0"]).current_dir(dir.path()).output().unwrap();
|
||||
create_test_file(dir.path(), "f.txt", "v1");
|
||||
tour_cmd().args(["commit", "f.txt", "-m", "s1"]).current_dir(dir.path()).output().unwrap();
|
||||
|
||||
tour_cmd().args(["s", "1"]).current_dir(dir.path()).output().unwrap();
|
||||
assert_eq!(fs::read_to_string(dir.path().join("f.txt")).unwrap(), "v0");
|
||||
|
||||
let output = tour_cmd().arg("n").current_dir(dir.path()).output().unwrap();
|
||||
assert!(output.status.success(), "alias n failed: {}", String::from_utf8_lossy(&output.stderr));
|
||||
assert_eq!(fs::read_to_string(dir.path().join("f.txt")).unwrap(), "v1");
|
||||
|
||||
let output = tour_cmd().arg("p").current_dir(dir.path()).output().unwrap();
|
||||
assert!(output.status.success(), "alias p failed");
|
||||
assert_eq!(fs::read_to_string(dir.path().join("f.txt")).unwrap(), "v0");
|
||||
|
||||
assert!(tour_cmd().arg("ls").current_dir(dir.path()).output().unwrap().status.success());
|
||||
assert!(tour_cmd().arg("st").current_dir(dir.path()).output().unwrap().status.success());
|
||||
}
|
||||
|
||||
// -- output style tests --
|
||||
|
||||
#[test]
|
||||
fn test_no_ansi_codes_when_piped() {
|
||||
let dir = setup_dir();
|
||||
init_tour(dir.path());
|
||||
create_test_file(dir.path(), "f.txt", "v0\n");
|
||||
tour_cmd().args(["commit", "f.txt", "-m", "s0"]).current_dir(dir.path()).output().unwrap();
|
||||
create_test_file(dir.path(), "f.txt", "v1\n");
|
||||
tour_cmd().args(["commit", "f.txt", "-m", "s1"]).current_dir(dir.path()).output().unwrap();
|
||||
|
||||
tour_cmd().arg("start").current_dir(dir.path()).output().unwrap();
|
||||
let output = tour_cmd().arg("next").current_dir(dir.path()).output().unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(!stdout.contains('\x1b'), "piped output must not contain ANSI escapes: {:?}", stdout);
|
||||
}
|
||||
|
||||
// -- binary file tests --
|
||||
|
||||
#[test]
|
||||
fn test_binary_file_navigation() {
|
||||
let dir = setup_dir();
|
||||
init_tour(dir.path());
|
||||
|
||||
fs::write(dir.path().join("blob.bin"), [0u8, 159, 146, 150, 255]).unwrap();
|
||||
tour_cmd().args(["commit", "blob.bin", "-m", "s0"]).current_dir(dir.path()).output().unwrap();
|
||||
fs::write(dir.path().join("blob.bin"), [1u8, 2, 3, 255, 254]).unwrap();
|
||||
tour_cmd().args(["commit", "blob.bin", "-m", "s1"]).current_dir(dir.path()).output().unwrap();
|
||||
|
||||
tour_cmd().arg("start").current_dir(dir.path()).output().unwrap();
|
||||
assert_eq!(fs::read(dir.path().join("blob.bin")).unwrap(), [0u8, 159, 146, 150, 255]);
|
||||
|
||||
let output = tour_cmd().arg("next").current_dir(dir.path()).output().unwrap();
|
||||
assert!(output.status.success(), "next over binary file failed: {}", String::from_utf8_lossy(&output.stderr));
|
||||
assert_eq!(fs::read(dir.path().join("blob.bin")).unwrap(), [1u8, 2, 3, 255, 254]);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("(binary file)"), "expected binary marker in: {}", stdout);
|
||||
}
|
||||
|
||||
// -- storage efficiency tests --
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn test_carry_forward_hardlinks_unchanged_files() {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
|
||||
let dir = setup_dir();
|
||||
init_tour(dir.path());
|
||||
|
||||
create_test_file(dir.path(), "same.txt", "unchanged");
|
||||
create_test_file(dir.path(), "diff.txt", "v0");
|
||||
tour_cmd().args(["commit", "same.txt", "diff.txt", "-m", "s0"]).current_dir(dir.path()).output().unwrap();
|
||||
create_test_file(dir.path(), "diff.txt", "v1");
|
||||
tour_cmd().args(["commit", "diff.txt", "-m", "s1"]).current_dir(dir.path()).output().unwrap();
|
||||
|
||||
let ino0 = fs::metadata(dir.path().join(".tour/steps/0/same.txt")).unwrap().ino();
|
||||
let ino1 = fs::metadata(dir.path().join(".tour/steps/1/same.txt")).unwrap().ino();
|
||||
assert_eq!(ino0, ino1, "unchanged file should share an inode across steps");
|
||||
|
||||
// The overlaid file must be a distinct inode (previous step untouched)
|
||||
assert_eq!(fs::read_to_string(dir.path().join(".tour/steps/0/diff.txt")).unwrap(), "v0");
|
||||
assert_eq!(fs::read_to_string(dir.path().join(".tour/steps/1/diff.txt")).unwrap(), "v1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_navigation_leaves_unchanged_files_untouched() {
|
||||
let dir = setup_dir();
|
||||
init_tour(dir.path());
|
||||
|
||||
create_test_file(dir.path(), "same.txt", "unchanged");
|
||||
create_test_file(dir.path(), "diff.txt", "v0");
|
||||
tour_cmd().args(["commit", "same.txt", "diff.txt", "-m", "s0"]).current_dir(dir.path()).output().unwrap();
|
||||
create_test_file(dir.path(), "diff.txt", "v1");
|
||||
tour_cmd().args(["commit", "diff.txt", "-m", "s1"]).current_dir(dir.path()).output().unwrap();
|
||||
|
||||
tour_cmd().arg("start").current_dir(dir.path()).output().unwrap();
|
||||
let mtime_before = fs::metadata(dir.path().join("same.txt")).unwrap().modified().unwrap();
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
tour_cmd().arg("next").current_dir(dir.path()).output().unwrap();
|
||||
|
||||
let mtime_after = fs::metadata(dir.path().join("same.txt")).unwrap().modified().unwrap();
|
||||
assert_eq!(mtime_before, mtime_after, "unchanged file must not be rewritten during navigation");
|
||||
assert_eq!(fs::read_to_string(dir.path().join("diff.txt")).unwrap(), "v1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_old_format_tour_still_navigates() {
|
||||
// A tour whose step dirs are plain copies (no hardlinks), as older
|
||||
// versions produced, must still navigate correctly.
|
||||
let dir = setup_dir();
|
||||
init_tour(dir.path());
|
||||
|
||||
let steps = dir.path().join(".tour/steps");
|
||||
fs::create_dir_all(steps.join("0")).unwrap();
|
||||
fs::write(steps.join("0/f.txt"), "v0").unwrap();
|
||||
fs::write(steps.join("0/message"), "s0").unwrap();
|
||||
fs::create_dir_all(steps.join("1")).unwrap();
|
||||
fs::write(steps.join("1/f.txt"), "v1").unwrap();
|
||||
fs::write(steps.join("1/message"), "s1").unwrap();
|
||||
|
||||
tour_cmd().arg("start").current_dir(dir.path()).output().unwrap();
|
||||
assert_eq!(fs::read_to_string(dir.path().join("f.txt")).unwrap(), "v0");
|
||||
tour_cmd().arg("next").current_dir(dir.path()).output().unwrap();
|
||||
assert_eq!(fs::read_to_string(dir.path().join("f.txt")).unwrap(), "v1");
|
||||
tour_cmd().arg("prev").current_dir(dir.path()).output().unwrap();
|
||||
assert_eq!(fs::read_to_string(dir.path().join("f.txt")).unwrap(), "v0");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user