vvv_engine/protocol/
diff.rs1use std::fmt;
2use std::path::Path;
3
4use serde::{Deserialize, Serialize};
5use similar::TextDiff;
6
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(transparent)]
10pub struct UnifiedDiff(String);
11
12impl UnifiedDiff {
13 pub fn of(path: &Path, before: &str, after: &str) -> Self {
14 Self::between(path, path, before, after)
15 }
16
17 pub fn between(old_path: &Path, new_path: &Path, before: &str, after: &str) -> Self {
19 let mut text = TextDiff::from_lines(before, after)
20 .unified_diff()
21 .context_radius(3)
22 .header(
23 &format!("a/{}", old_path.display()),
24 &format!("b/{}", new_path.display()),
25 )
26 .to_string();
27 if text.is_empty() && old_path != new_path {
28 text = format!(
29 "--- a/{}\n+++ b/{}\n",
30 old_path.display(),
31 new_path.display()
32 );
33 }
34 Self(text)
35 }
36
37 pub fn as_str(&self) -> &str {
38 &self.0
39 }
40}
41
42impl fmt::Display for UnifiedDiff {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 f.write_str(&self.0)
45 }
46}