use std::path::{Path, PathBuf};
use similar::{ChangeTag, TextDiff};
const DIFF_LINES: usize = 48;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocumentFile {
path: PathBuf,
name: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Snapshot(pub Option<String>);
impl Snapshot {
pub fn content(&self) -> Option<&str> {
self.0.as_deref()
}
}
impl DocumentFile {
pub fn new(sandbox_dir: &Path, name: &str) -> Self {
Self {
path: sandbox_dir.join(name),
name: name.to_string(),
}
}
pub fn name(&self) -> &str {
&self.name
}
pub async fn read(&self) -> Snapshot {
match async_fs::read_to_string(&self.path).await {
Ok(content) => Snapshot(Some(content)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Snapshot(None),
Err(error) => {
tracing::warn!(
path = %self.path.display(),
%error,
"the working document cannot be read"
);
Snapshot(None)
}
}
}
}
pub fn diff(previous: &Snapshot, current: &Snapshot) -> Option<String> {
if previous == current {
return None;
}
let diff = TextDiff::from_lines(
previous.content().unwrap_or_default(),
current.content().unwrap_or_default(),
);
let mut lines = Vec::new();
for change in diff.iter_all_changes() {
let prefix = match change.tag() {
ChangeTag::Delete => "- ",
ChangeTag::Insert => "+ ",
ChangeTag::Equal => continue,
};
let value = change.value().trim_end_matches('\n');
if value.is_empty() {
continue;
}
lines.push([prefix, value].concat());
if lines.len() == DIFF_LINES {
lines.push("...".to_string());
break;
}
}
Some(lines.join("\n"))
}
#[cfg(feature = "languages")]
pub fn added(previous: &Snapshot, current: &Snapshot) -> Option<String> {
if previous == current {
return None;
}
let diff = TextDiff::from_lines(
previous.content().unwrap_or_default(),
current.content().unwrap_or_default(),
);
let added: String = diff
.iter_all_changes()
.filter(|change| change.tag() == ChangeTag::Insert)
.map(|change| change.value())
.collect();
(!added.trim().is_empty()).then_some(added)
}