1use std::collections::BTreeMap;
2use std::path::{Path, PathBuf};
3
4#[cfg(feature = "diff")]
5use git2::{DiffFormat, DiffOptions, Repository, Tree};
6use sha2::{Digest, Sha256};
7#[cfg(feature = "diff")]
8use tempfile::TempDir;
9
10use crate::error::{Result, TuffError};
11
12#[derive(Debug, Clone, serde::Serialize)]
13pub struct FileChange {
14 pub path: String,
15 pub status: String,
16 pub old_hash: Option<String>,
17 pub new_hash: Option<String>,
18}
19
20#[derive(Debug)]
21pub struct TreeComparison {
22 pub patch: String,
24 pub changes: Vec<FileChange>,
25}
26
27pub fn compare(old_root: &Path, new_root: &Path) -> Result<TreeComparison> {
30 let patch = patch(old_root, new_root)?;
31 let old_files = file_hashes(old_root)?;
32 let new_files = file_hashes(new_root)?;
33 let mut changes = Vec::new();
34 let mut paths = old_files.keys().cloned().collect::<Vec<_>>();
35 paths.extend(
36 new_files
37 .keys()
38 .filter(|path| !old_files.contains_key(*path))
39 .cloned(),
40 );
41 paths.sort();
42 paths.dedup();
43 for path in paths {
44 let old_hash = old_files.get(&path).cloned();
45 let new_hash = new_files.get(&path).cloned();
46 if old_hash == new_hash {
47 continue;
48 }
49 let status = match (&old_hash, &new_hash) {
50 (None, Some(_)) => "added",
51 (Some(_), None) => "removed",
52 (Some(_), Some(_)) => "modified",
53 (None, None) => unreachable!(),
54 };
55 changes.push(FileChange {
56 path,
57 status: status.to_string(),
58 old_hash,
59 new_hash,
60 });
61 }
62
63 Ok(TreeComparison { patch, changes })
64}
65
66#[cfg(feature = "diff")]
69fn patch(old_root: &Path, new_root: &Path) -> Result<String> {
70 let temp = TempDir::new()?;
71 let repository = Repository::init(temp.path()).map_err(git_error)?;
72 let old_tree = write_tree(&repository, old_root)?;
73 let new_tree = write_tree(&repository, new_root)?;
74
75 let mut options = DiffOptions::new();
76 let diff = repository
77 .diff_tree_to_tree(Some(&old_tree), Some(&new_tree), Some(&mut options))
78 .map_err(git_error)?;
79 let mut patch = Vec::new();
80 diff.print(DiffFormat::Patch, |_delta, _hunk, line| {
81 match line.origin() {
82 '+' | '-' | ' ' => {
83 patch.push(line.origin() as u8);
84 patch.extend_from_slice(line.content());
85 }
86 _ => patch.extend_from_slice(line.content()),
87 }
88 true
89 })
90 .map_err(git_error)?;
91 Ok(String::from_utf8_lossy(&patch).into_owned())
92}
93
94#[cfg(not(feature = "diff"))]
95fn patch(_old_root: &Path, _new_root: &Path) -> Result<String> {
96 Ok(String::new())
97}
98
99#[cfg(feature = "diff")]
100fn write_tree<'repo>(repository: &'repo Repository, root: &Path) -> Result<Tree<'repo>> {
101 let workdir = repository
102 .workdir()
103 .ok_or_else(|| TuffError::new("temporary git repository has no workdir"))?;
104 for entry in std::fs::read_dir(workdir)? {
105 let entry = entry?;
106 if entry.file_name() == ".git" {
107 continue;
108 }
109 let path = entry.path();
110 if path.is_dir() {
111 std::fs::remove_dir_all(path)?;
112 } else {
113 std::fs::remove_file(path)?;
114 }
115 }
116 copy_tree(root, workdir)?;
117
118 let mut index = repository.index().map_err(git_error)?;
119 index.clear().map_err(git_error)?;
120 let mut files = Vec::new();
121 collect_paths(root, root, &mut files)?;
122 files.sort();
123 for path in files {
124 index.add_path(&path).map_err(git_error)?;
125 }
126 index.write().map_err(git_error)?;
127 let tree_id = index.write_tree().map_err(git_error)?;
128 repository.find_tree(tree_id).map_err(git_error)
129}
130
131#[cfg(feature = "diff")]
132fn copy_tree(source: &Path, destination: &Path) -> Result<()> {
133 for entry in std::fs::read_dir(source)? {
134 let entry = entry?;
135 let source_path = entry.path();
136 let destination_path = destination.join(entry.file_name());
137 if source_path.is_dir() {
138 std::fs::create_dir_all(&destination_path)?;
139 copy_tree(&source_path, &destination_path)?;
140 } else if source_path.is_file() {
141 std::fs::copy(source_path, destination_path)?;
142 }
143 }
144 Ok(())
145}
146
147fn collect_paths(root: &Path, current: &Path, output: &mut Vec<PathBuf>) -> Result<()> {
148 for entry in std::fs::read_dir(current)? {
149 let path = entry?.path();
150 if path.is_dir() {
151 collect_paths(root, &path, output)?;
152 } else if path.is_file() {
153 output.push(
154 path.strip_prefix(root)
155 .map(PathBuf::from)
156 .map_err(|error| {
157 TuffError::of(crate::error::ErrorKind::Io, error.to_string())
158 })?,
159 );
160 }
161 }
162 Ok(())
163}
164
165fn file_hashes(root: &Path) -> Result<BTreeMap<String, String>> {
166 let mut paths = Vec::new();
167 collect_paths(root, root, &mut paths)?;
168 let mut result = BTreeMap::new();
169 for relative in paths {
170 let content = std::fs::read(root.join(&relative))?;
171 let mut hasher = Sha256::new();
172 hasher.update(content);
173 result.insert(
174 relative.to_string_lossy().replace('\\', "/"),
175 format!("{:x}", hasher.finalize()),
176 );
177 }
178 Ok(result)
179}
180
181#[cfg(feature = "diff")]
182fn git_error(error: git2::Error) -> TuffError {
183 TuffError::new(format!("git2 diff failed: {error}"))
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189 use tempfile::TempDir;
190
191 #[test]
192 fn compares_added_removed_and_modified_files() {
193 let old = TempDir::new().unwrap();
194 let new = TempDir::new().unwrap();
195 std::fs::write(old.path().join("modified"), "old").unwrap();
196 std::fs::write(old.path().join("removed"), "gone").unwrap();
197 std::fs::write(new.path().join("modified"), "new").unwrap();
198 std::fs::write(new.path().join("added"), "new file").unwrap();
199
200 let result = compare(old.path(), new.path()).unwrap();
201 assert_eq!(result.changes.len(), 3);
202 assert!(result.changes.iter().any(|change| change.status == "added"));
203 assert!(
204 result
205 .changes
206 .iter()
207 .any(|change| change.status == "removed")
208 );
209 assert!(
210 result
211 .changes
212 .iter()
213 .any(|change| change.status == "modified")
214 );
215 assert_eq!(
217 result.patch.contains("+new file"),
218 cfg!(feature = "diff"),
219 "{}",
220 result.patch
221 );
222 }
223}