Skip to main content

verctl_git/
merge_base.rs

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
14/// What a missing or unreachable merge-base means for a version comparison.
15const NEED_FULL_FETCH: &str =
16    "cannot compare versions against the default branch (need a full fetch, not a shallow clone)";
17
18/// File contents at the merge-base of HEAD and the default branch.
19///
20/// Paths are relative to `root` (the directory containing `.ctl/`) and are
21/// mapped onto the git workdir so `-c crates/foo/.ctl/ver.yaml` still hits the
22/// right blob. One repository open for the whole list.
23///
24/// Every entry is `None` when there is no repository, or when the repository
25/// has no `origin` remote and none of the candidate refs exists. A path
26/// missing from the merge-base tree is `None` for that entry only.
27///
28/// # Errors
29///
30/// Returns an error when:
31///
32/// - `origin` exists but resolving its default branch ref fails;
33/// - HEAD names no commit;
34/// - there is no merge-base (a shallow clone, for one);
35/// - the merge-base commit or its tree cannot be read.
36pub 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
62/// `rel` as a path inside the repository. A relative path joins the
63/// canonical root without being canonicalized itself. A file deleted from the
64/// working tree still resolves to its committed copy this way. The version
65/// guard has to see a manifest that a pull request removed. An absolute path
66/// to a file that is gone resolves through its canonical directory, so a
67/// fragment a commit deleted still names its committed copy.
68pub(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/// The tree at the merge-base of HEAD and the pull request's base, and the
88/// paths the working tree changes against it. The content check for a Version
89/// PR replays the version step on this tree.
90#[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    /// Read the merge-base tree and list each tracked path that differs from
100    /// it: committed on the branch, modified, or deleted. A symlink or a
101    /// submodule differs when its entry on HEAD does. Untracked files are left
102    /// out.
103    ///
104    /// `None` when there is no repository, or no `origin` and none of the
105    /// candidate refs, as for [`files_on_merge_base`].
106    ///
107    /// # Errors
108    ///
109    /// Returns an error under the conditions of [`files_on_merge_base`], or
110    /// when a tree, a blob, a working tree file, or `git status` cannot be
111    /// read.
112    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    /// Whether `rel` differs from the merge-base. A regular file compares by
164    /// its bytes in the working tree, and a symlink by its target there, so an
165    /// uncommitted edit counts. A submodule compares by its commit on HEAD:
166    /// an uncommitted submodule move is out of scope, since CI checks out a
167    /// commit.
168    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    /// The working tree's root, canonical.
185    #[must_use]
186    pub fn workdir(&self) -> &Path {
187        &self.workdir
188    }
189
190    /// Each path, relative to the working tree's root, that differs from the
191    /// merge-base. A file differs by its bytes, a symlink by its target, and a
192    /// submodule by its commit.
193    #[must_use]
194    pub fn changed(&self) -> &BTreeSet<String> {
195        &self.changed
196    }
197
198    /// A file's bytes at the merge-base, or `None` when it has no file there.
199    ///
200    /// # Errors
201    ///
202    /// Returns an error when the blob cannot be read.
203    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    /// A file's bytes in the working tree, or `None` when it is missing.
215    ///
216    /// # Errors
217    ///
218    /// Returns an error when the file exists but cannot be read.
219    pub fn worktree_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
220        read_optional(&self.workdir.join(rel))
221    }
222
223    /// Write every regular file of the merge-base tree under `dir`. Each file
224    /// keeps its executable bit.
225    ///
226    /// The whole tree is written because the replay's readers are not a fixed
227    /// list. `cargo metadata` expands member globs and needs each member's
228    /// target files. A pin or a served file can name any path. Symlinks
229    /// are not recreated, so no write through one leaves `dir`.
230    ///
231    /// # Errors
232    ///
233    /// Returns an error when a blob cannot be read or a file cannot be
234    /// written.
235    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/// What the working tree contains at a path, as the merge-base tree records it:
258/// a symlink's target, or a file's bytes.
259#[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
283/// A file's bytes, or `None` when it does not exist.
284///
285/// # Errors
286///
287/// Returns an error when the file exists but cannot be read.
288pub 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
296/// Every entry in `tree` other than a directory, by path, with its object and
297/// kind. A symlink or a submodule contains no bytes the version step writes, so
298/// the content check never replays one. It still lists one that changed.
299pub(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
317/// The text of `path` at commit `sha`, or `None` when that commit contains no
318/// such file.
319///
320/// # Errors
321///
322/// Returns an error when `root` is in no repository, when `path` is outside
323/// it, or when `sha` names no commit in it.
324pub 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
341/// Every blob named `file_name` under `dir` at commit `sha`, as
342/// `(path relative to dir, UTF-8 text)` pairs.
343///
344/// # Errors
345///
346/// Returns an error when `root` is in no repository, when `dir` is outside it,
347/// when `sha` names no commit in it, or when reading the tree or a blob fails.
348pub 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}