Merge pull request 'Improve usability and efficiency' (#1) from usability-efficiency into main
Reviewed-on: https://www.adam-french.co.uk/gitea/adamf/tour/pulls/1
This commit was merged in pull request #1.
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
|
- `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)
|
- `rm.rs` — marks files for removal in the next commit (skipped during carry-forward)
|
||||||
- `end.rs` — finalizes the tour (writes `.tour/ended` marker)
|
- `end.rs` — finalizes the tour (writes `.tour/ended` marker)
|
||||||
- `step.rs` — navigation: `next`, `prev`, `step_n`; handles file replacement, diff display, binary detection
|
- `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
|
- `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
|
- `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)
|
- `info.rs` — tour metadata (author, description, language, dates)
|
||||||
- `utils.rs` — shared helpers: `require_tour`, `get_current_step`, `get_tour_step`, `copy_tree`, path validation
|
- `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
|
- `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:**
|
**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
|
- `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
|
- `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::`
|
- 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"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"clap",
|
"clap",
|
||||||
|
"libc",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -6,5 +6,8 @@ edition = "2024"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
clap = { version = "4.5.59", features = ["derive"] }
|
clap = { version = "4.5.59", features = ["derive"] }
|
||||||
|
|
||||||
|
[target.'cfg(unix)'.dependencies]
|
||||||
|
libc = "0.2"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3.26.0"
|
tempfile = "3.26.0"
|
||||||
|
|||||||
+5
-17
@@ -1,27 +1,15 @@
|
|||||||
use crate::error::TourError;
|
use crate::error::TourError;
|
||||||
use crate::utils::{is_descendant_of_current_dir, is_file_in_dir, require_tour};
|
use crate::style::{green, reset};
|
||||||
use crate::TOUR_DIR;
|
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::{Path, PathBuf};
|
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_tour()?;
|
require_tour()?;
|
||||||
let tour_dir = Path::new(TOUR_DIR);
|
validate_paths(&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()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let existing = get_staged()?;
|
let existing = get_staged()?;
|
||||||
let existing_set: std::collections::HashSet<PathBuf> = existing.into_iter().collect();
|
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());
|
println!("already staged: {}", normalized.display());
|
||||||
} else {
|
} else {
|
||||||
writeln!(staged, "{}", normalized.display())?;
|
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::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::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 crate::TOUR_DIR;
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
@@ -26,17 +27,7 @@ pub fn commit(files: Vec<PathBuf>, message: String) -> Result<(), TourError> {
|
|||||||
files
|
files
|
||||||
};
|
};
|
||||||
|
|
||||||
for file in &files {
|
validate_paths(&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()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let removed = get_removed()?;
|
let removed = get_removed()?;
|
||||||
let removed_set: HashSet<PathBuf> = removed.into_iter().collect();
|
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()?;
|
clear_removed()?;
|
||||||
crate::info::update_last_modified()?;
|
crate::info::update_last_modified()?;
|
||||||
|
|
||||||
println!("Step {}: {}", step_num + 1, message);
|
println!("{}committed step {}{}: {}", bold(), step_num + 1, reset(), message);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,7 +93,11 @@ fn carry_forward(
|
|||||||
if let Some(parent) = dest.parent() {
|
if let Some(parent) = dest.parent() {
|
||||||
fs::create_dir_all(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(())
|
Ok(())
|
||||||
|
|||||||
@@ -12,8 +12,12 @@ pub enum TourError {
|
|||||||
InsideTourDir(PathBuf),
|
InsideTourDir(PathBuf),
|
||||||
FileNotFound(PathBuf),
|
FileNotFound(PathBuf),
|
||||||
StepOutOfRange { step: u32, total: u32 },
|
StepOutOfRange { step: u32, total: u32 },
|
||||||
|
NoStepsToNavigate,
|
||||||
|
NotStarted,
|
||||||
|
ResetNeedsForce,
|
||||||
CorruptedTour(String),
|
CorruptedTour(String),
|
||||||
Io(io::Error),
|
Io(io::Error),
|
||||||
|
IoContext { context: String, source: io::Error },
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Display for TourError {
|
impl std::fmt::Display for TourError {
|
||||||
@@ -40,12 +44,36 @@ impl std::fmt::Display for TourError {
|
|||||||
Self::StepOutOfRange { step, total } => {
|
Self::StepOutOfRange { step, total } => {
|
||||||
write!(f, "Step {} is out of range (1-{}).", 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::CorruptedTour(msg) => write!(f, "Tour data is corrupted: {}", msg),
|
||||||
Self::Io(e) => write!(f, "{}", e),
|
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 std::error::Error for TourError {}
|
||||||
|
|
||||||
impl From<io::Error> for TourError {
|
impl From<io::Error> for TourError {
|
||||||
|
|||||||
+8
-2
@@ -1,5 +1,6 @@
|
|||||||
use crate::error::TourError;
|
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 crate::TOUR_DIR;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
@@ -7,6 +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();
|
||||||
|
|
||||||
if total == 0 {
|
if total == 0 {
|
||||||
println!("No steps yet.");
|
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 step_dir = Path::new(TOUR_DIR).join("steps").join(i.to_string());
|
||||||
let message = fs::read_to_string(step_dir.join("message"))
|
let message = fs::read_to_string(step_dir.join("message"))
|
||||||
.unwrap_or_else(|_| "(no message)".into());
|
.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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+29
-6
@@ -12,6 +12,7 @@ mod reset;
|
|||||||
mod rm;
|
mod rm;
|
||||||
mod status;
|
mod status;
|
||||||
mod step;
|
mod step;
|
||||||
|
mod style;
|
||||||
mod unstage;
|
mod unstage;
|
||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
@@ -60,18 +61,27 @@ enum Commands {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/// Advance n steps (default 1)
|
/// Advance n steps (default 1)
|
||||||
|
#[command(visible_alias = "n")]
|
||||||
Next {
|
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>,
|
n: Option<u32>,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// Go back n steps (default 1)
|
/// Go back n steps (default 1)
|
||||||
|
#[command(visible_alias = "p")]
|
||||||
Prev {
|
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>,
|
n: Option<u32>,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// Jump to step n
|
/// Jump to step n
|
||||||
|
#[command(visible_alias = "s")]
|
||||||
Step {
|
Step {
|
||||||
#[arg(value_name = "STEP")]
|
#[arg(value_name = "STEP")]
|
||||||
n: u32,
|
n: u32,
|
||||||
@@ -84,16 +94,29 @@ enum Commands {
|
|||||||
Info,
|
Info,
|
||||||
|
|
||||||
/// Show current step and staged files
|
/// Show current step and staged files
|
||||||
|
#[command(visible_alias = "st")]
|
||||||
Status,
|
Status,
|
||||||
|
|
||||||
/// List all steps with messages
|
/// List all steps with messages
|
||||||
|
#[command(visible_alias = "ls")]
|
||||||
List,
|
List,
|
||||||
|
|
||||||
/// Reset tour session and remove tracked files
|
/// Reset tour session and remove tracked files
|
||||||
Reset,
|
Reset {
|
||||||
|
/// Skip the confirmation prompt
|
||||||
|
#[arg(short, long)]
|
||||||
|
force: bool,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
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 args = Args::parse();
|
||||||
let result = match args.command {
|
let result = match args.command {
|
||||||
Some(Commands::Init) => crate::init::init(),
|
Some(Commands::Init) => crate::init::init(),
|
||||||
@@ -102,14 +125,14 @@ fn main() {
|
|||||||
Some(Commands::Commit { files, message }) => crate::commit::commit(files, message),
|
Some(Commands::Commit { files, message }) => crate::commit::commit(files, message),
|
||||||
Some(Commands::Rm { files }) => crate::rm::rm(files),
|
Some(Commands::Rm { files }) => crate::rm::rm(files),
|
||||||
Some(Commands::End { message }) => crate::end::end(message),
|
Some(Commands::End { message }) => crate::end::end(message),
|
||||||
Some(Commands::Next { n }) => crate::step::next(n),
|
Some(Commands::Next { count, n }) => crate::step::next(count.or(n)),
|
||||||
Some(Commands::Prev { n }) => crate::step::prev(n),
|
Some(Commands::Prev { count, n }) => crate::step::prev(count.or(n)),
|
||||||
Some(Commands::Step { n }) => crate::step::step_n(n),
|
Some(Commands::Step { n }) => crate::step::step_n(n),
|
||||||
Some(Commands::Start) => crate::step::step_n(1),
|
Some(Commands::Start) => crate::step::step_n(1),
|
||||||
Some(Commands::Info) => crate::info::info(),
|
Some(Commands::Info) => crate::info::info(),
|
||||||
Some(Commands::Status) => crate::status::status(),
|
Some(Commands::Status) => crate::status::status(),
|
||||||
Some(Commands::List) => crate::list::list(),
|
Some(Commands::List) => crate::list::list(),
|
||||||
Some(Commands::Reset) => crate::reset::reset(),
|
Some(Commands::Reset { force }) => crate::reset::reset(force),
|
||||||
None => Ok(()),
|
None => Ok(()),
|
||||||
};
|
};
|
||||||
if let Err(e) = result {
|
if let Err(e) = result {
|
||||||
|
|||||||
+22
-1
@@ -3,12 +3,33 @@ use crate::step;
|
|||||||
use crate::utils::require_tour;
|
use crate::utils::require_tour;
|
||||||
use crate::SESSION_PATH;
|
use crate::SESSION_PATH;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
use std::io::{self, IsTerminal, Write};
|
||||||
|
|
||||||
pub fn reset() -> Result<(), TourError> {
|
pub fn reset(force: bool) -> Result<(), TourError> {
|
||||||
require_tour()?;
|
require_tour()?;
|
||||||
|
|
||||||
let cwd = std::env::current_dir()?;
|
let cwd = std::env::current_dir()?;
|
||||||
let tracked = step::get_tracked_files()?;
|
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)?;
|
step::remove_tracked_files(&cwd, &tracked)?;
|
||||||
|
|
||||||
let _ = fs::remove_file(SESSION_PATH);
|
let _ = fs::remove_file(SESSION_PATH);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use crate::error::TourError;
|
use crate::error::TourError;
|
||||||
|
use crate::style::{red, reset};
|
||||||
use crate::utils::require_tour;
|
use crate::utils::require_tour;
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::fs::{self, OpenOptions};
|
use std::fs::{self, OpenOptions};
|
||||||
@@ -23,7 +24,7 @@ pub fn rm(files: Vec<PathBuf>) -> Result<(), TourError> {
|
|||||||
println!("already marked for removal: {}", file.display());
|
println!("already marked for removal: {}", file.display());
|
||||||
} else {
|
} else {
|
||||||
writeln!(removed_file, "{}", file.display())?;
|
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::error::{IoResultExt, TourError};
|
||||||
use crate::utils::{copy_tree, get_current_step, get_tour_step, require_tour};
|
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::SESSION_PATH;
|
||||||
use crate::TOUR_DIR;
|
use crate::TOUR_DIR;
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::BTreeSet;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::path::{Path, PathBuf};
|
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).
|
/// Jump to step `n` (1-based, as shown to the user).
|
||||||
pub fn step_n(n: u32) -> Result<(), TourError> {
|
pub fn step_n(n: u32) -> Result<(), TourError> {
|
||||||
require_tour()?;
|
require_tour()?;
|
||||||
let total = get_tour_step()?;
|
let total = get_tour_step()?;
|
||||||
|
|
||||||
|
if total == 0 {
|
||||||
|
return Err(TourError::NoStepsToNavigate);
|
||||||
|
}
|
||||||
if n < 1 || n > total {
|
if n < 1 || n > total {
|
||||||
return Err(TourError::StepOutOfRange { step: 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> {
|
pub fn next(n: Option<u32>) -> Result<(), TourError> {
|
||||||
require_tour()?;
|
require_tour()?;
|
||||||
let total = get_tour_step()?;
|
let total = get_tour_step()?;
|
||||||
|
if total == 0 {
|
||||||
|
return Err(TourError::NoStepsToNavigate);
|
||||||
|
}
|
||||||
let delta = n.unwrap_or(1);
|
let delta = n.unwrap_or(1);
|
||||||
let target = match get_current_step() {
|
let last = total - 1;
|
||||||
Some(c) => c.saturating_add(delta),
|
match get_current_step() {
|
||||||
None if delta > 0 => delta - 1,
|
Some(current) if current >= last => {
|
||||||
None => return Err(TourError::StepOutOfRange { step: 0, total }),
|
println!("Already at the last step ({total}/{total}).");
|
||||||
};
|
Ok(())
|
||||||
if target >= total {
|
}
|
||||||
return Err(TourError::StepOutOfRange {
|
Some(current) => go_to_step(current.saturating_add(delta).min(last), total),
|
||||||
step: target + 1,
|
None => go_to_step(delta.saturating_sub(1).min(last), total),
|
||||||
total,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
go_to_step(target, total)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn prev(n: Option<u32>) -> Result<(), TourError> {
|
pub fn prev(n: Option<u32>) -> Result<(), TourError> {
|
||||||
require_tour()?;
|
require_tour()?;
|
||||||
let total = get_tour_step()?;
|
let total = get_tour_step()?;
|
||||||
|
if total == 0 {
|
||||||
|
return Err(TourError::NoStepsToNavigate);
|
||||||
|
}
|
||||||
let delta = n.unwrap_or(1);
|
let delta = n.unwrap_or(1);
|
||||||
let current = get_current_step().ok_or(TourError::StepOutOfRange { step: 0, total })?;
|
let current = get_current_step().ok_or(TourError::NotStarted)?;
|
||||||
let target = current
|
if current == 0 {
|
||||||
.checked_sub(delta)
|
println!("Already at the first step (1/{total}).");
|
||||||
.ok_or(TourError::StepOutOfRange { step: 0, total })?;
|
return Ok(());
|
||||||
go_to_step(target, total)
|
}
|
||||||
|
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> {
|
fn go_to_step(target: u32, total: u32) -> Result<(), TourError> {
|
||||||
let cwd = std::env::current_dir()?;
|
let cwd = std::env::current_dir()?;
|
||||||
let tracked = get_tracked_files()?;
|
let steps_dir = Path::new(TOUR_DIR).join("steps");
|
||||||
let old_files = snapshot_tracked_files(&cwd, &tracked)?;
|
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 mut target_files = BTreeSet::new();
|
||||||
let step_dir = Path::new(TOUR_DIR).join("steps").join(target.to_string());
|
collect_step_files(&target_dir, &target_dir, &mut target_files)?;
|
||||||
let tmp_dir = Path::new(TOUR_DIR).join("tmp_step");
|
|
||||||
if tmp_dir.exists() {
|
// Files the tour owns in the working directory: the current step's set if a
|
||||||
fs::remove_dir_all(&tmp_dir)?;
|
// 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)?;
|
let to_delete: BTreeSet<PathBuf> = current_files
|
||||||
for entry in fs::read_dir(&step_dir)? {
|
.difference(&target_files)
|
||||||
let entry = entry?;
|
.cloned()
|
||||||
if entry.file_name() == "message" {
|
.collect();
|
||||||
continue;
|
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
|
// Install only the files that differ. Always copy — never link into the
|
||||||
remove_tracked_files(&cwd, &tracked)?;
|
// snapshot store — so user edits can't write through to step data.
|
||||||
for entry in fs::read_dir(&tmp_dir)? {
|
for relative in &to_install {
|
||||||
let entry = entry?;
|
let dest = cwd.join(relative);
|
||||||
copy_tree(&entry.path(), &cwd.join(entry.file_name()))?;
|
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(&changes);
|
||||||
print_changes(&old_files, &new_files);
|
|
||||||
|
|
||||||
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());
|
.unwrap_or_else(|_| "(no message)".into());
|
||||||
println!(
|
println!(
|
||||||
"\n{BOLD}Step {}/{total}:{RESET} {}",
|
"\n{}Step {}/{total}:{} {}",
|
||||||
|
bold(),
|
||||||
target + 1,
|
target + 1,
|
||||||
|
reset(),
|
||||||
message.trim()
|
message.trim()
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(())
|
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> {
|
pub fn get_tracked_files() -> Result<BTreeSet<PathBuf>, io::Error> {
|
||||||
let steps_dir = Path::new(TOUR_DIR).join("steps");
|
let steps_dir = Path::new(TOUR_DIR).join("steps");
|
||||||
let mut tracked = BTreeSet::new();
|
let mut tracked = BTreeSet::new();
|
||||||
@@ -161,41 +224,22 @@ fn collect_step_files(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Snapshots tracked files from root. Returns None for binary files (invalid UTF-8).
|
fn print_changes(changes: &[(PathBuf, FileChange)]) {
|
||||||
fn snapshot_tracked_files(
|
for (path, change) in changes {
|
||||||
root: &Path,
|
match change {
|
||||||
tracked: &BTreeSet<PathBuf>,
|
FileChange::Added => {
|
||||||
) -> Result<BTreeMap<PathBuf, Option<String>>, io::Error> {
|
println!("{} new: {}{}", green(), path.display(), reset())
|
||||||
let mut files = BTreeMap::new();
|
}
|
||||||
for relative in tracked {
|
FileChange::Modified { old, new } => {
|
||||||
let full = root.join(relative);
|
println!("{} modified: {}{}", cyan(), path.display(), reset());
|
||||||
if full.is_file() {
|
match (old, new) {
|
||||||
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) {
|
|
||||||
(Some(o), Some(n)) => print_diff(o, n),
|
(Some(o), Some(n)) => print_diff(o, n),
|
||||||
_ => println!(" (binary file)"),
|
_ => println!(" (binary file)"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => {}
|
FileChange::Removed => {
|
||||||
}
|
println!("{} deleted: {}{}", red(), path.display(), reset())
|
||||||
}
|
}
|
||||||
for path in old.keys() {
|
|
||||||
if !new.contains_key(path) {
|
|
||||||
println!("{RED} deleted: {}{RESET}", path.display());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -204,19 +248,36 @@ fn print_diff(old: &str, new: &str) {
|
|||||||
let old_lines: Vec<&str> = old.lines().collect();
|
let old_lines: Vec<&str> = old.lines().collect();
|
||||||
let new_lines: Vec<&str> = new.lines().collect();
|
let new_lines: Vec<&str> = new.lines().collect();
|
||||||
|
|
||||||
let m = old_lines.len();
|
// Trim the common prefix and suffix so the LCS table only covers the
|
||||||
let n = new_lines.len();
|
// 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 {
|
if m > 1000 || n > 1000 {
|
||||||
println!(" (file changed)");
|
println!(" (file changed)");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// LCS table
|
// LCS table over the changed middle
|
||||||
let mut dp = vec![vec![0usize; n + 1]; m + 1];
|
let mut dp = vec![vec![0usize; n + 1]; m + 1];
|
||||||
for i in 1..=m {
|
for i in 1..=m {
|
||||||
for j in 1..=n {
|
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;
|
dp[i][j] = dp[i - 1][j - 1] + 1;
|
||||||
} else {
|
} else {
|
||||||
dp[i][j] = dp[i - 1][j].max(dp[i][j - 1]);
|
dp[i][j] = dp[i - 1][j].max(dp[i][j - 1]);
|
||||||
@@ -225,22 +286,26 @@ fn print_diff(old: &str, new: &str) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Backtrack
|
// 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);
|
let (mut i, mut j) = (m, n);
|
||||||
while i > 0 || j > 0 {
|
while i > 0 || j > 0 {
|
||||||
if i > 0 && j > 0 && old_lines[i - 1] == new_lines[j - 1] {
|
if i > 0 && j > 0 && old_mid[i - 1] == new_mid[j - 1] {
|
||||||
ops.push((' ', old_lines[i - 1]));
|
mid_ops.push((' ', old_mid[i - 1]));
|
||||||
i -= 1;
|
i -= 1;
|
||||||
j -= 1;
|
j -= 1;
|
||||||
} else if j > 0 && (i == 0 || dp[i][j - 1] >= dp[i - 1][j]) {
|
} 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;
|
j -= 1;
|
||||||
} else {
|
} else {
|
||||||
ops.push(('-', old_lines[i - 1]));
|
mid_ops.push(('-', old_mid[i - 1]));
|
||||||
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
|
// Print with context: only show changed lines and up to 2 surrounding context lines
|
||||||
const CTX: usize = 2;
|
const CTX: usize = 2;
|
||||||
@@ -275,8 +340,8 @@ fn print_diff(old: &str, new: &str) {
|
|||||||
}
|
}
|
||||||
prev_visible = true;
|
prev_visible = true;
|
||||||
match op {
|
match op {
|
||||||
'+' => println!("{GREEN} + {line}{RESET}"),
|
'+' => println!("{} + {line}{}", green(), reset()),
|
||||||
'-' => println!("{RED} - {line}{RESET}"),
|
'-' => println!("{} - {line}{}", red(), reset()),
|
||||||
_ => println!(" {line}"),
|
_ => 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::fs;
|
||||||
use std::io;
|
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::SESSION_PATH;
|
||||||
use crate::TOUR_DIR;
|
use crate::TOUR_DIR;
|
||||||
|
|
||||||
@@ -25,7 +25,8 @@ pub fn get_current_step() -> Option<u32> {
|
|||||||
|
|
||||||
pub fn get_tour_step() -> Result<u32, TourError> {
|
pub fn get_tour_step() -> Result<u32, TourError> {
|
||||||
let steps_dir = Path::new(TOUR_DIR).join("steps");
|
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_map(|e| e.ok())
|
||||||
.filter(|e| e.path().is_dir())
|
.filter(|e| e.path().is_dir())
|
||||||
.filter_map(|e| e.file_name().to_str()?.parse::<u32>().ok())
|
.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() {
|
if let Some(parent) = dest.parent() {
|
||||||
fs::create_dir_all(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)?;
|
fs::copy(src, &dest)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Recursively copies src to dest. If src is a directory, copies its contents
|
/// Validates that every path exists, lives under the working directory, and is
|
||||||
/// into dest. If src is a file, copies it to dest.
|
/// not inside the .tour directory. Canonicalizes the anchors once, not per file.
|
||||||
pub fn copy_tree(src: &Path, dest: &Path) -> Result<(), io::Error> {
|
pub fn validate_paths(files: &[PathBuf]) -> Result<(), TourError> {
|
||||||
if src.is_dir() {
|
let cwd = std::env::current_dir()?.canonicalize()?;
|
||||||
fs::create_dir_all(dest)?;
|
let tour_canon = Path::new(TOUR_DIR).canonicalize()?;
|
||||||
for entry in fs::read_dir(src)? {
|
for file in files {
|
||||||
let entry = entry?;
|
if !file.exists() {
|
||||||
copy_tree(&entry.path(), &dest.join(entry.file_name()))?;
|
return Err(TourError::FileNotFound(file.clone()));
|
||||||
}
|
}
|
||||||
} else {
|
let canon = file.canonicalize()?;
|
||||||
if let Some(parent) = dest.parent() {
|
if !canon.starts_with(&cwd) {
|
||||||
fs::create_dir_all(parent)?;
|
return Err(TourError::NotADescendant(file.clone()));
|
||||||
|
}
|
||||||
|
if canon.starts_with(&tour_canon) {
|
||||||
|
return Err(TourError::InsideTourDir(file.clone()));
|
||||||
}
|
}
|
||||||
fs::copy(src, dest)?;
|
|
||||||
}
|
}
|
||||||
Ok(())
|
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 {
|
fn setup_dir() -> tempfile::TempDir {
|
||||||
let dir = tempfile::tempdir().expect("failed to create temp dir");
|
tempfile::tempdir().expect("failed to create temp dir")
|
||||||
dir
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn init_tour(dir: &Path) {
|
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("1 steps"), "expected step count in: {}", stdout);
|
||||||
assert!(stdout.contains("not started"), "expected 'not started' 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