surjection_core/layering/
git.rs1use std::path::{Path, PathBuf};
7
8use crate::error::{CoreError, ErrorCode};
9use crate::fs::Fs;
10
11pub 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 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 pub fn workdir(&self) -> &Path {
57 &self.workdir
58 }
59
60 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 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 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 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 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 pub fn exclude_file(&self) -> PathBuf {
117 self.commondir.join("info").join("exclude")
118 }
119
120 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 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
177fn 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
202fn 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}