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:
+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}"),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user