Repository navigation
Expand file tree
/
Copy pathgit.rs
More file actions
411 lines (381 loc) · 13.6 KB
/
Copy pathgit.rs
File metadata and controls
411 lines (381 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Running Git.
//!
//! Every repository operation goes through the user's own `git` binary, so the
//! semantics are exactly those of the Git version installed, whatever it is.
//! The [`Repo`] value knows where the repository lives and runs each command
//! with the environment scrubbed of the variables Git sets for hooks, with our
//! own hooks disabled, and with `GIT_UNDO_INTERNAL=1` so the installed hook
//! scripts know to stay quiet.
use anyhow::{anyhow, bail, Context, Result};
use std::ffi::{OsStr, OsString};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
/// Variables Git exports to hooks and subprocesses. Any of them left in our
/// environment would point our own `git` calls at the wrong index or
/// repository, so they are removed before every call.
const SCRUBBED: &[&str] = &[
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_INDEX_VERSION",
"GIT_PREFIX",
"GIT_COMMON_DIR",
"GIT_NAMESPACE",
"GIT_IMPLICIT_WORK_TREE",
"GIT_QUARANTINE_PATH",
"GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_REFLOG_ACTION",
];
/// The environment variable the hook scripts check before scheduling a snapshot.
pub const INTERNAL_ENV: &str = "GIT_UNDO_INTERNAL";
/// When set, child `git` processes are started without a console window.
/// The detached hook worker has no console of its own, and on Windows each
/// console program it starts would otherwise get a brand-new window.
pub static QUIET_CHILDREN: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
#[derive(Clone, Debug)]
pub struct Repo {
/// This worktree's git directory (`.git`, or `.git/worktrees/<name>`).
pub git_dir: PathBuf,
/// The git directory shared by every worktree of the repository.
pub common_dir: PathBuf,
/// The working tree, or `None` in a bare repository.
pub work_tree: Option<PathBuf>,
git: OsString,
}
impl Repo {
/// Find the repository that contains `start` (the current directory when
/// `None`), honouring `GIT_DIR` and `GIT_WORK_TREE` the way Git does.
pub fn discover(start: Option<&Path>) -> Result<Repo> {
let git = git_binary();
let mut cmd = git_command(&git);
if let Some(dir) = start {
cmd.current_dir(dir);
}
cmd.env_remove("GIT_INDEX_FILE").env_remove("GIT_PREFIX");
cmd.args([
"rev-parse",
"--path-format=absolute",
"--git-dir",
"--git-common-dir",
"--is-bare-repository",
]);
let out = cmd
.stdin(Stdio::null())
.output()
.context("could not run git; is it installed and on PATH?")?;
if !out.status.success() {
bail!("not a git repository{}", suffix(&out.stderr));
}
let text = String::from_utf8_lossy(&out.stdout);
let mut lines = text.lines();
let git_dir = PathBuf::from(lines.next().unwrap_or_default());
let common_dir = PathBuf::from(lines.next().unwrap_or_default());
let bare = lines.next().unwrap_or_default().trim() == "true";
let work_tree = if bare {
None
} else {
let mut cmd = git_command(&git);
if let Some(dir) = start {
cmd.current_dir(dir);
}
cmd.env_remove("GIT_INDEX_FILE").env_remove("GIT_PREFIX");
cmd.args(["rev-parse", "--path-format=absolute", "--show-toplevel"]);
let out = cmd.stdin(Stdio::null()).output()?;
if out.status.success() {
let top = String::from_utf8_lossy(&out.stdout).trim().to_string();
if top.is_empty() {
None
} else {
Some(PathBuf::from(top))
}
} else {
None
}
};
Ok(Repo {
git_dir,
common_dir,
work_tree,
git,
})
}
/// Open a repository whose location is already known (the background
/// worker is started this way, so it never depends on the hook's
/// environment).
pub fn open(git_dir: &Path, work_tree: Option<&Path>) -> Result<Repo> {
let git = git_binary();
let out = git_command(&git)
.arg("--git-dir")
.arg(git_dir)
.args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
.stdin(Stdio::null())
.output()?;
if !out.status.success() {
bail!(
"{} is not a git directory{}",
git_dir.display(),
suffix(&out.stderr)
);
}
let common_dir = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
Ok(Repo {
git_dir: git_dir.to_path_buf(),
common_dir,
work_tree: work_tree.map(Path::to_path_buf),
git,
})
}
/// True when this is a linked worktree rather than the main one.
pub fn is_linked_worktree(&self) -> bool {
normalise(&self.git_dir) != normalise(&self.common_dir)
}
/// The name Git gave this linked worktree (`.git/worktrees/<name>`).
pub fn worktree_name(&self) -> Option<String> {
if !self.is_linked_worktree() {
return None;
}
self.git_dir
.file_name()
.map(|n| n.to_string_lossy().into_owned())
}
/// Where git-undo keeps its own scratch files for this worktree.
pub fn state_dir(&self) -> PathBuf {
self.git_dir.join("undo")
}
/// A `git` command pointed at this repository with a clean environment
/// and none of the configuration overrides [`cmd`] adds.
fn base(&self) -> Command {
let mut c = git_command(&self.git);
for key in SCRUBBED {
c.env_remove(key);
}
c.env(INTERNAL_ENV, "1");
c.arg("--git-dir").arg(&self.git_dir);
match &self.work_tree {
Some(wt) => {
c.arg("--work-tree").arg(wt);
c.current_dir(wt);
}
None => {
c.current_dir(&self.git_dir);
}
}
c.stdin(Stdio::null());
c
}
/// A `git` command pointed at this repository, with hooks and signing
/// switched off so our own plumbing never triggers either.
pub fn cmd(&self) -> Command {
let mut c = self.base();
let no_hooks = self.state_dir().join("no-hooks");
c.arg("-c")
.arg(format!("core.hooksPath={}", no_hooks.display()));
c.args(["-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false"]);
c.args([
"-c",
"advice.addEmbeddedRepo=false",
"-c",
"advice.addIgnoredFile=false",
]);
c
}
/// Run `git <args>` and return stdout without its trailing newline; fail
/// on a non-zero exit. Only newlines are trimmed: tab-separated output
/// may legitimately end in empty fields.
pub fn run<I, S>(&self, args: I) -> Result<String>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let out = self.exec(self.cmd().args(args), None, true)?;
Ok(String::from_utf8_lossy(&out.stdout)
.trim_end_matches(['\n', '\r'])
.to_string())
}
/// Run `git <args>`, feeding `input` on stdin, and return raw stdout.
pub fn run_bytes<I, S>(&self, args: I, input: Option<&[u8]>) -> Result<Vec<u8>>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
Ok(self.exec(self.cmd().args(args), input, true)?.stdout)
}
/// Run `git <args>` with an alternate index file.
pub fn run_index<I, S>(&self, index: &Path, args: I, input: Option<&[u8]>) -> Result<Vec<u8>>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut c = self.cmd();
c.env("GIT_INDEX_FILE", index);
Ok(self.exec(c.args(args), input, true)?.stdout)
}
/// Run `git <args>` and hand back the raw output, whatever the exit code.
pub fn try_run<I, S>(&self, args: I, input: Option<&[u8]>) -> Result<Output>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
self.exec(self.cmd().args(args), input, false)
}
/// Same as [`try_run`] with an alternate index file.
pub fn try_run_index<I, S>(&self, index: &Path, args: I, input: Option<&[u8]>) -> Result<Output>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut c = self.cmd();
c.env("GIT_INDEX_FILE", index);
self.exec(c.args(args), input, false)
}
/// Run a prepared command, optionally feeding stdin, optionally checking
/// the exit status.
pub fn exec(&self, cmd: &mut Command, input: Option<&[u8]>, check: bool) -> Result<Output> {
let label = describe(cmd);
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let out = match input {
None => cmd.output(),
Some(bytes) => {
cmd.stdin(Stdio::piped());
let mut child = cmd.spawn()?;
let mut stdin = child.stdin.take().expect("piped stdin");
let bytes = bytes.to_vec();
// Write on another thread so a chatty command can never
// deadlock against a full stdout pipe.
let writer = std::thread::spawn(move || {
let _ = stdin.write_all(&bytes);
});
let out = child.wait_with_output();
let _ = writer.join();
out
}
}
.with_context(|| format!("could not start {label}"))?;
if check && !out.status.success() {
return Err(anyhow!(
"{label} failed{}{}",
match out.status.code() {
Some(c) => format!(" (exit {c})"),
None => String::new(),
},
suffix(&out.stderr)
));
}
Ok(out)
}
/// `git rev-parse --git-path <name>` for each name, in order.
pub fn git_paths(&self, names: &[&str]) -> Result<Vec<PathBuf>> {
let mut args: Vec<&str> = vec!["rev-parse", "--path-format=absolute"];
for n in names {
args.push("--git-path");
args.push(n);
}
// Without the hooksPath override, or "hooks" would resolve to our own
// do-nothing directory.
let out = self.exec(self.base().args(args), None, true)?;
Ok(String::from_utf8_lossy(&out.stdout)
.lines()
.map(PathBuf::from)
.collect())
}
/// `git rev-parse --git-path <name>`.
pub fn git_path(&self, name: &str) -> Result<PathBuf> {
Ok(self
.git_paths(&[name])?
.into_iter()
.next()
.unwrap_or_else(|| self.git_dir.join(name)))
}
/// A configuration value, or `None` when unset.
pub fn config(&self, key: &str) -> Result<Option<String>> {
let out = self.exec(self.base().args(["config", "--get", key]), None, false)?;
if out.status.success() {
Ok(Some(
String::from_utf8_lossy(&out.stdout).trim().to_string(),
))
} else if out.status.code() == Some(1) {
Ok(None)
} else {
Err(anyhow!(
"git config --get {key} failed{}",
suffix(&out.stderr)
))
}
}
/// A boolean configuration value with a default.
pub fn config_bool(&self, key: &str, default: bool) -> bool {
match self.exec(
self.base().args(["config", "--type=bool", "--get", key]),
None,
false,
) {
Ok(out) if out.status.success() => {
String::from_utf8_lossy(&out.stdout).trim() == "true"
}
_ => default,
}
}
/// An integer configuration value with a default.
pub fn config_u64(&self, key: &str, default: u64) -> u64 {
self.config(key)
.ok()
.flatten()
.and_then(|v| v.trim().parse().ok())
.unwrap_or(default)
}
/// A lock file that serialises captures within one worktree.
pub fn state_file(&self, name: &str) -> PathBuf {
self.state_dir().join(name)
}
}
fn git_binary() -> OsString {
std::env::var_os("GIT_UNDO_GIT").unwrap_or_else(|| OsString::from("git"))
}
/// Every `git` process we start goes through here, so the no-window flag
/// applies to all of them, including repository discovery.
fn git_command(git: &OsStr) -> Command {
#[allow(unused_mut)]
let mut c = Command::new(git);
#[cfg(windows)]
if QUIET_CHILDREN.load(std::sync::atomic::Ordering::Relaxed) {
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
c.creation_flags(CREATE_NO_WINDOW);
}
c
}
fn normalise(p: &Path) -> String {
p.to_string_lossy()
.replace('\\', "/")
.trim_end_matches('/')
.to_lowercase()
}
fn describe(cmd: &Command) -> String {
let mut parts: Vec<String> = vec!["git".into()];
let mut skip = false;
for a in cmd.get_args() {
let s = a.to_string_lossy();
// Hide the boilerplate we add to every call.
if skip {
skip = false;
continue;
}
if s == "--git-dir" || s == "--work-tree" || s == "-c" {
skip = true;
continue;
}
parts.push(s.into_owned());
}
parts.join(" ")
}
fn suffix(stderr: &[u8]) -> String {
let text = String::from_utf8_lossy(stderr).trim().to_string();
if text.is_empty() {
String::new()
} else {
format!(": {text}")
}
}