use crate::git::{self, Opts};
use crate::history::{self, LogEntry};
use crate::{model::Config, ui};
use anyhow::{bail, Result};
use std::collections::HashMap;
const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
const ZERO_OID: &str = "0000000000000000000000000000000000000000";
const MAX_FILE_ROWS: usize = 500;
const BIG_FILE_LINES: usize = 3000;
const BLAME_WINDOW: usize = 500;
pub fn normalize_path(path: &str) -> String {
let p = path.trim().replace('\\', "/");
p.strip_prefix("./").unwrap_or(&p).to_string()
}
pub fn top_spec(path: &str) -> String {
format!(":(top,literal){}", normalize_path(path))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NameStatus {
pub status: char,
pub score: Option<u32>,
pub path: String,
pub old: Option<String>,
}
pub fn parse_name_status(text: &str) -> Vec<NameStatus> {
let mut tokens = text.split('\0');
let mut out = Vec::new();
while let Some(raw) = tokens.next() {
let code = raw.trim();
let Some(status) = code.chars().next().filter(|c| "AMDRCTU".contains(*c)) else {
continue;
};
let score = code[1..].parse().ok();
let Some(first) = tokens.next() else { break };
if matches!(status, 'R' | 'C') {
let Some(new) = tokens.next() else { break };
out.push(NameStatus {
status,
score,
path: new.to_string(),
old: Some(first.to_string()),
});
} else {
out.push(NameStatus {
status,
score,
path: first.to_string(),
old: None,
});
}
}
out
}
pub fn describe_change(n: &NameStatus) -> String {
match (n.status, &n.old) {
('A', _) => "added".into(),
('M', _) => "modified".into(),
('D', _) => "deleted".into(),
('T', _) => "type changed".into(),
('U', _) => "unmerged".into(),
('R', Some(old)) => format!("renamed, was {old}"),
('C', Some(old)) => format!("copied from {old}"),
(c, _) => c.to_string(),
}
}
pub fn filter_files(list: &str, filter: &str) -> (Vec<String>, usize) {
let needle = filter.trim().to_lowercase();
let all: Vec<String> = list
.split('\0')
.filter(|p| !p.is_empty())
.filter(|p| needle.is_empty() || p.to_lowercase().contains(&needle))
.map(String::from)
.collect();
let more = all.len().saturating_sub(MAX_FILE_ROWS);
(all.into_iter().take(MAX_FILE_ROWS).collect(), more)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKind {
Binary,
Lines(usize),
Unknown,
}
pub fn file_kind(numstat: &str) -> FileKind {
let Some(line) = numstat.lines().next() else {
return FileKind::Unknown;
};
let mut f = line.split('\t');
match (f.next(), f.next()) {
(Some("-"), Some("-")) => FileKind::Binary,
(Some(added), Some(_)) => added.parse().map_or(FileKind::Unknown, FileKind::Lines),
_ => FileKind::Unknown,
}
}
pub fn parse_range(text: &str) -> Option<(usize, usize)> {
let t = text.trim();
let (a, b) = match t.split_once(',') {
Some((a, b)) => (a.trim().parse().ok()?, b.trim().parse().ok()?),
None => {
let a: usize = t.parse().ok()?;
(a, a)
}
};
(a >= 1 && b >= a).then_some((a, b))
}
pub fn window_start(line: usize, total: usize) -> usize {
let start = line.saturating_sub(BLAME_WINDOW / 2).max(1);
start.min(total.saturating_sub(BLAME_WINDOW).max(1))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlameLine {
pub oid: String,
pub author: String,
pub date: String,
pub orig_line: usize,
pub line_no: usize,
pub text: String,
pub boundary: bool,
pub uncommitted: bool,
pub previous: Option<(String, String)>,
pub filename: String,
pub summary: String,
}
#[derive(Default, Clone)]
struct Meta {
author: String,
time: i64,
tz: i64,
boundary: bool,
previous: Option<(String, String)>,
filename: String,
summary: String,
}
fn is_blame_header(line: &str) -> Option<(String, usize, usize)> {
let mut f = line.split(' ');
let oid = f.next()?;
if !(oid.len() == 40 || oid.len() == 64) || !oid.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let orig = f.next()?.parse().ok()?;
let fin = f.next()?.parse().ok()?;
Some((oid.to_string(), orig, fin))
}
pub fn parse_blame_porcelain(text: &str) -> Vec<BlameLine> {
let mut metas: HashMap<String, Meta> = HashMap::new();
let mut out = Vec::new();
let mut current: Option<(String, usize, usize)> = None;
for raw in text.split('\n') {
let line = raw.strip_suffix('\r').unwrap_or(raw);
if let Some(content) = line.strip_prefix('\t') {
if let Some((oid, orig, fin)) = current.take() {
let m = metas.get(&oid).cloned().unwrap_or_default();
let uncommitted = oid == ZERO_OID;
out.push(BlameLine {
author: if uncommitted {
"Not committed yet".into()
} else {
m.author
},
date: if uncommitted {
String::new()
} else {
format_date(m.time, m.tz)
},
uncommitted,
oid,
orig_line: orig,
line_no: fin,
text: content.to_string(),
boundary: m.boundary,
previous: m.previous,
filename: m.filename,
summary: m.summary,
});
}
continue;
}
if let Some(h) = is_blame_header(line) {
metas.entry(h.0.clone()).or_default();
current = Some(h);
continue;
}
let Some((oid, _, _)) = ¤t else {
continue;
};
let m = metas.entry(oid.clone()).or_default();
let (key, value) = line.split_once(' ').unwrap_or((line, ""));
match key {
"author" => m.author = value.to_string(),
"author-time" => m.time = value.parse().unwrap_or(0),
"author-tz" => m.tz = parse_tz(value).unwrap_or(0),
"summary" => m.summary = value.to_string(),
"boundary" => m.boundary = true,
"filename" => m.filename = value.to_string(),
"previous" => {
m.previous = value
.split_once(' ')
.map(|(sha, path)| (sha.to_string(), path.to_string()));
}
_ => {}
}
}
out
}
fn parse_tz(tz: &str) -> Option<i64> {
let sign = match tz.as_bytes().first()? {
b'-' => -1,
b'+' => 1,
_ => return None,
};
let digits = &tz[1..];
if digits.len() != 4 || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let h: i64 = digits[..2].parse().ok()?;
let m: i64 = digits[2..].parse().ok()?;
Some(sign * (h * 3600 + m * 60))
}
fn format_date(epoch: i64, tz: i64) -> String {
let days = (epoch + tz).div_euclid(86_400);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
format!("{y:04}-{m:02}-{d:02}")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryRow {
pub entry: LogEntry,
pub change: Option<NameStatus>,
}
pub fn parse_history(text: &str) -> Vec<HistoryRow> {
text.split('\u{1d}')
.filter_map(|section| {
let (record, rest) = section.split_once('\u{1e}')?;
let entry = history::parse_log(&format!("{record}\u{1e}"))
.into_iter()
.next()?;
let change = parse_name_status(rest).into_iter().next();
Some(HistoryRow { entry, change })
})
.collect()
}
fn date10(iso: &str) -> &str {
iso.get(..10).unwrap_or(iso)
}
fn history_row_text(r: &HistoryRow) -> String {
let what = r.change.as_ref().map(describe_change).unwrap_or_default();
format!(
"{} {} {:<14.14} {} [{}]",
r.entry.short,
date10(&r.entry.author_date),
r.entry.author,
r.entry.subject,
what
)
}
fn blame_row_text(l: &BlameLine) -> String {
let text = l.text.replace('\t', " ");
if l.uncommitted {
return format!(
"{:<8} {:<14} {:<10} {:>5} | {text}",
"-", "Not committed yet", "", l.line_no
);
}
let mark = if l.boundary { "^" } else { "" };
format!(
"{:<8} {:<14.14} {:<10} {:>5} | {text}",
format!("{mark}{}", l.oid.get(..7).unwrap_or(&l.oid)),
l.author,
l.date,
l.line_no
)
}
fn opts(max_lines: usize) -> Opts<'static> {
Opts {
max_lines: Some(max_lines),
..Opts::default()
}
}
pub fn list_files() -> Result<String> {
git::git_ok(
&["ls-files", "-z", "--full-name", "--", ":(top)"],
&Opts::default(),
)
}
pub fn file_history(path: &str) -> Result<Vec<HistoryRow>> {
let fmt = format!("--format=%x1d{}", history::LOG_FORMAT);
let spec = top_spec(path);
let text = git::git_ok(
&[
"-c",
"core.quotepath=false",
"log",
"--follow",
"-M",
&fmt,
"--name-status",
"-z",
"-n",
"200",
"--",
&spec,
],
&opts(5000),
)?;
Ok(parse_history(&text))
}
pub fn kind_of(path: &str) -> FileKind {
let spec = top_spec(path);
git::git_ok(
&["diff", "--numstat", EMPTY_TREE, "HEAD", "--", &spec],
&Opts::default(),
)
.map_or(FileKind::Unknown, |t| file_kind(&t))
}
fn is_text_attr_unset(path: &str) -> bool {
let spec = top_spec(path);
git::git_ok(&["check-attr", "text", "--", &spec], &Opts::default())
.map(|t| t.trim_end().ends_with(": unset"))
.unwrap_or(false)
}
pub fn blame(path: &str, rev: Option<&str>, start: Option<usize>) -> Result<Vec<BlameLine>> {
let cdup = git::git_ok(&["rev-parse", "--show-cdup"], &Opts::default())?;
let rel = format!("{}{}", cdup.trim(), normalize_path(path));
let range = start.map(|s| format!("{s},+{BLAME_WINDOW}"));
let mut args: Vec<&str> = vec!["blame", "--porcelain", "-M", "-w"];
if let Some(r) = &range {
args.extend(["-L", r]);
}
if let Some(rev) = rev {
if rev.starts_with('-') {
bail!("Invalid revision: {rev}");
}
args.push(rev);
}
args.extend(["--", &rel]);
let text = git::git_ok(&args, &opts(80_000))?;
Ok(parse_blame_porcelain(&text))
}
pub fn line_history(path: &str, a: usize, b: usize) -> Result<Vec<String>> {
let cdup = git::git_ok(&["rev-parse", "--show-cdup"], &Opts::default())?;
let spec = format!("{a},{b}:{}{}", cdup.trim(), normalize_path(path));
let text = git::git_ok(&["log", "-L", &spec, "--no-color", "-n", "50"], &opts(5000))?;
Ok(text.lines().map(String::from).collect())
}
pub fn run(config: &mut Config) -> Result<()> {
let list = ui::git_job("Listing files...", list_files)?;
let mut filter = match ui::ask("Filter files (part of a name, empty for all)", "")? {
Some(f) => f,
None => return Ok(()),
};
let mut index = 0;
loop {
let (files, more) = filter_files(&list, &filter);
let mut header = vec![format!("{} file(s) shown", files.len())];
if more > 0 {
header.push(format!("+{more} more, refine the filter"));
}
if files.is_empty() {
header.push("No tracked file matches. Press F to change the filter.".into());
}
let keys = [ui::Key {
key: 'f',
label: "change filter",
}];
match ui::action_list("Files", &header, &files, &keys, &mut index)? {
ui::Choice::Back => return Ok(()),
ui::Choice::Open(i) => {
if let Some(path) = files.get(i) {
file_menu(config, path)?;
}
}
ui::Choice::Action(_, _) => {
if let Some(f) = ui::ask("Filter files (part of a name, empty for all)", &filter)? {
filter = f;
index = 0;
}
}
}
}
}
#[allow(dead_code)] pub fn open(cfg: &mut Config, path: &str) -> Result<()> {
file_menu(cfg, &normalize_path(path))
}
fn file_menu(cfg: &mut Config, path: &str) -> Result<()> {
loop {
let ctx = vec![path.to_string()];
let opts = [
"History (follows renames)",
"Blame (who wrote each line)",
"Line history",
];
match ui::choose("File", &ctx, &opts)? {
Some(0) => history_view(cfg, path)?,
Some(1) => blame_view(cfg, path)?,
Some(2) => line_history_view(path)?,
_ => return Ok(()),
}
}
}
fn history_view(cfg: &mut Config, path: &str) -> Result<()> {
let p = path.to_string();
let rows = ui::git_job("Reading history...", move || file_history(&p))?;
if rows.is_empty() {
return ui::notice(
"History",
&[
format!("No commits touch {path} yet."),
"Commit the file first.".into(),
],
);
}
let texts: Vec<String> = rows.iter().map(history_row_text).collect();
let header = vec![format!(
"History of {path} (newest first, renames followed)"
)];
let mut index = 0;
loop {
match ui::action_list("File history", &header, &texts, &[], &mut index)? {
ui::Choice::Open(i) => {
if let Some(r) = rows.get(i) {
super::log::show(cfg, &r.entry.oid)?;
}
}
ui::Choice::Action(_, _) => {}
ui::Choice::Back => return Ok(()),
}
}
}
fn blame_view(cfg: &mut Config, path: &str) -> Result<()> {
match kind_of(path) {
FileKind::Binary => {
return ui::notice(
"Blame",
&[format!(
"{path} is a binary file; blame only works on text."
)],
);
}
_ if is_text_attr_unset(path) => {
return ui::notice(
"Blame",
&[format!(
"{path} is marked as binary (-text); blame skipped."
)],
);
}
_ => {}
}
let total = match kind_of(path) {
FileKind::Lines(n) => n,
_ => 0,
};
let mut start = None;
if total > BIG_FILE_LINES {
let answer = ui::ask(&format!("{total} lines: start at which line?"), "1")?;
let Some(answer) = answer else { return Ok(()) };
let line = answer.trim().parse().unwrap_or(1);
start = Some(window_start(line, total));
}
let mut stack: Vec<(Option<String>, String)> = vec![(None, path.to_string())];
let mut index = 0;
loop {
let Some((rev, p)) = stack.last().cloned() else {
return Ok(());
};
let (r2, p2) = (rev.clone(), p.clone());
let lines = match ui::git_job("Running blame...", move || blame(&p2, r2.as_deref(), start))
{
Ok(l) => l,
Err(e) if e.to_string() == crate::input::CANCELLED => return Err(e),
Err(e) => {
ui::notice("Blame", &[e.to_string()])?;
stack.pop();
continue;
}
};
let texts: Vec<String> = lines.iter().map(blame_row_text).collect();
let at = rev
.as_deref()
.map_or("working tree".to_string(), |r| r.chars().take(8).collect());
let mut header = vec![format!("Blame of {p} at {at}")];
if let Some(s) = start {
header.push(format!(
"Showing lines {s}-{} (N next window, P previous)",
s + BLAME_WINDOW - 1
));
}
header.push("Enter opens the commit, B shows the file before that change.".into());
let keys = [
ui::Key {
key: 'b',
label: "blame before this change",
},
ui::Key {
key: 'n',
label: "next window",
},
ui::Key {
key: 'p',
label: "previous window",
},
];
match ui::action_list("Blame", &header, &texts, &keys, &mut index)? {
ui::Choice::Back => {
stack.pop();
index = 0;
}
ui::Choice::Open(i) => {
if let Some(l) = lines.get(i) {
if l.uncommitted {
ui::notice("Blame", &["This line is not committed yet.".into()])?;
} else {
super::log::show(cfg, &l.oid)?;
}
}
}
ui::Choice::Action('b', i) => {
let Some(l) = lines.get(i) else { continue };
if l.uncommitted {
stack.push((Some("HEAD".into()), p.clone()));
} else if let Some((sha, prev_path)) = &l.previous {
stack.push((Some(sha.clone()), prev_path.clone()));
} else {
ui::notice(
"Blame",
&["This line comes from the first commit that has the file; nothing earlier to show.".into()],
)?;
continue;
}
index = 0;
}
ui::Choice::Action('n', _) => {
if let Some(s) = start {
if s + BLAME_WINDOW <= total {
start = Some(s + BLAME_WINDOW);
index = 0;
}
}
}
ui::Choice::Action('p', _) => {
if let Some(s) = start {
start = Some(s.saturating_sub(BLAME_WINDOW).max(1));
index = 0;
}
}
ui::Choice::Action(_, _) => {}
}
}
}
fn line_history_view(path: &str) -> Result<()> {
let Some(answer) = ui::ask("Line range (start,end), e.g. 10,25", "1,20")? else {
return Ok(());
};
let Some((a, b)) = parse_range(&answer) else {
return ui::notice(
"Line history",
&["Type two line numbers like 10,25 (start at 1).".into()],
);
};
let p = path.to_string();
match ui::git_job("Tracing lines...", move || line_history(&p, a, b)) {
Ok(lines) if lines.is_empty() => ui::notice(
"Line history",
&["No history found for those lines.".into()],
),
Ok(lines) => ui::pager(&format!("Lines {a}-{b} of {path}"), &lines, "Esc back"),
Err(e) if e.to_string() == crate::input::CANCELLED => Err(e),
Err(e) => ui::notice("Line history", &[e.to_string()]),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::TempRepo;
#[test]
fn name_status_variants() {
let t = "A\0a.txt\0M\0dir/b c.txt\0D\0d.txt\0T\0t.txt\0U\0u.txt\0R100\0old/x.rs\0new/x.rs\0C75\0s.rs\0copy of s.rs\0bogus\0";
let v = parse_name_status(t);
assert_eq!(v.len(), 7);
assert_eq!(v[1].path, "dir/b c.txt");
assert_eq!(v[3].status, 'T');
assert_eq!(v[4].status, 'U');
assert_eq!(v[5].old.as_deref(), Some("old/x.rs"));
assert_eq!(v[5].path, "new/x.rs");
assert_eq!(v[5].score, Some(100));
assert_eq!(v[6].status, 'C');
assert_eq!(v[6].score, Some(75));
assert_eq!(v[6].path, "copy of s.rs");
assert_eq!(describe_change(&v[5]), "renamed, was old/x.rs");
assert!(parse_name_status("").is_empty());
assert_eq!(parse_name_status("\nM\0a.txt\0\0")[0].path, "a.txt");
let odd = parse_name_status("R090\0we\tird\"\n.txt\0new\tname.txt\0");
assert_eq!(odd[0].old.as_deref(), Some("we\tird\"\n.txt"));
assert_eq!(odd[0].path, "new\tname.txt");
assert!(parse_name_status("R100\0only-one").is_empty());
}
#[test]
fn tz_is_total() {
assert_eq!(parse_tz("+0530"), Some(19_800));
assert_eq!(parse_tz("-0500"), Some(-18_000));
for bad in [
"",
"+",
"0530",
"+05",
"+05300",
"+\u{e9}\u{e9}",
"+0a30",
"\u{e9}0530",
"++530",
"+-530",
] {
assert_eq!(parse_tz(bad), None, "{bad:?}");
}
}
#[test]
fn history_handles_odd_names_and_literal_brackets() {
let repo = crate::testutil::TempRepo::new(0);
repo.write("a1.txt", "decoy line one\nline two\nline three\n");
repo.write("a[1].txt", "bracket file content here\nmore\nmore again\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-qm", "first"]);
repo.git(&["mv", "a[1].txt", "we ird.txt"]);
repo.git(&["commit", "-qm", "renamed"]);
let rows = repo.run(|| file_history("we ird.txt")).unwrap();
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].change.as_ref().unwrap().status, 'R');
assert_eq!(
rows[0].change.as_ref().unwrap().old.as_deref(),
Some("a[1].txt")
);
let lit = repo.run(|| file_history("a[1].txt")).unwrap();
assert!(lit
.iter()
.all(|r| r.change.as_ref().is_some_and(|c| c.path != "a1.txt")));
assert_eq!(lit.len(), 2);
assert_eq!(repo.run(|| file_history("a1.txt")).unwrap().len(), 1);
}
#[test]
fn blame_parsing() {
let a = "a".repeat(40);
let b = "b".repeat(40);
let text = format!(
"{a} 1 1 2\nauthor Ann\nauthor-mail <a@x>\nauthor-time 1704110400\nauthor-tz +0000\nsummary first\nboundary\nfilename old.txt\n\tone\n{a} 2 2\n\ttwo\n{b} 3 3 1\nauthor Bob\nauthor-time 1704110400\nauthor-tz -0500\nsummary edit\nprevious {a} old.txt\nfilename new.txt\n\tthr\u{e9}e\n{ZERO_OID} 4 4 1\nauthor Not Committed Yet\nauthor-time 1704110400\nauthor-tz +0000\nsummary Version of new.txt from new.txt\nfilename new.txt\n\tfour\r\n"
);
let v = parse_blame_porcelain(&text);
assert_eq!(v.len(), 4);
assert!(v[0].boundary && v[1].boundary);
assert_eq!(v[1].author, "Ann");
assert_eq!(v[1].text, "two");
assert_eq!(v[0].date, "2024-01-01");
assert_eq!(v[2].previous, Some((a.clone(), "old.txt".into())));
assert_eq!(v[2].filename, "new.txt");
assert_eq!(v[2].text, "thr\u{e9}e");
assert_eq!(v[2].date, "2024-01-01");
assert!(v[3].uncommitted);
assert_eq!(v[3].author, "Not committed yet");
assert_eq!(v[3].text, "four");
assert!(parse_blame_porcelain("").is_empty());
}
#[test]
fn normalize_and_helpers() {
assert_eq!(normalize_path("src\\modes\\files.rs"), "src/modes/files.rs");
assert_eq!(normalize_path("./a b.txt"), "a b.txt");
assert_eq!(top_spec("a\\b"), ":(top,literal)a/b");
assert_eq!(parse_range("10,25"), Some((10, 25)));
assert_eq!(parse_range("5"), Some((5, 5)));
assert_eq!(parse_range("0,3"), None);
assert_eq!(parse_range("9,3"), None);
assert_eq!(file_kind("-\t-\tpic.png"), FileKind::Binary);
assert_eq!(file_kind("12\t0\ta.txt"), FileKind::Lines(12));
assert_eq!(file_kind(""), FileKind::Unknown);
assert_eq!(window_start(1, 10_000), 1);
assert_eq!(window_start(5000, 10_000), 4750);
assert_eq!(window_start(9999, 10_000), 9500);
let (rows, more) = filter_files("a/B.rs\0c.txt\0\0x/b.rs\0", "B.RS");
assert_eq!(rows, vec!["a/B.rs", "x/b.rs"]);
assert_eq!(more, 0);
let big: String = (0..600).map(|i| format!("f{i}\0")).collect();
let (rows, more) = filter_files(&big, "");
assert_eq!((rows.len(), more), (500, 100));
assert_eq!(format_date(0, 0), "1970-01-01");
assert_eq!(format_date(1_704_110_400, 0), "2024-01-01");
}
#[test]
fn history_follows_rename() {
let repo = TempRepo::new(1);
repo.write("old name.txt", "a\nb\nc\nd\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-qm", "add file"]);
repo.git(&["mv", "old name.txt", "new.txt"]);
repo.git(&["commit", "-qm", "rename"]);
repo.write("new.txt", "a\nb\nc\nd\ne\n");
repo.git(&["commit", "-qam", "edit"]);
let rows = repo.run(|| file_history("new.txt")).unwrap();
let subjects: Vec<&str> = rows.iter().map(|r| r.entry.subject.as_str()).collect();
assert_eq!(subjects, vec!["edit", "rename", "add file"]);
let rename = rows[1].change.as_ref().unwrap();
assert_eq!(rename.status, 'R');
assert_eq!(rename.old.as_deref(), Some("old name.txt"));
assert_eq!(rows[2].change.as_ref().unwrap().status, 'A');
}
#[test]
fn blame_attributes_lines() {
let repo = TempRepo::new(1);
repo.write("sub/f.txt", "one\ntwo\nthree\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-qm", "first"]);
let first = repo.git(&["rev-parse", "HEAD"]);
repo.write("sub/f.txt", "one\nTWO\nthree\n");
repo.git(&["commit", "-qam", "second"]);
let second = repo.git(&["rev-parse", "HEAD"]);
let lines = repo.run(|| blame("sub\\f.txt", None, None)).unwrap();
assert_eq!(lines.len(), 3);
assert_eq!(lines[0].oid, first);
assert_eq!(lines[1].oid, second);
assert_eq!(lines[1].text, "TWO");
assert_eq!(lines[2].oid, first);
assert_eq!(
lines[1].previous.as_ref().map(|p| p.0.clone()),
Some(first.clone())
);
let before = repo.run(|| blame("sub/f.txt", Some(&first), None)).unwrap();
assert_eq!(before[1].text, "two");
let kind = repo.run(|| kind_of("sub/f.txt"));
assert_eq!(kind, FileKind::Lines(3));
let hist = repo.run(|| line_history("sub/f.txt", 2, 2)).unwrap();
assert!(hist.iter().any(|l| l.contains("second")));
let files = repo.run(list_files).unwrap();
assert!(files.split('\0').any(|f| f == "sub/f.txt"));
}
}