1use std::collections::{BTreeMap, BTreeSet};
2use std::fs::{self, Permissions};
3use std::io::ErrorKind;
4use std::path::{Component, Path, PathBuf};
5
6use anyhow::{Context, Result};
7use gix::bstr::ByteSlice;
8use gix::objs::tree::EntryKind;
9
10use crate::branches::default_upstream_commit;
11use crate::status::{IgnoredFiles, status_paths};
12use crate::{discover, repo_covering};
13
14const NEED_FULL_FETCH: &str =
16 "cannot compare versions against the default branch (need a full fetch, not a shallow clone)";
17
18pub fn files_on_merge_base(
37 root: &Path,
38 rels: &[&Path],
39 candidates: &[String],
40) -> Result<Vec<Option<String>>> {
41 let Some(repo) = repo_covering(root) else {
42 return Ok(vec![None; rels.len()]);
43 };
44 let Some(upstream) = default_upstream_commit(&repo, candidates)? else {
45 return Ok(vec![None; rels.len()]);
46 };
47 let head = repo
48 .head_commit()
49 .context("cannot compare versions (need HEAD)")?;
50 let base = repo
51 .merge_base(head.id(), upstream)
52 .context(NEED_FULL_FETCH)?
53 .context(NEED_FULL_FETCH)?;
54 let tree = repo.find_commit(base)?.tree()?;
55 let workdir = repo.workdir().map(Path::to_path_buf);
56 Ok(rels
57 .iter()
58 .map(|rel| git_path(root, rel, workdir.as_deref()).and_then(|path| blob_at(&tree, &path)))
59 .collect())
60}
61
62pub(crate) fn git_path(root: &Path, rel: &Path, workdir: Option<&Path>) -> Option<PathBuf> {
69 let abs = if rel.is_absolute() {
70 rel.canonicalize().ok().or_else(|| {
71 rel.parent()?
72 .canonicalize()
73 .ok()
74 .map(|dir| dir.join(rel.file_name().unwrap_or_default()))
75 })?
76 } else {
77 let inside: PathBuf = rel
78 .components()
79 .filter(|part| !matches!(part, Component::CurDir))
80 .collect();
81 root.canonicalize().ok()?.join(inside)
82 };
83 let workdir = workdir?.canonicalize().ok()?;
84 abs.strip_prefix(workdir).ok().map(Path::to_path_buf)
85}
86
87#[derive(Debug)]
91pub struct MergeBase {
92 repo: gix::Repository,
93 workdir: PathBuf,
94 files: BTreeMap<String, (gix::ObjectId, EntryKind)>,
95 changed: BTreeSet<String>,
96}
97
98impl MergeBase {
99 pub fn read(root: &Path, candidates: &[String]) -> Result<Option<Self>> {
113 let Some(repo) = repo_covering(root) else {
114 return Ok(None);
115 };
116 let Some(upstream) = default_upstream_commit(&repo, candidates)? else {
117 return Ok(None);
118 };
119 let (files, head_files) = {
120 let head = repo
121 .head_commit()
122 .context("cannot compare the Version PR (need HEAD)")?;
123 let base = repo
124 .merge_base(head.id(), upstream)
125 .context(NEED_FULL_FETCH)?
126 .context(NEED_FULL_FETCH)?;
127 (
128 files_of(&repo.find_commit(base)?.tree()?)?,
129 files_of(&head.tree()?)?,
130 )
131 };
132 let workdir = repo
133 .workdir()
134 .context("the Version PR check needs a working tree")?
135 .canonicalize()
136 .context("the working tree")?;
137 let mut candidates: BTreeSet<String> = files
138 .keys()
139 .chain(head_files.keys())
140 .filter(|path| files.get(*path) != head_files.get(*path))
141 .cloned()
142 .collect();
143 candidates.extend(
144 status_paths(&repo, Vec::new(), IgnoredFiles::Skip)
145 .context("git status")?
146 .into_iter()
147 .filter(|path| files.contains_key(path) || head_files.contains_key(path)),
148 );
149 let mut merge_base = Self {
150 repo,
151 workdir,
152 files,
153 changed: BTreeSet::new(),
154 };
155 for path in candidates {
156 if merge_base.differs(&path, head_files.get(&path))? {
157 merge_base.changed.insert(path);
158 }
159 }
160 Ok(Some(merge_base))
161 }
162
163 fn differs(&self, rel: &str, head: Option<&(gix::ObjectId, EntryKind)>) -> Result<bool> {
169 let base = self.files.get(rel);
170 let gitlink = |entry: Option<&(gix::ObjectId, EntryKind)>| {
171 entry.is_some_and(|(_, kind)| *kind == EntryKind::Commit)
172 };
173 if gitlink(base) || gitlink(head) {
174 return Ok(base != head);
175 }
176 let expected = match base {
177 None => Worktree::Missing,
178 Some((_, EntryKind::Link)) => Worktree::Link(self.base_bytes(rel)?.unwrap_or_default()),
179 Some(_) => Worktree::File(self.base_bytes(rel)?.unwrap_or_default()),
180 };
181 Ok(expected != Worktree::read(&self.workdir.join(rel))?)
182 }
183
184 #[must_use]
186 pub fn workdir(&self) -> &Path {
187 &self.workdir
188 }
189
190 #[must_use]
194 pub fn changed(&self) -> &BTreeSet<String> {
195 &self.changed
196 }
197
198 pub fn base_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
204 let Some((oid, _)) = self.files.get(rel) else {
205 return Ok(None);
206 };
207 let blob = self
208 .repo
209 .find_blob(*oid)
210 .with_context(|| format!("{rel} at the merge-base"))?;
211 Ok(Some(blob.data.clone()))
212 }
213
214 pub fn worktree_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
220 read_optional(&self.workdir.join(rel))
221 }
222
223 pub fn write_to(&self, dir: &Path) -> Result<()> {
236 use std::os::unix::fs::PermissionsExt as _;
237 for (rel, (_, kind)) in &self.files {
238 let mode = match kind {
239 EntryKind::Blob => 0o644,
240 EntryKind::BlobExecutable => 0o755,
241 EntryKind::Link | EntryKind::Tree | EntryKind::Commit => continue,
242 };
243 let path = dir.join(rel);
244 if let Some(parent) = path.parent() {
245 fs::create_dir_all(parent)
246 .with_context(|| format!("create {}", parent.display()))?;
247 }
248 let bytes = self.base_bytes(rel)?.unwrap_or_default();
249 fs::write(&path, bytes).with_context(|| format!("write {}", path.display()))?;
250 fs::set_permissions(&path, Permissions::from_mode(mode))
251 .with_context(|| format!("chmod {}", path.display()))?;
252 }
253 Ok(())
254 }
255}
256
257#[derive(Debug, PartialEq, Eq)]
260enum Worktree {
261 Missing,
262 Link(Vec<u8>),
263 File(Vec<u8>),
264}
265
266impl Worktree {
267 fn read(path: &Path) -> Result<Self> {
268 use std::os::unix::ffi::OsStrExt as _;
269 let metadata = match fs::symlink_metadata(path) {
270 Ok(metadata) => metadata,
271 Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Self::Missing),
272 Err(error) => return Err(error).with_context(|| path.display().to_string()),
273 };
274 if metadata.file_type().is_symlink() {
275 let target = fs::read_link(path).with_context(|| path.display().to_string())?;
276 return Ok(Self::Link(target.as_os_str().as_bytes().to_vec()));
277 }
278 let bytes = fs::read(path).with_context(|| path.display().to_string())?;
279 Ok(Self::File(bytes))
280 }
281}
282
283pub fn read_optional(path: &Path) -> Result<Option<Vec<u8>>> {
289 match fs::read(path) {
290 Ok(bytes) => Ok(Some(bytes)),
291 Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
292 Err(error) => Err(error).with_context(|| path.display().to_string()),
293 }
294}
295
296pub(crate) fn files_of(
300 tree: &gix::Tree<'_>,
301) -> Result<BTreeMap<String, (gix::ObjectId, EntryKind)>> {
302 Ok(tree
303 .traverse()
304 .breadthfirst
305 .files()?
306 .into_iter()
307 .filter(|entry| !entry.mode.is_tree())
308 .map(|entry| {
309 (
310 entry.filepath.to_str_lossy().into_owned(),
311 (entry.oid, entry.mode.kind()),
312 )
313 })
314 .collect())
315}
316
317pub fn file_at(root: &Path, sha: &str, path: &Path) -> Result<Option<String>> {
325 let repo = discover(root).context("reading a file at a commit needs a git repository")?;
326 let rel = git_path(root, path, repo.workdir())
327 .with_context(|| format!("{} is not in the repository", path.display()))?;
328 let id = gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
329 let commit = repo
330 .find_commit(id)
331 .with_context(|| format!("commit {sha} is not in the repository"))?;
332 Ok(blob_at(&commit.tree()?, &rel))
333}
334
335pub(crate) fn blob_at(tree: &gix::Tree<'_>, rel: &Path) -> Option<String> {
336 let entry = tree.lookup_entry_by_path(rel).ok()??;
337 let blob = entry.object().ok()?.try_into_blob().ok()?;
338 Some(String::from_utf8_lossy(&blob.data).into_owned())
339}
340
341pub fn files_named_at(
349 root: &Path,
350 sha: &str,
351 dir: &Path,
352 file_name: &str,
353) -> Result<Vec<(String, String)>> {
354 let repo = discover(root).context("reading files at a commit needs a git repository")?;
355 let dir = dir
356 .canonicalize()
357 .with_context(|| format!("resolve {}", dir.display()))?;
358 let dir_rel = git_path(root, &dir, repo.workdir())
359 .with_context(|| format!("{} is not in the repository", dir.display()))?;
360 let id = gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
361 let commit = repo
362 .find_commit(id)
363 .with_context(|| format!("commit {sha} is not in the repository"))?;
364 let mut found = Vec::new();
365 for (rel, (oid, kind)) in files_of(&commit.tree()?)? {
366 if !matches!(kind, EntryKind::Blob | EntryKind::BlobExecutable) {
367 continue;
368 }
369 let path = Path::new(&rel);
370 if path.file_name().and_then(|name| name.to_str()) != Some(file_name) {
371 continue;
372 }
373 let under_dir = if dir_rel.as_os_str().is_empty() {
374 path
375 } else if let Ok(stripped) = path.strip_prefix(&dir_rel) {
376 stripped
377 } else {
378 continue;
379 };
380 let blob = repo
381 .find_object(oid)
382 .with_context(|| format!("read {rel} at commit {sha}"))?
383 .try_into_blob()
384 .with_context(|| format!("{rel} at commit {sha} is not a blob"))?;
385 found.push((
386 under_dir.to_string_lossy().into_owned(),
387 String::from_utf8_lossy(&blob.data).into_owned(),
388 ));
389 }
390 Ok(found)
391}