Skip to main content

surjection_core/layering/
git.rs

1//! The project's git repository, for the private-file rules of SPEC 6.5:
2//! whether a client file is tracked or ignored, and hiding an untracked
3//! private file through `info/exclude`. git2 needs a real repository on
4//! disk, so these work on real paths.
5
6use std::path::{Path, PathBuf};
7
8use crate::error::{CoreError, ErrorCode};
9use crate::fs::Fs;
10
11/// The work tree holding a project folder. Its folders are spelled like the
12/// folder it was discovered from: git2 reports resolved paths (symlinks
13/// such as macOS `/var`, Windows 8.3 short names expanded), and files the
14/// caller reads or writes through [`Fs`] stay under the spelling it uses.
15pub struct ProjectRepo {
16    repo: git2::Repository,
17    workdir: PathBuf,
18    commondir: PathBuf,
19}
20
21impl std::fmt::Debug for ProjectRepo {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        f.debug_struct("ProjectRepo")
24            .field("workdir", &self.workdir)
25            .finish_non_exhaustive()
26    }
27}
28
29fn git_error(err: git2::Error) -> CoreError {
30    CoreError::new(ErrorCode::GitError, err.message().to_owned())
31}
32
33impl ProjectRepo {
34    /// The repository whose work tree holds `root`; `None` when there is no
35    /// repository there or it is bare. Any other failure (a repository git
36    /// refuses to open, such as one owned by another user, or a broken
37    /// config) is `git_error`: whether a file is tracked is then unknown.
38    pub fn discover(root: &Path) -> Result<Option<Self>, CoreError> {
39        let repo = match git2::Repository::discover(root) {
40            Ok(repo) => repo,
41            Err(err) if err.code() == git2::ErrorCode::NotFound => return Ok(None),
42            Err(err) => return Err(git_error(err).with_path(root)),
43        };
44        let Some(workdir) = repo.workdir().map(|dir| spelled_like(dir, root)) else {
45            return Ok(None);
46        };
47        let commondir = spelled_like(repo.commondir(), root);
48        Ok(Some(Self {
49            repo,
50            workdir,
51            commondir,
52        }))
53    }
54
55    /// The work tree root.
56    pub fn workdir(&self) -> &Path {
57        &self.workdir
58    }
59
60    /// `path` relative to the work tree, `/`-separated; `None` when it lies
61    /// outside.
62    pub fn relative(&self, path: &Path) -> Option<String> {
63        let rest = match path.strip_prefix(&self.workdir) {
64            Ok(rest) => rest.to_path_buf(),
65            Err(_) => {
66                // Spellings differ (8.3 names, symlinks): compare the
67                // canonical forms of the deepest existing ancestors.
68                let base = std::fs::canonicalize(&self.workdir).ok()?;
69                let (existing, tail) = existing_ancestor(path)?;
70                let full = std::fs::canonicalize(existing).ok()?.join(tail);
71                full.strip_prefix(&base).ok()?.to_path_buf()
72            }
73        };
74        let parts: Vec<String> = rest
75            .components()
76            .map(|part| part.as_os_str().to_string_lossy().into_owned())
77            .collect();
78        (!parts.is_empty()).then(|| parts.join("/"))
79    }
80
81    /// Whether the index holds `path` (it is tracked).
82    pub fn is_tracked(&self, path: &Path) -> Result<bool, CoreError> {
83        let Some(relative) = self.relative(path) else {
84            return Ok(false);
85        };
86        let index = self.repo.index().map_err(git_error)?;
87        Ok(index.get_path(Path::new(&relative), 0).is_some())
88    }
89
90    /// Whether the index holds `path` or any file below it (a folder with
91    /// tracked files).
92    pub fn tracks_any_under(&self, path: &Path) -> Result<bool, CoreError> {
93        let Some(relative) = self.relative(path) else {
94            return Ok(false);
95        };
96        let prefix = format!("{relative}/");
97        let index = self.repo.index().map_err(git_error)?;
98        Ok(index.iter().any(|entry| {
99            let tracked = String::from_utf8_lossy(&entry.path);
100            tracked == relative.as_str() || tracked.starts_with(&prefix)
101        }))
102    }
103
104    /// Whether the repository's ignore rules match `path`.
105    pub fn is_ignored(&self, path: &Path) -> Result<bool, CoreError> {
106        let Some(relative) = self.relative(path) else {
107            return Ok(false);
108        };
109        self.repo
110            .is_path_ignored(Path::new(&relative))
111            .map_err(git_error)
112    }
113
114    /// `info/exclude` of the repository. Linked work trees share the one in
115    /// the common directory.
116    pub fn exclude_file(&self) -> PathBuf {
117        self.commondir.join("info").join("exclude")
118    }
119
120    /// The files whose content [`ProjectRepo::is_tracked`] and
121    /// [`ProjectRepo::is_ignored`] of `path` depend on: the index,
122    /// `info/exclude` and the `.gitignore` of each folder from the work
123    /// tree root down to `path`'s (git's global excludes file aside).
124    pub fn state_files(&self, path: &Path) -> Vec<PathBuf> {
125        let gitdir = spelled_like(self.repo.path(), &self.workdir);
126        let mut files = vec![gitdir.join("index"), self.exclude_file()];
127        let mut dir = self.workdir.clone();
128        files.push(dir.join(".gitignore"));
129        if let Some(relative) = self.relative(path) {
130            let parts: Vec<&str> = relative.split('/').collect();
131            for part in &parts[..parts.len().saturating_sub(1)] {
132                dir.push(part);
133                files.push(dir.join(".gitignore"));
134            }
135        }
136        files
137    }
138
139    /// Hides `path` from git by appending `/<relative path>` to
140    /// `info/exclude` (creating it). Does nothing when the path is outside
141    /// the work tree, already ignored or already listed. Returns whether
142    /// the file was changed.
143    pub fn exclude(&self, fs: &dyn Fs, path: &Path) -> Result<bool, CoreError> {
144        let Some(relative) = self.relative(path) else {
145            return Ok(false);
146        };
147        if self.is_ignored(path)? {
148            return Ok(false);
149        }
150        let pattern = format!("/{relative}");
151        let file = self.exclude_file();
152        let io = |what: &str, at: &Path, err: std::io::Error| {
153            CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(at)
154        };
155        let mut text = if fs.exists(&file) {
156            fs.read_to_string(&file)
157                .map_err(|err| io("cannot read file", &file, err))?
158        } else {
159            String::new()
160        };
161        if text
162            .lines()
163            .any(|line| line.trim() == pattern || line.trim() == relative)
164        {
165            return Ok(false);
166        }
167        if !text.is_empty() && !text.ends_with('\n') {
168            text.push('\n');
169        }
170        text.push_str(&pattern);
171        text.push('\n');
172        crate::apply::write_atomic_project(fs, &file, text.as_bytes())?;
173        Ok(true)
174    }
175}
176
177/// `path`, an existing folder as git2 reports it, spelled from the deepest
178/// ancestor-or-self of `root` it lies under once both are resolved; as it
179/// is when it already shares a spelling with `root` or cannot be resolved.
180fn spelled_like(path: &Path, root: &Path) -> PathBuf {
181    if root.starts_with(path) || path.starts_with(root) {
182        return path.to_path_buf();
183    }
184    let Ok(real) = std::fs::canonicalize(path) else {
185        return path.to_path_buf();
186    };
187    for base in root.ancestors() {
188        let Ok(real_base) = std::fs::canonicalize(base) else {
189            continue;
190        };
191        if let Ok(rest) = real.strip_prefix(&real_base) {
192            return if rest.as_os_str().is_empty() {
193                base.to_path_buf()
194            } else {
195                base.join(rest)
196            };
197        }
198    }
199    path.to_path_buf()
200}
201
202/// The deepest existing ancestor-or-self of `path` and the rest below it.
203fn existing_ancestor(path: &Path) -> Option<(&Path, PathBuf)> {
204    let mut tail: Vec<&std::ffi::OsStr> = Vec::new();
205    let mut current = path;
206    loop {
207        if current.exists() {
208            let mut rest = PathBuf::new();
209            for part in tail.iter().rev() {
210                rest.push(part);
211            }
212            return Some((current, rest));
213        }
214        tail.push(current.file_name()?);
215        current = current.parent()?;
216    }
217}