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
|
use std::collections::BTreeMap;
use std::path::Path;
use std::process::{Command, Output, Stdio};
use crate::error::{Error, Missing, Result};
pub fn git(cwd: Option<&Path>, args: &[&str]) -> Result<String> {
let mut cmd = Command::new("git");
if let Some(c) = cwd {
cmd.current_dir(c);
}
cmd.args(args);
cmd.env("GIT_TERMINAL_PROMPT", "0");
cmd.env("GIT_CONFIG_NOSYSTEM", "1");
cmd.env("LC_ALL", "C");
let out = cmd.output().map_err(|e| Error::git(format!("git {args:?}: {e}")))?;
ok(out, args)
}
fn ok(out: Output, args: &[&str]) -> Result<String> {
if !out.status.success() {
return Err(Error::git(format!(
"git {args:?} exited {}: {}",
out.status,
String::from_utf8_lossy(&out.stderr).trim()
)));
}
Ok(String::from_utf8_lossy(&out.stdout).to_string())
}
pub fn git_ok(cwd: Option<&Path>, args: &[&str]) -> bool {
git(cwd, args).is_ok()
}
pub fn ls_remote_head(url: &str) -> Result<Option<String>> {
match git(None, &["ls-remote", url, "HEAD"]) {
Ok(out) => {
let sha = out
.split_whitespace()
.next()
.filter(|s| s.len() >= 7)
.map(|s| s.to_string());
Ok(sha)
}
Err(e) if is_missing_remote(&e) => Ok(None),
Err(e) => Err(e),
}
}
pub fn ls_remote_heads(url: &str) -> Result<Vec<(String, String)>> {
let out = git(None, &["ls-remote", "--heads", url])?;
let mut v = Vec::new();
for line in out.lines() {
let mut it = line.split_whitespace();
if let (Some(sha), Some(name)) = (it.next(), it.next()) {
v.push((name.to_string(), sha.to_string()));
}
}
Ok(v)
}
pub fn ls_remote_ref(url: &str, refname: &str) -> Result<Option<String>> {
match git(None, &["ls-remote", url, refname]) {
Ok(out) => Ok(out
.lines()
.next()
.and_then(|l| l.split_whitespace().next())
.map(|s| s.to_string())),
Err(e) if is_missing_remote(&e) => Ok(None),
Err(e) => Err(e),
}
}
fn is_missing_remote(e: &Error) -> bool {
let s = e.to_string();
s.contains("not found")
|| s.contains("does not appear to be a git repository")
|| s.contains("Repository not found")
|| s.contains("404")
}
pub fn clone(url: &str, dest: &Path) -> Result<()> {
if dest.exists() {
return Ok(());
}
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
git(None, &["clone", "--quiet", "--mirror", url, &dest.display().to_string()])?;
Ok(())
}
pub fn clone_bare(url: &str, dest: &Path) -> Result<()> {
if dest.exists() {
return Ok(());
}
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
git(
None,
&["clone", "--quiet", "--bare", url, &dest.display().to_string()],
)?;
Ok(())
}
pub fn fetch_head(mirror: &Path) -> Result<String> {
git(Some(mirror), &["fetch", "--quiet", "--no-prune", "origin"])?;
head(mirror)
}
pub fn head(mirror: &Path) -> Result<String> {
Ok(git(Some(mirror), &["rev-parse", "HEAD"])?.trim().to_string())
}
pub fn has_commit(mirror: &Path, commit: &str) -> bool {
git_ok(Some(mirror), &["cat-file", "-e", &format!("{commit}^{{commit}}")])
}
pub fn ls_tree(mirror: &Path, commit: &str) -> Result<Vec<(String, String)>> {
let out = git(Some(mirror), &["ls-tree", "-r", commit])?;
let mut v = Vec::new();
for line in out.lines() {
if let Some(rest) = line.strip_prefix("100644 blob ").or_else(|| line.strip_prefix("100755 blob ")) {
if let Some((sha, path)) = rest.split_once('\t') {
v.push((path.to_string(), sha.to_string()));
}
}
}
Ok(v)
}
pub fn read_blob(mirror: &Path, commit: &str, path: &str) -> Result<Vec<u8>> {
let spec = format!("{commit}:{path}");
let out = Command::new("git")
.current_dir(mirror)
.env("GIT_TERMINAL_PROMPT", "0")
.env("GIT_CONFIG_NOSYSTEM", "1")
.args(["cat-file", "blob", &spec])
.output()
.map_err(|e| Error::git(e.to_string()))?;
if !out.status.success() {
return Err(Error::not_found(Missing::MirrorPath(spec)));
}
Ok(out.stdout)
}
pub fn cat_file_batch(mirror: &Path, oids: &[String]) -> Result<BTreeMap<String, Vec<u8>>> {
let mut out = BTreeMap::new();
if oids.is_empty() {
return Ok(out);
}
let mut child = Command::new("git")
.current_dir(mirror)
.env("GIT_TERMINAL_PROMPT", "0")
.env("GIT_CONFIG_NOSYSTEM", "1")
.env("LC_ALL", "C")
.args(["cat-file", "--batch"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| Error::git(format!("git cat-file --batch: {e}")))?;
// The ids go in on their own thread: git streams blobs back as it reads the
// list, so a tree big enough to fill the pipe buffer would deadlock a
// write-everything-then-read-anything version here.
let mut stdin = child.stdin.take().expect("piped stdin");
let input = oids.join("\n") + "\n";
let writer = std::thread::spawn(move || {
use std::io::Write;
let _ = stdin.write_all(input.as_bytes());
});
use std::io::{BufRead, BufReader, Read};
let mut stderr = child.stderr.take().expect("piped stderr");
let mut stdout = BufReader::new(child.stdout.take().expect("piped stdout"));
loop {
let mut header = String::new();
if stdout.read_line(&mut header)? == 0 {
break;
}
let mut fields = header.trim_end_matches('\n').split(' ');
let id = fields.next().unwrap_or_default().to_string();
match (fields.next(), fields.next().and_then(|s| s.parse().ok())) {
(Some("missing"), _) => continue,
(Some("blob"), Some(size)) => {
let mut body = vec![0u8; size];
stdout.read_exact(&mut body)?;
// `--batch` puts an LF after every body, even an empty one.
let mut newline = [0u8; 1];
stdout.read_exact(&mut newline)?;
out.insert(id, body);
}
_ => {
return Err(Error::git(format!(
"unreadable cat-file header {:?}",
header.trim_end()
)))
}
}
}
let _ = writer.join();
let status = child.wait().map_err(|e| Error::git(e.to_string()))?;
// A missing object is a line in the output, not a non-zero exit; a non-zero
// exit means the process itself failed, which is not the caller's problem to
// distinguish from an absent blob.
if !status.success() {
let mut detail = Vec::new();
stderr.read_to_end(&mut detail)?;
return Err(Error::git(format!(
"git cat-file --batch exited {status}: {}",
String::from_utf8_lossy(&detail).trim()
)));
}
Ok(out)
}
pub fn materialize(mirror: &Path, commit: &str, dest: &Path) -> Result<()> {
std::fs::create_dir_all(dest)?;
let out = Command::new("git")
.current_dir(mirror)
.env("GIT_TERMINAL_PROMPT", "0")
.env("GIT_CONFIG_NOSYSTEM", "1")
.args(["archive", "--format=tar", commit])
.output()
.map_err(|e| Error::git(e.to_string()))?;
if !out.status.success() {
return Err(Error::git(format!(
"git archive {commit}: {}",
String::from_utf8_lossy(&out.stderr).trim()
)));
}
let mut ar = tar::Archive::new(std::io::Cursor::new(&out.stdout));
ar.set_preserve_permissions(true);
ar.unpack(dest)
.map_err(|e| Error::git(format!("unpack {commit}: {e}")))?;
Ok(())
}
pub fn log_oneline(mirror: &Path, range: &str) -> Result<Vec<String>> {
let out = git(Some(mirror), &["log", "--oneline", range])?;
Ok(out.lines().map(|l| l.to_string()).collect())
}
pub fn diff(mirror: &Path, range: &str, paths: &[&str]) -> Result<String> {
let mut args: Vec<&str> = vec!["diff", "--no-color", range, "--"];
args.extend(paths);
git(Some(mirror), &args)
}
pub fn count_commits(mirror: &Path, range: &str) -> Result<usize> {
let out = git(Some(mirror), &["rev-list", "--count", range])?;
Ok(out.trim().parse().unwrap_or(0))
}
pub fn clone_source(url: &str, dest: &Path, depth: Option<usize>, branch: Option<&str>) -> Result<()> {
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
let mut args: Vec<String> = vec!["clone".into(), "--quiet".into()];
if let Some(d) = depth {
args.push(format!("--depth={d}"));
}
if let Some(b) = branch {
args.push(format!("--branch={b}"));
}
args.push(url.to_string());
args.push(dest.display().to_string());
let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
git(None, &refs)?;
Ok(())
}
pub fn fetch_and_head(repo: &Path) -> Result<String> {
git(Some(repo), &["fetch", "--quiet", "--no-prune", "origin"])?;
head(repo)
}
|