use crate::{
diff::{self, FileDiff},
git::{self, Opts},
input,
model::Config,
modes,
policy::{self, Op},
repo_state::{self, Entry, EntryKind},
screen, ui,
};
use anyhow::Result;
const MAX_DIFF_LINES: usize = 5000;
const LITERAL: &[(&str, &str)] = &[("GIT_LITERAL_PATHSPECS", "1")];
#[cfg(windows)]
const NULL_FILE: &str = "NUL";
#[cfg(not(windows))]
const NULL_FILE: &str = "/dev/null";
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Section {
Staged,
Unstaged,
Untracked,
Conflicted,
}
impl Section {
fn tag(self) -> &'static str {
match self {
Section::Staged => "[S] staged ",
Section::Unstaged => "[M] unstaged ",
Section::Untracked => "[?] untracked",
Section::Conflicted => "[!] conflict ",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Row {
entry: usize,
section: Section,
}
fn build_rows(entries: &[Entry]) -> Vec<Row> {
let mut rows = Vec::new();
for section in [
Section::Staged,
Section::Unstaged,
Section::Untracked,
Section::Conflicted,
] {
for (entry, e) in entries.iter().enumerate() {
let hit = match section {
Section::Staged => e.staged(),
Section::Unstaged => e.unstaged(),
Section::Untracked => e.kind == EntryKind::Untracked,
Section::Conflicted => e.conflicted(),
};
if hit {
rows.push(Row { entry, section });
}
}
}
rows
}
fn row_text(e: &Entry, section: Section) -> String {
let letter = match section {
Section::Staged => e.x,
Section::Unstaged => e.y,
Section::Untracked => '?',
Section::Conflicted => '!',
};
let name = match (&e.orig_path, section) {
(Some(old), Section::Staged) => format!("{old} -> {}", e.path),
_ => e.path.clone(),
};
format!("{} {letter} {name}", section.tag())
}
fn header_lines(rows: &[Row]) -> Vec<String> {
let count = |s: Section| rows.iter().filter(|r| r.section == s).count();
let mut lines = vec![format!(
"Staged {} | Unstaged {} | Untracked {} | Conflicted {}",
count(Section::Staged),
count(Section::Unstaged),
count(Section::Untracked),
count(Section::Conflicted)
)];
if rows.is_empty() {
lines.push(screen::muted(
"Nothing to stage: the working tree is clean. Edit a file, then press R.",
));
}
lines
}
fn entry_paths(e: &Entry) -> Vec<String> {
let mut paths: Vec<String> = e.orig_path.iter().cloned().collect();
paths.push(e.path.clone());
paths
}
fn diff_args(section: Section, e: &Entry) -> Option<Vec<String>> {
let base = [
"diff",
"--no-color",
"--no-ext-diff",
"--no-textconv",
"--src-prefix=a/",
"--dst-prefix=b/",
]
.map(String::from);
let mut args: Vec<String> = base.to_vec();
match section {
Section::Staged => {
args.extend(["--cached", "-M", "--"].map(String::from));
args.extend(entry_paths(e));
}
Section::Unstaged => {
args.extend(["--", &e.path].map(String::from));
}
Section::Untracked => {
args.extend(["--no-index", "--", NULL_FILE, &e.path].map(String::from));
}
Section::Conflicted => return None,
}
Some(args)
}
fn at<'a>(dir: &'a str, args: &[&'a str]) -> Vec<&'a str> {
let mut full = vec!["-C", dir];
full.extend_from_slice(args);
full
}
fn head_exists(dir: &str) -> bool {
git::git_raw(
&at(dir, &["rev-parse", "--verify", "-q", "HEAD"]),
&Opts::default(),
)
.map(|o| o.ok())
.unwrap_or(false)
}
fn run_paths(dir: &str, args: &[&str], paths: &[String]) -> Result<()> {
if paths.is_empty() {
return Ok(());
}
let mut stdin = Vec::new();
for path in paths {
stdin.extend_from_slice(path.as_bytes());
stdin.push(0);
}
let mut full = at(dir, args);
full.extend(["--pathspec-from-file=-", "--pathspec-file-nul"]);
git::git_ok(
&full,
&Opts {
stdin: Some(&stdin),
env: LITERAL,
..Opts::default()
},
)?;
Ok(())
}
fn stage_paths(dir: &str, paths: &[String]) -> Result<()> {
run_paths(dir, &["add"], paths)
}
fn unstage_paths(dir: &str, paths: &[String]) -> Result<()> {
if head_exists(dir) {
run_paths(dir, &["restore", "--staged"], paths)
} else {
run_paths(
dir,
&["rm", "--cached", "-r", "-q", "--ignore-unmatch"],
paths,
)
}
}
fn discard_tracked_exec(dir: &str, path: &str) -> Result<()> {
let args = at(dir, &["restore", "--worktree", "--", path]);
git::git_ok(
&args,
&Opts {
env: LITERAL,
..Opts::default()
},
)?;
Ok(())
}
fn clean_args(path: &str) -> Vec<&str> {
let mut args = vec!["clean", "-f"];
if path.ends_with('/') {
args.push("-d");
}
args.extend(["--", path]);
args
}
fn discard_untracked_exec(dir: &str, path: &str) -> Result<()> {
git::git_ok(
&at(dir, &clean_args(path)),
&Opts {
env: LITERAL,
..Opts::default()
},
)?;
Ok(())
}
fn discard_row(cfg: &Config, dir: &str, section: Section, e: &Entry) -> Result<bool> {
let (op, what, command) = match section {
Section::Unstaged => (
Op::DiscardUnstaged,
format!(
"Throw away your unstaged changes to {}? This cannot be undone.",
e.path
),
format!("git restore --worktree -- {}", e.path),
),
Section::Untracked => (
Op::DiscardUntracked,
format!(
"Delete the untracked {} from disk? This cannot be undone.",
e.path
),
format!("git {}", clean_args(&e.path).join(" ")),
),
_ => return Ok(false),
};
if !ui::gate(cfg, &policy::check(cfg, &op), &what, &command)? {
return Ok(false);
}
if section == Section::Unstaged {
discard_tracked_exec(dir, &e.path)?;
} else {
discard_untracked_exec(dir, &e.path)?;
}
let mut lines = vec![format!("Ran: {command}")];
lines.extend(ui::explain(
cfg,
&["Discarding puts the file back to how it was at the last commit or staging."],
));
ui::notice("Discarded", &lines)?;
Ok(true)
}
fn apply_patch(dir: &str, flags: &[&str], patch: &[u8]) -> Result<()> {
let mut args = vec!["apply"];
args.extend_from_slice(flags);
args.extend(["--whitespace=nowarn", "-"]);
git::git_ok(
&at(dir, &args),
&Opts {
stdin: Some(patch),
..Opts::default()
},
)?;
Ok(())
}
fn stage_hunk(dir: &str, fd: &FileDiff, idx: usize) -> Result<()> {
apply_patch(dir, &["--cached"], &diff::hunk_patch(fd, idx))
}
fn unstage_hunk(dir: &str, fd: &FileDiff, idx: usize) -> Result<()> {
apply_patch(dir, &["-R", "--cached"], &diff::hunk_patch(fd, idx))
}
fn discard_hunk_exec(dir: &str, fd: &FileDiff, idx: usize) -> Result<()> {
apply_patch(dir, &["-R"], &diff::hunk_patch(fd, idx))
}
fn load_files(dir: &str, section: Section, e: &Entry) -> Result<Vec<FileDiff>> {
let Some(args) = diff_args(section, e) else {
return Ok(Vec::new());
};
if section == Section::Untracked && e.path.ends_with('/') {
let out = git::git_ok(
&at(
dir,
&["ls-files", "--others", "--exclude-standard", "--", &e.path],
),
&Opts {
env: LITERAL,
..Opts::default()
},
)?;
let mut header = format!("Untracked directory {}\nFiles:\n", e.path);
out.lines()
.for_each(|l| header.push_str(&format!(" {l}\n")));
return Ok(vec![FileDiff {
header: header.into_bytes(),
hunks: Vec::new(),
}]);
}
let mut refs: Vec<&str> = vec!["-C", dir];
refs.extend([
"-c",
"diff.relative=false",
"-c",
"diff.noprefix=false",
"-c",
"diff.mnemonicPrefix=false",
]);
refs.extend(args.iter().map(String::as_str));
let out = git::git_raw(
&refs,
&Opts {
env: LITERAL,
..Opts::default()
},
)?;
let good = out.ok() || (section == Section::Untracked && out.code == Some(1));
if !good {
anyhow::bail!("{}", out.stderr.trim());
}
Ok(diff::parse_diff(&out.stdout))
}
const LIST_KEYS: [ui::Key; 10] = [
ui::Key {
key: 'a',
label: "stage",
},
ui::Key {
key: 'u',
label: "unstage",
},
ui::Key {
key: 'x',
label: "discard",
},
ui::Key {
key: 'A',
label: "stage ALL (Shift)",
},
ui::Key {
key: 'U',
label: "unstage ALL (Shift)",
},
ui::Key {
key: 'i',
label: "ignore",
},
ui::Key {
key: 'c',
label: "commit staged",
},
ui::Key {
key: 'r',
label: "refresh",
},
ui::Key {
key: 'm',
label: "menu",
},
ui::Key {
key: 'd',
label: "diff",
},
];
fn report(result: Result<()>) -> Result<()> {
match result {
Err(error) if !input::is_cancel(&error) => ui::notice("Git said no", &[error.to_string()]),
other => other,
}
}
fn say(title: &str, line: &str) -> Result<()> {
ui::notice(title, &[line.to_string()])
}
fn conflict_menu(cfg: &mut Config, e: &Entry) -> Result<()> {
let context = [
format!("{} has merge conflicts.", e.path),
"Conflicted files are read-only here: resolve in Conflicts mode.".into(),
];
if ui::choose(
"Conflicted file",
&context,
&["Open Conflicts mode", "Back"],
)? == Some(0)
{
modes::open("conflicts", cfg)?;
}
Ok(())
}
fn stage_all(dir: &str, entries: &[Entry]) -> Result<()> {
let paths: Vec<String> = entries
.iter()
.filter(|e| e.unstaged() || e.kind == EntryKind::Untracked)
.map(|e| e.path.clone())
.collect();
stage_paths(dir, &paths)
}
fn unstage_all(dir: &str, entries: &[Entry]) -> Result<()> {
let paths: Vec<String> = entries
.iter()
.filter(|e| e.staged())
.flat_map(entry_paths)
.collect();
unstage_paths(dir, &paths)
}
fn commit_staged(cfg: &mut Config) -> Result<()> {
let state = repo_state::load()?;
if !state.entries.iter().any(|e| e.staged()) {
return say(
"Nothing staged",
"Stage a file or hunk first (a), then commit it here.",
);
}
modes::STAGED_ONLY.store(true, std::sync::atomic::Ordering::Relaxed);
let result = modes::open("commit", cfg);
modes::STAGED_ONLY.store(false, std::sync::atomic::Ordering::Relaxed);
result
}
fn row_action(cfg: &mut Config, dir: &str, key: char, e: &Entry, section: Section) -> Result<()> {
if section == Section::Conflicted {
return match key {
'i' | 'c' | 'a' | 'u' | 'x' => conflict_menu(cfg, e),
_ => Ok(()),
};
}
match (key, section) {
('a', Section::Staged) => say("Already staged", "Use U-shift or u to unstage it."),
('a', _) => report(stage_paths(dir, std::slice::from_ref(&e.path))),
('u', Section::Staged) => report(unstage_paths(dir, &entry_paths(e))),
('u', _) => say(
"Not staged",
"This row is not in the index; nothing to unstage.",
),
('x', Section::Staged) => say(
"Unstage first",
"Press u to unstage it, then discard the working copy.",
),
('x', _) => report(discard_row(cfg, dir, section, e).map(|_| ())),
('i', _) => modes::ignore::ignore_path(cfg, &e.path),
_ => Ok(()),
}
}
fn row_menu(cfg: &mut Config, dir: &str, e: &Entry, section: Section) -> Result<()> {
let mut options: Vec<(&str, char)> = vec![("View diff", 'd')];
match section {
Section::Staged => options.push(("Unstage", 'u')),
Section::Unstaged | Section::Untracked => {
options.push(("Stage", 'a'));
options.push(("Discard changes", 'x'));
options.push(("Ignore this path", 'i'));
}
Section::Conflicted => options.push(("Resolve in Conflicts mode", 'a')),
}
options.push(("Commit staged changes", 'c'));
let labels: Vec<&str> = options.iter().map(|o| o.0).collect();
let context = [row_text(e, section)];
let Some(pick) = ui::choose("File actions", &context, &labels)? else {
return Ok(());
};
match options[pick].1 {
'd' => open_row(cfg, dir, e, section),
'c' => commit_staged(cfg),
key => row_action(cfg, dir, key, e, section),
}
}
fn open_row(cfg: &mut Config, dir: &str, e: &Entry, section: Section) -> Result<()> {
if section == Section::Conflicted {
return conflict_menu(cfg, e);
}
view_diff(cfg, dir, e, section)
}
fn diff_keys(section: Section) -> &'static [ui::Key] {
const STAGE: [ui::Key; 2] = [
ui::Key {
key: 'a',
label: "stage hunk",
},
ui::Key {
key: 'x',
label: "discard hunk",
},
];
const UNSTAGE: [ui::Key; 1] = [ui::Key {
key: 'a',
label: "unstage hunk",
}];
const UNTRACKED: [ui::Key; 1] = [ui::Key {
key: 'a',
label: "stage file",
}];
match section {
Section::Unstaged => &STAGE,
Section::Staged => &UNSTAGE,
_ => &UNTRACKED,
}
}
fn hunk_action(
cfg: &Config,
dir: &str,
section: Section,
key: char,
fd: &FileDiff,
idx: usize,
) -> Result<bool> {
match (section, key) {
(Section::Unstaged, 'a') => stage_hunk(dir, fd, idx)?,
(Section::Staged, 'a') => unstage_hunk(dir, fd, idx)?,
(Section::Unstaged, 'x') => {
let verdict = policy::check(cfg, &Op::DiscardUnstaged);
let what = "Throw away this hunk from your working copy? This cannot be undone.";
if !ui::gate(cfg, &verdict, what, "git apply -R -")? {
return Ok(false);
}
discard_hunk_exec(dir, fd, idx)?;
}
_ => return Ok(false),
}
Ok(true)
}
fn view_diff(cfg: &mut Config, dir: &str, e: &Entry, section: Section) -> Result<()> {
let mut acted = false;
loop {
let files = match load_files(dir, section, e) {
Ok(files) => files,
Err(error) => return ui::notice("Cannot show diff", &[error.to_string()]),
};
if acted && diff::hunk_count(&files) == 0 {
return Ok(());
}
let lines = diff::display_lines(&files, MAX_DIFF_LINES);
if lines.is_empty() {
return say(
"No differences",
"Nothing to show (an empty file or no textual change).",
);
}
let kind = if section == Section::Staged {
"Staged"
} else {
"Unstaged"
};
let title = format!("{kind} diff: {}", row_text(e, section).trim());
match ui::diff_view(&title, &lines, diff_keys(section))? {
ui::DiffChoice::Back => return Ok(()),
ui::DiffChoice::Action(key, hunk) => {
if section == Section::Untracked {
report(stage_paths(dir, std::slice::from_ref(&e.path)))?;
return Ok(());
}
if let Some((fi, hi)) = diff::locate_hunk(&files, hunk) {
match hunk_action(cfg, dir, section, key, &files[fi], hi) {
Ok(changed) => acted |= changed,
Err(error) if !input::is_cancel(&error) => {
ui::notice("Git said no", &[error.to_string()])?;
}
Err(error) => return Err(error),
}
}
}
}
}
}
pub fn run(config: &mut Config) -> Result<()> {
let mut index = 0usize;
loop {
let state = repo_state::load()?;
let dir = state.workdir.to_string_lossy().into_owned();
let dir = dir.as_str();
let rows = build_rows(&state.entries);
let header = header_lines(&rows);
let texts: Vec<String> = rows
.iter()
.map(|r| row_text(&state.entries[r.entry], r.section))
.collect();
let choice = ui::action_list(
"Stage: files and hunks",
&header,
&texts,
&LIST_KEYS,
&mut index,
)?;
let (key, at) = match choice {
ui::Choice::Back => return Ok(()),
ui::Choice::Open(i) => ('d', i),
ui::Choice::Action(key, i) => (key, i),
};
let row = rows.get(at).copied();
match (key, row) {
('r', _) => {}
('A', _) => report(stage_all(dir, &state.entries))?,
('U', _) => report(unstage_all(dir, &state.entries))?,
('c', _) => commit_staged(config)?,
(_, None) => {}
('d', Some(r)) => open_row(config, dir, &state.entries[r.entry], r.section)?,
('m', Some(r)) => row_menu(config, dir, &state.entries[r.entry], r.section)?,
(k, Some(r)) => row_action(config, dir, k, &state.entries[r.entry], r.section)?,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::TempRepo;
fn entry(path: &str, x: char, y: char, kind: EntryKind) -> Entry {
Entry {
path: path.into(),
orig_path: None,
x,
y,
kind,
}
}
fn d(repo: &TempRepo) -> String {
repo.path().to_string_lossy().into_owned()
}
fn numbered(change_a: bool, change_b: bool) -> String {
(1..=40)
.map(|i| match (i, change_a, change_b) {
(3, true, _) => "THREE\n".to_string(),
(38, _, true) => "THIRTY-EIGHT\n".to_string(),
_ => format!("line {i}\n"),
})
.collect()
}
fn base_repo() -> TempRepo {
let repo = TempRepo::new(1);
repo.write("big.txt", &numbered(false, false));
repo.git(&["add", "big.txt"]);
repo.git(&["commit", "-qm", "big"]);
repo.write("big.txt", &numbered(true, true));
repo
}
#[test]
fn rows_are_grouped_by_section() {
let entries = vec![
entry("u.txt", '?', '?', EntryKind::Untracked),
entry("both.txt", 'M', 'M', EntryKind::Ordinary),
entry("c.txt", 'U', 'U', EntryKind::Unmerged),
entry("i.txt", '!', '!', EntryKind::Ignored),
entry("s.txt", 'A', '.', EntryKind::Ordinary),
];
let rows = build_rows(&entries);
let got: Vec<(usize, Section)> = rows.iter().map(|r| (r.entry, r.section)).collect();
assert_eq!(
got,
vec![
(1, Section::Staged),
(4, Section::Staged),
(1, Section::Unstaged),
(0, Section::Untracked),
(2, Section::Conflicted)
]
);
assert!(header_lines(&rows)[0].contains("Staged 2"));
assert!(header_lines(&[]).len() == 2);
}
#[test]
fn rename_row_shows_both_names() {
let mut e = entry("new.txt", 'R', '.', EntryKind::Renamed);
e.orig_path = Some("old.txt".into());
assert!(row_text(&e, Section::Staged).ends_with("old.txt -> new.txt"));
assert_eq!(
entry_paths(&e),
vec!["old.txt".to_string(), "new.txt".to_string()]
);
}
#[test]
fn diff_args_per_section() {
let e = entry("a b.txt", 'M', 'M', EntryKind::Ordinary);
assert!(diff_args(Section::Staged, &e)
.unwrap()
.contains(&"--cached".to_string()));
let un = diff_args(Section::Unstaged, &e).unwrap();
assert!(!un.contains(&"--cached".to_string()));
assert_eq!(un.last().unwrap(), "a b.txt");
let nu = diff_args(Section::Untracked, &e).unwrap();
assert!(nu.contains(&"--no-index".to_string()) && nu.contains(&NULL_FILE.to_string()));
assert!(diff_args(Section::Conflicted, &e).is_none());
}
#[test]
fn clean_uses_d_only_for_directories() {
assert_eq!(clean_args("f.txt"), vec!["clean", "-f", "--", "f.txt"]);
assert_eq!(clean_args("dir/"), vec!["clean", "-f", "-d", "--", "dir/"]);
}
#[test]
fn discard_untracked_is_danger_even_when_confirmations_off() {
let cfg = Config {
confirm_destructive: false,
..Config::default()
};
assert_eq!(
policy::check(&cfg, &Op::DiscardUntracked),
policy::Verdict::Danger
);
assert_eq!(
policy::check(&cfg, &Op::DiscardUnstaged),
policy::Verdict::Danger
);
}
#[test]
fn stage_only_first_hunk_round_trip() {
let repo = base_repo();
repo.run(|| {
let e = entry("big.txt", '.', 'M', EntryKind::Ordinary);
let files = load_files(&d(&repo), Section::Unstaged, &e).unwrap();
assert_eq!(files[0].hunks.len(), 2);
stage_hunk(&d(&repo), &files[0], 0).unwrap();
});
let cached = repo.git(&["diff", "--cached"]);
assert!(cached.contains("+THREE") && !cached.contains("THIRTY-EIGHT"));
let work = repo.git(&["diff"]);
assert!(work.contains("+THIRTY-EIGHT") && !work.contains("THREE"));
}
#[test]
fn unstage_one_hunk_round_trip() {
let repo = base_repo();
repo.git(&["add", "big.txt"]);
repo.run(|| {
let e = entry("big.txt", 'M', '.', EntryKind::Ordinary);
let files = load_files(&d(&repo), Section::Staged, &e).unwrap();
assert_eq!(files[0].hunks.len(), 2);
unstage_hunk(&d(&repo), &files[0], 0).unwrap();
});
let cached = repo.git(&["diff", "--cached"]);
assert!(cached.contains("+THIRTY-EIGHT") && !cached.contains("THREE"));
assert!(repo.git(&["diff"]).contains("+THREE"));
}
#[test]
fn discard_one_hunk_keeps_the_other() {
let repo = base_repo();
repo.run(|| {
let e = entry("big.txt", '.', 'M', EntryKind::Ordinary);
let files = load_files(&d(&repo), Section::Unstaged, &e).unwrap();
discard_hunk_exec(&d(&repo), &files[0], 1).unwrap();
});
let work = repo.git(&["diff"]);
assert!(work.contains("+THREE") && !work.contains("THIRTY-EIGHT"));
}
#[test]
fn crlf_hunk_stages_cleanly() {
let repo = TempRepo::new(1);
let crlf = |a: &str| -> String {
(1..=30)
.map(|i| {
if i == 2 {
format!("{a}\r\n")
} else {
format!("l{i}\r\n")
}
})
.collect()
};
repo.write("w.txt", &crlf("old"));
repo.git(&["add", "w.txt"]);
repo.git(&["commit", "-qm", "w"]);
repo.write("w.txt", &crlf("new"));
repo.run(|| {
let e = entry("w.txt", '.', 'M', EntryKind::Ordinary);
let files = load_files(&d(&repo), Section::Unstaged, &e).unwrap();
stage_hunk(&d(&repo), &files[0], 0).unwrap();
});
assert!(repo.git(&["diff"]).is_empty());
}
#[test]
fn discard_tracked_restores_content() {
let repo = TempRepo::new(1);
repo.write("f1.txt", "scribble");
repo.run(|| discard_tracked_exec(&d(&repo), "f1.txt").unwrap());
assert!(repo.git(&["status", "--porcelain"]).is_empty());
}
#[test]
fn discard_untracked_removes_file_and_dir() {
let repo = TempRepo::new(1);
repo.write("new.txt", "x");
repo.write("d/inner.txt", "y");
repo.run(|| {
discard_untracked_exec(&d(&repo), "new.txt").unwrap();
discard_untracked_exec(&d(&repo), "d/").unwrap();
});
assert!(repo.git(&["status", "--porcelain"]).is_empty());
}
#[test]
fn untracked_diff_shows_added_lines() {
let repo = TempRepo::new(1);
repo.write("fresh.txt", "one\ntwo\n");
repo.run(|| {
let e = entry("fresh.txt", '?', '?', EntryKind::Untracked);
let files = load_files(&d(&repo), Section::Untracked, &e).unwrap();
assert_eq!(files[0].hunks.len(), 1);
let shown = diff::display_lines(&files, 100);
assert!(shown.contains(&"+one".to_string()));
});
}
#[test]
fn bulk_stage_and_unstage_via_stdin() {
let repo = TempRepo::new(1);
let names: Vec<String> = (0..5).map(|i| format!("n{i}.txt")).collect();
for n in &names {
repo.write(n, "x");
}
repo.write("odd [x].txt", "x");
let mut all = names.clone();
all.push("odd [x].txt".into());
repo.run(|| stage_paths(&d(&repo), &all).unwrap());
assert_eq!(
repo.git(&["diff", "--cached", "--name-only"])
.lines()
.count(),
6
);
repo.run(|| unstage_paths(&d(&repo), &all).unwrap());
assert!(repo.git(&["diff", "--cached", "--name-only"]).is_empty());
}
#[test]
fn unstage_on_unborn_head() {
let repo = TempRepo::new(0);
repo.write("a.txt", "x");
repo.git(&["add", "a.txt"]);
repo.run(|| unstage_paths(&d(&repo), &["a.txt".to_string()]).unwrap());
assert!(repo.git(&["ls-files"]).is_empty());
}
#[test]
fn unstaging_a_rename_restores_both_paths() {
let repo = TempRepo::new(1);
repo.git(&["mv", "f1.txt", "moved.txt"]);
repo.run(|| {
let state = repo_state::load().unwrap();
let e = state
.entries
.iter()
.find(|e| e.path == "moved.txt")
.unwrap();
assert_eq!(e.orig_path.as_deref(), Some("f1.txt"));
unstage_paths(&d(&repo), &entry_paths(e)).unwrap();
});
assert!(repo.git(&["diff", "--cached", "--name-only"]).is_empty());
let status = repo.git(&["status", "--porcelain"]);
assert!(status.contains(" D f1.txt") && status.contains("?? moved.txt"));
}
fn in_sub<T>(repo: &TempRepo, f: impl FnOnce() -> T) -> T {
crate::git::with_ctx(&repo.path().join("sub"), repo.env(), f)
}
#[test]
fn executors_work_from_a_subfolder() {
let repo = TempRepo::new(1);
repo.write("same.txt", "root\n");
repo.write("sub/same.txt", "sub\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-qm", "two"]);
repo.write("same.txt", "root changed\n");
repo.write("sub/same.txt", "sub changed\n");
let dir = d(&repo);
in_sub(&repo, || stage_paths(&dir, &["same.txt".to_string()])).unwrap();
assert_eq!(repo.git(&["diff", "--cached", "--name-only"]), "same.txt");
in_sub(&repo, || unstage_paths(&dir, &["same.txt".to_string()])).unwrap();
assert!(repo.git(&["diff", "--cached", "--name-only"]).is_empty());
let e = entry("same.txt", '.', 'M', EntryKind::Ordinary);
let files = in_sub(&repo, || load_files(&dir, Section::Unstaged, &e)).unwrap();
in_sub(&repo, || stage_hunk(&dir, &files[0], 0)).unwrap();
assert_eq!(repo.git(&["diff", "--cached", "--name-only"]), "same.txt");
in_sub(&repo, || discard_tracked_exec(&dir, "same.txt")).unwrap();
assert_eq!(
std::fs::read_to_string(repo.path().join("sub/same.txt")).unwrap(),
"sub changed\n"
);
repo.write("new.txt", "x");
repo.write("sub/new.txt", "y");
in_sub(&repo, || discard_untracked_exec(&dir, "new.txt")).unwrap();
assert!(!repo.path().join("new.txt").exists() && repo.path().join("sub/new.txt").exists());
}
#[test]
fn hunks_survive_user_diff_settings() {
let repo = base_repo();
repo.git(&["config", "diff.noprefix", "true"]);
repo.git(&["config", "diff.mnemonicPrefix", "true"]);
repo.run(|| {
let e = entry("big.txt", '.', 'M', EntryKind::Ordinary);
let files = load_files(&d(&repo), Section::Unstaged, &e).unwrap();
stage_hunk(&d(&repo), &files[0], 0).unwrap();
});
let cached = repo.git(&["diff", "--cached"]);
assert!(cached.contains("+THREE") && !cached.contains("THIRTY-EIGHT"));
}
}