use std::io::{self, Write};
use std::sync::OnceLock;
use crate::delta::{DiffType, State};
const SUPPORTED_VERSION: u32 = 1;
const OSC: &str = "\x1b]1717";
const ST: &str = "\x1b\\";
fn pick_version(advertised: &str) -> Option<u32> {
advertised
.split(',')
.filter_map(|v| v.trim().strip_prefix('V')?.parse::<u32>().ok())
.filter(|v| *v <= SUPPORTED_VERSION)
.max()
}
pub fn negotiated_version() -> Option<u32> {
static VERSION: OnceLock<Option<u32>> = OnceLock::new();
*VERSION.get_or_init(|| pick_version(&std::env::var("OSC1717").ok()?))
}
pub fn handshake() -> String {
negotiated_version().map_or(String::new(), handshake_for_version)
}
fn handshake_for_version(version: u32) -> String {
format!("{OSC};{version}{ST}")
}
pub struct DiffLineMetadata {
version: u32,
old_line: usize,
new_line: usize,
file: String,
last_record: Option<(char, usize, Option<usize>)>,
}
impl DiffLineMetadata {
pub fn from_env() -> Option<Self> {
negotiated_version().map(|version| Self {
version,
old_line: 0,
new_line: 0,
file: String::new(),
last_record: None,
})
}
#[cfg(test)]
pub fn v1_for_tests() -> Self {
Self {
version: 1,
old_line: 0,
new_line: 0,
file: String::new(),
last_record: None,
}
}
pub fn initialize_hunk(&mut self, line_numbers: &[(usize, usize)], file: String) {
self.old_line = line_numbers[0].0;
self.new_line = line_numbers[line_numbers.len() - 1].0;
self.file = file;
}
pub fn osc_for_line(&mut self, state: &State) -> String {
use State::*;
let record = match state {
HunkZero(DiffType::Unified, _) => {
let record = ('c', self.new_line, None);
self.old_line += 1;
self.new_line += 1;
record
}
HunkPlus(DiffType::Unified, _) => {
let record = ('a', self.new_line, None);
self.new_line += 1;
record
}
HunkMinus(DiffType::Unified, _) => {
let record = ('d', self.new_line, Some(self.old_line));
self.old_line += 1;
record
}
HunkZeroWrapped | HunkMinusWrapped | HunkPlusWrapped => match self.last_record {
Some(record) => record,
None => return String::new(),
},
_ => return String::new(),
};
self.last_record = Some(record);
let (type_char, new_line, old_line) = record;
let old_field = old_line.map_or(String::new(), |n| n.to_string());
format!(
"{OSC};{version};{type_char};{new_line};{old_field};{file}{ST}",
version = self.version,
file = self.file,
)
}
pub fn osc_for_hunk_header(&self) -> String {
self.header_osc('h', Some(self.new_line), &self.file)
}
pub fn osc_for_file_header(&self, file: &str) -> String {
self.header_osc('f', None, file)
}
fn header_osc(&self, type_char: char, new_line: Option<usize>, file: &str) -> String {
let new_field = new_line.map_or(String::new(), |n| n.to_string());
format!(
"{OSC};{version};{type_char};{new_field};;{file}{ST}",
version = self.version,
)
}
pub fn osc_for_commit(&self, commit: &str) -> String {
format!("{OSC};{version};C;;;{commit}{ST}", version = self.version)
}
}
pub fn commit_id(line: &str, marker_end: usize) -> Option<&str> {
let commit = line.get(marker_end..)?.split_whitespace().next()?;
let is_hash = commit.len() >= 4 && commit.chars().all(|c| c.is_ascii_hexdigit());
is_hash.then_some(commit)
}
struct OscLinePrefixer<'a> {
inner: &'a mut dyn Write,
prefix: &'a str,
at_line_start: bool,
}
impl Write for OscLinePrefixer<'_> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
for chunk in buf.split_inclusive(|&b| b == b'\n') {
if self.at_line_start {
self.inner.write_all(self.prefix.as_bytes())?;
}
self.inner.write_all(chunk)?;
self.at_line_start = chunk.ends_with(b"\n");
}
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}
pub fn write_with_header_osc(
writer: &mut dyn Write,
osc: &str,
draw: impl FnOnce(&mut dyn Write) -> io::Result<()>,
) -> io::Result<()> {
if osc.is_empty() {
draw(writer)
} else {
let mut prefixer = OscLinePrefixer {
inner: writer,
prefix: osc,
at_line_start: true,
};
draw(&mut prefixer)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::delta::{DiffType, State};
fn emitter() -> DiffLineMetadata {
let mut md = DiffLineMetadata::v1_for_tests();
md.initialize_hunk(&[(1, 3), (1, 4)], "f.txt".to_owned());
md
}
#[test]
fn test_handshake_is_version_only() {
assert_eq!(handshake_for_version(1), "\x1b]1717;1\x1b\\");
}
#[test]
fn test_hunk_header_record_carries_the_hunks_first_line() {
let mut md = emitter();
assert_eq!(md.osc_for_hunk_header(), "\x1b]1717;1;h;1;;f.txt\x1b\\");
assert_eq!(
md.osc_for_line(&State::HunkZero(DiffType::Unified, None)),
"\x1b]1717;1;c;1;;f.txt\x1b\\"
);
}
#[test]
fn test_file_header_record_has_no_line_numbers() {
let md = emitter();
assert_eq!(
md.osc_for_file_header("src/foo.rs"),
"\x1b]1717;1;f;;;src/foo.rs\x1b\\"
);
}
#[test]
fn test_header_record_prefixes_every_row_of_a_multi_row_block() {
let draw = |w: &mut dyn io::Write| -> io::Result<()> {
write!(w, "โโโ\n1:โ\nโโโ\n")
};
let mut tagged = Vec::new();
write_with_header_osc(&mut tagged, "[osc]", draw).unwrap();
assert_eq!(
String::from_utf8(tagged).unwrap(),
"[osc]โโโ\n[osc]1:โ\n[osc]โโโ\n"
);
let mut untouched = Vec::new();
write_with_header_osc(&mut untouched, "", draw).unwrap();
assert_eq!(String::from_utf8(untouched).unwrap(), "โโโ\n1:โ\nโโโ\n");
}
#[test]
fn test_commit_record_carries_the_commit_id() {
let md = emitter();
assert_eq!(
md.osc_for_commit("dbb7c03c3f306c0b12ce003358e1fd17c3fd2701"),
"\x1b]1717;1;C;;;dbb7c03c3f306c0b12ce003358e1fd17c3fd2701\x1b\\"
);
}
#[test]
fn test_commit_id_is_the_token_after_what_marks_the_line() {
assert_eq!(
commit_id("commit dbb7c03 (HEAD -> main, origin/main)", 7),
Some("dbb7c03")
);
assert_eq!(commit_id("commit ", 7), None);
assert_eq!(commit_id("commit not-a-hash", 7), None);
}
#[test]
fn test_wrapped_rows_reemit_the_primary_record_without_advancing() {
let mut md = emitter();
let zero = md.osc_for_line(&State::HunkZero(DiffType::Unified, None));
let plus = md.osc_for_line(&State::HunkPlus(DiffType::Unified, None));
let plus_w1 = md.osc_for_line(&State::HunkPlusWrapped);
let plus_w2 = md.osc_for_line(&State::HunkPlusWrapped);
let zero_after = md.osc_for_line(&State::HunkZero(DiffType::Unified, None));
assert_eq!(zero, "\x1b]1717;1;c;1;;f.txt\x1b\\");
assert_eq!(plus, "\x1b]1717;1;a;2;;f.txt\x1b\\");
assert_eq!(plus_w1, plus);
assert_eq!(plus_w2, plus);
assert_eq!(zero_after, "\x1b]1717;1;c;3;;f.txt\x1b\\");
}
#[test]
fn test_wrapped_deletion_reemits_both_line_numbers() {
let mut md = emitter();
let minus = md.osc_for_line(&State::HunkMinus(DiffType::Unified, None));
let minus_w = md.osc_for_line(&State::HunkMinusWrapped);
assert_eq!(minus, "\x1b]1717;1;d;1;1;f.txt\x1b\\");
assert_eq!(minus_w, minus);
}
#[test]
fn test_wrapped_row_with_no_preceding_primary_emits_nothing() {
let mut md = emitter();
assert_eq!(md.osc_for_line(&State::HunkZeroWrapped), "");
}
#[test]
fn test_pick_version() {
assert_eq!(pick_version("V1"), Some(1));
assert_eq!(pick_version("V1,V2"), Some(1)); assert_eq!(pick_version("V2,V3"), None); assert_eq!(pick_version(""), None);
assert_eq!(pick_version("garbage"), None);
}
#[test]
fn test_unified_context_addition_deletion_sequence() {
let mut md = emitter();
assert_eq!(
md.osc_for_line(&State::HunkZero(DiffType::Unified, None)),
"\x1b]1717;1;c;1;;f.txt\x1b\\"
);
assert_eq!(
md.osc_for_line(&State::HunkMinus(DiffType::Unified, None)),
"\x1b]1717;1;d;2;2;f.txt\x1b\\"
);
assert_eq!(
md.osc_for_line(&State::HunkMinus(DiffType::Unified, None)),
"\x1b]1717;1;d;2;3;f.txt\x1b\\"
);
assert_eq!(
md.osc_for_line(&State::HunkPlus(DiffType::Unified, None)),
"\x1b]1717;1;a;2;;f.txt\x1b\\"
);
assert_eq!(
md.osc_for_line(&State::HunkPlus(DiffType::Unified, None)),
"\x1b]1717;1;a;3;;f.txt\x1b\\"
);
assert_eq!(
md.osc_for_line(&State::HunkZero(DiffType::Unified, None)),
"\x1b]1717;1;c;4;;f.txt\x1b\\"
);
}
#[test]
fn test_initialize_hunk_reseeds_the_counters() {
let mut md = emitter();
md.initialize_hunk(&[(20, 3), (25, 4)], "f.txt".to_owned());
assert_eq!(
md.osc_for_line(&State::HunkZero(DiffType::Unified, None)),
"\x1b]1717;1;c;25;;f.txt\x1b\\"
);
assert_eq!(
md.osc_for_line(&State::HunkMinus(DiffType::Unified, None)),
"\x1b]1717;1;d;26;21;f.txt\x1b\\"
);
}
#[test]
fn test_whole_file_deletion_sits_at_new_line_zero() {
let mut md = emitter();
md.initialize_hunk(&[(1, 3), (0, 0)], "gone.txt".to_owned());
assert_eq!(
md.osc_for_line(&State::HunkMinus(DiffType::Unified, None)),
"\x1b]1717;1;d;0;1;gone.txt\x1b\\"
);
assert_eq!(
md.osc_for_line(&State::HunkMinus(DiffType::Unified, None)),
"\x1b]1717;1;d;0;2;gone.txt\x1b\\"
);
}
#[test]
fn test_path_may_contain_semicolons() {
let mut md = emitter();
md.initialize_hunk(&[(1, 1), (1, 1)], "weird;name.txt".to_owned());
assert_eq!(
md.osc_for_line(&State::HunkPlus(DiffType::Unified, None)),
"\x1b]1717;1;a;1;;weird;name.txt\x1b\\"
);
}
}