1use std::ffi::OsString;
10use std::path::Path;
11use std::process::{Command, Stdio};
12
13use nibkeep_node::{GitRepository, ToClone};
14
15pub fn clear_variables(git: &mut Command) {
18 for variable in [
19 "GIT_DIR",
20 "GIT_WORK_TREE",
21 "GIT_INDEX_FILE",
22 "GIT_OBJECT_DIRECTORY",
23 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
24 "GIT_COMMON_DIR",
25 "GIT_NAMESPACE",
26 "GIT_PREFIX",
27 "GIT_CEILING_DIRECTORIES",
28 "GIT_DISCOVERY_ACROSS_FILESYSTEM",
29 "GIT_CONFIG",
30 "GIT_CONFIG_PARAMETERS",
31 "GIT_CONFIG_COUNT",
32 "GIT_SHALLOW_FILE",
33 "GIT_GRAFT_FILE",
34 "GIT_REPLACE_REF_BASE",
35 "GIT_NO_REPLACE_OBJECTS",
36 "GIT_IMPLICIT_WORK_TREE",
37 "GIT_QUARANTINE_PATH",
38 "GIT_INTERNAL_SUPER_PREFIX",
39 ] {
40 git.env_remove(variable);
41 }
42}
43
44#[derive(Clone, Debug)]
47pub struct Git {
48 program: OsString,
49 variables: Vec<(OsString, Option<OsString>)>,
50}
51
52impl Git {
53 #[must_use]
56 pub fn person() -> Self {
57 let mut git = Command::new("git");
58 clear_variables(&mut git);
59 Self::from_template(&git)
60 }
61
62 #[must_use]
65 pub fn from_template(template: &Command) -> Self {
66 Self {
67 program: template.get_program().to_owned(),
68 variables: template
69 .get_envs()
70 .map(|(key, value)| (key.to_owned(), value.map(ToOwned::to_owned)))
71 .collect(),
72 }
73 }
74
75 fn command(&self) -> Command {
77 let mut command = Command::new(&self.program);
78 for (key, value) in &self.variables {
79 match value {
80 Some(value) => command.env(key, value),
81 None => command.env_remove(key),
82 };
83 }
84 command
85 }
86
87 fn run(&self, folder: &Path, arguments: &[&str]) -> Option<String> {
92 let mut git = self.command();
93 git.arg("-C").arg(folder).args(arguments);
94 if let Some(parent) = folder.parent() {
95 git.env("GIT_CEILING_DIRECTORIES", parent);
96 }
97 let output = git
98 .env("GIT_OPTIONAL_LOCKS", "0")
99 .env("GIT_TERMINAL_PROMPT", "0")
100 .stdin(Stdio::null())
101 .stderr(Stdio::null())
102 .output()
103 .ok()?;
104 output
105 .status
106 .success()
107 .then(|| String::from_utf8_lossy(&output.stdout).trim().to_owned())
108 }
109
110 #[must_use]
114 pub fn describe(&self, root: &Path, paths: &[String]) -> Vec<GitRepository> {
115 paths
116 .iter()
117 .filter_map(|path| self.describe_one(&root.join(path), path))
118 .collect()
119 }
120
121 #[must_use]
125 pub fn describe_one(&self, folder: &Path, path: &str) -> Option<GitRepository> {
126 if !self.holds_own(folder) {
128 return None;
129 }
130 let mut remotes: Vec<(String, String)> = Vec::new();
131 let listed = self
132 .run(
133 folder,
134 &["config", "--local", "--get-regexp", r"^remote\..*\.url$"],
135 )
136 .unwrap_or_default();
137 for line in listed.lines() {
138 if let Some((key, address)) = line.split_once(' ')
139 && let Some(name) = key
140 .strip_prefix("remote.")
141 .and_then(|rest| rest.strip_suffix(".url"))
142 && !remotes.iter().any(|(known, _)| known == name)
143 {
144 remotes.push((name.to_owned(), address.to_owned()));
145 }
146 }
147 let branch = self
148 .run(folder, &["symbolic-ref", "--quiet", "--short", "HEAD"])
149 .filter(|branch| !branch.is_empty());
150 let upstream = branch
151 .as_ref()
152 .and_then(|branch| {
153 self.run(
154 folder,
155 &["config", "--get", &format!("branch.{branch}.remote")],
156 )
157 })
158 .filter(|remote| remotes.iter().any(|(name, _)| name == remote));
160 Some(GitRepository {
161 path: path.to_owned(),
162 remotes,
163 branch,
164 upstream,
165 commit: self.head(folder),
166 })
167 }
168
169 #[must_use]
173 pub fn work_only_here(&self, folder: &Path, pinned: Option<&str>) -> Vec<String> {
174 let mut work = Vec::new();
175 if !self.holds_own(folder) {
176 return work;
177 }
178 let has_remote = self
179 .run(folder, &["remote"])
180 .is_some_and(|remotes| !remotes.is_empty());
181 if self
182 .run(folder, &["status", "--porcelain"])
183 .is_some_and(|changes| !changes.is_empty())
184 {
185 work.push("changes not committed".to_owned());
186 }
187 if !has_remote {
188 work.push("no remote at all".to_owned());
189 } else if let Some(count) = self
190 .run(
191 folder,
192 &["rev-list", "--count", "--branches", "--not", "--remotes"],
193 )
194 .and_then(|count| count.parse::<u64>().ok())
195 .filter(|count| *count > 0)
196 {
197 let commits = if count == 1 { "commit" } else { "commits" };
198 work.push(format!("{count} {commits} not pushed"));
199 }
200 if self
201 .run(folder, &["stash", "list"])
202 .is_some_and(|stashes| !stashes.is_empty())
203 {
204 work.push("stashes".to_owned());
205 }
206 if let Some(pinned) = pinned
208 && has_remote
209 && self
210 .run(folder, &["cat-file", "-e", &format!("{pinned}^{{commit}}")])
211 .is_some()
212 && self
213 .run(folder, &["branch", "--remotes", "--contains", pinned])
214 .is_none_or(|branches| branches.is_empty())
215 {
216 work.push("the pinned commit, which no remote has".to_owned());
217 }
218 work
219 }
220
221 #[must_use]
223 pub fn head(&self, folder: &Path) -> Option<String> {
224 if !self.holds_own(folder) {
225 return None;
226 }
227 self.run(folder, &["rev-parse", "--verify", "--quiet", "HEAD"])
228 .filter(|commit| !commit.is_empty())
229 }
230
231 fn holds_own(&self, folder: &Path) -> bool {
235 if !std::fs::symlink_metadata(folder.join(".git")).is_ok_and(|metadata| metadata.is_dir()) {
236 return false;
237 }
238 let Some(top) = self.run(folder, &["rev-parse", "--show-toplevel"]) else {
239 return false;
240 };
241 let same = |path: &Path| std::fs::canonicalize(path).ok();
242 same(Path::new(&top)).is_some_and(|top| Some(top) == same(folder))
243 }
244
245 pub fn clone(&self, to: &ToClone, folder: &Path) -> Result<(), String> {
255 let mut cloning = self.command();
256 cloning
257 .arg("clone")
258 .arg("--no-recurse-submodules")
259 .arg(format!("--origin={}", to.remote));
260 if let Some(branch) = &to.branch {
261 cloning.arg(format!("--branch={branch}"));
262 }
263 cloning.arg("--").arg(&to.address).arg(folder);
264 checked(cloning)?;
265 for (name, address) in &to.others {
266 let mut adding = self.command();
267 adding
268 .arg("-C")
269 .arg(folder)
270 .args(["remote", "add", "--"])
271 .arg(name)
272 .arg(address);
273 checked(adding)?;
274 }
275 if let Some(pinned) = &to.pinned {
276 let mut resetting = self.command();
277 resetting
278 .arg("-C")
279 .arg(folder)
280 .args(["reset", "--hard", "--quiet"])
281 .arg(pinned);
282 checked(resetting)?;
283 }
284 Ok(())
285 }
286}
287
288fn checked(mut command: Command) -> Result<(), String> {
291 let output = command
292 .env("LC_ALL", "C")
293 .env_remove("LANGUAGE")
294 .stdout(Stdio::null())
295 .output()
296 .map_err(|error| format!("Git could not run: {error}"))?;
297 if output.status.success() {
298 Ok(())
299 } else {
300 let said = String::from_utf8_lossy(&output.stderr).trim().to_owned();
301 Err(if said.is_empty() {
302 format!("Git failed: {}", output.status)
303 } else {
304 said
305 })
306 }
307}