Skip to main content

nibkeep_git/
lib.rs

1//! The person's own Git, run for the repositories in NibKeep's trees, with their settings and
2//! credentials: reading what a repository's remotes, branch and commit are, finding the work
3//! that only this computer holds, and cloning what other devices recorded, once the engine
4//! has said a clone may take it. The engine knows nothing of Git: `nib` and apps run
5//! it through this crate, alike ([technical design: trees]).
6//!
7//! [technical design: trees]: ../../../docs/Technical-design.md#15-trees
8
9use std::ffi::OsString;
10use std::path::Path;
11use std::process::{Command, Stdio};
12
13use nibkeep_node::{GitRepository, ToClone};
14
15/// Clears from a command of Git the variables that would make it work on another repository
16/// than the folder it is given, as a hook or an alias of Git that runs `nib` sets them.
17pub 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/// The person's Git: its program and the variables it runs with, apart from the
45/// environment, so that what reads with it may be handed on.
46#[derive(Clone, Debug)]
47pub struct Git {
48	program: OsString,
49	variables: Vec<(OsString, Option<OsString>)>,
50}
51
52impl Git {
53	/// The `git` that the system finds, with none of the variables that would point it
54	/// elsewhere.
55	#[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	/// The Git of a template: its program, and the variables it sets or takes away, as a
63	/// test sets them.
64	#[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	/// A command of it, to give arguments to.
76	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	/// Runs it in `folder` with `arguments`, reading nothing from the terminal, never
88	/// looking for a repository above `folder`, and taking no lock it need not, so that the
89	/// person's own Git is never in its way, and returns what it wrote, trimmed, if it
90	/// succeeded.
91	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	/// What Git says of the repositories at `paths` in the tree at `root`: their remotes,
111	/// branch, the remote the branch follows, and commit. One that Git cannot read is left
112	/// out, which leaves it as the tree records it.
113	#[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	/// What Git says of the repository in `folder`, at `path` in the tree: its own, never
122	/// one above it, with the remotes of its own settings, each at the address it fetches
123	/// from, its first.
124	#[must_use]
125	pub fn describe_one(&self, folder: &Path, path: &str) -> Option<GitRepository> {
126		// A folder that holds no repository of its own is left as it is.
127		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			// Git takes an address there too: only a remote's name is the upstream.
159			.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	/// The work that the repository in `folder` holds and its remotes lack: changes not
170	/// committed, commits not pushed, stashes, a pinned commit that it has and no remote
171	/// has, or no remote at all. A reference brings back only what a remote holds.
172	#[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		// A pinned commit this clone does not have is no work of this computer's.
207		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	/// The commit that the repository in `folder` has checked out, in full.
222	#[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	/// Whether `folder` holds a repository of its own: a `.git` folder in it, never a file
232	/// that points elsewhere, as a worktree's or a submodule's does, and Git takes `folder`
233	/// for the top of its working tree, never a folder above it.
234	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	/// Clones a repository into `folder`, empty and checked by the engine, as `to` says:
246	/// from its remote, with the address after `--` so that Git never reads it as an option,
247	/// no submodule, its other remotes added, and its branch checked out, at its pinned
248	/// commit if it has one. Only a repository the engine did not refuse comes here. Git
249	/// speaks English here, so that what it says can be told apart.
250	///
251	/// # Errors
252	///
253	/// Returns what Git said, if a step failed.
254	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
288/// Runs a command of Git, its prompts on the terminal, as for credentials, in English, and
289/// returns what it said on failure.
290fn 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}