-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_client.rs
More file actions
340 lines (291 loc) · 11.8 KB
/
git_client.rs
File metadata and controls
340 lines (291 loc) · 11.8 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
use std::path::Path;
use std::process::Command;
use super::PresetError;
/// Whether a remote ref is a tag or a branch.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefKind {
Tag,
Branch,
}
/// A remote ref returned by `ls-remote`, with its name and kind.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteRef {
pub name: String,
pub kind: RefKind,
}
/// Abstraction for git command execution.
///
/// Enables testing with `MockGitClient` while `ProcessGitClient` runs real git processes.
pub trait GitClient {
/// Run `git clone --depth 1 [--branch <branch>] <url> .` into `dest`.
fn clone_shallow(
&self,
url: &str,
dest: &Path,
branch: Option<&str>,
) -> Result<(), PresetError>;
/// Run `git fetch --depth 1 origin [<branch>]` in `repo_dir`.
fn fetch(&self, repo_dir: &Path, branch: Option<&str>) -> Result<(), PresetError>;
/// Run `git checkout <git_ref>` in `repo_dir`.
fn checkout(&self, repo_dir: &Path, git_ref: &str) -> Result<(), PresetError>;
/// Run `git rev-parse HEAD` in `repo_dir` and return the commit SHA.
fn rev_parse_head(&self, repo_dir: &Path) -> Result<String, PresetError>;
/// Run `git ls-remote --tags --heads --refs <url>` and return remote refs
/// with their kind (tag or branch).
fn ls_remote_refs(&self, url: &str) -> Result<Vec<RemoteRef>, PresetError>;
}
/// Strip credentials from a URL for safe use in error messages.
///
/// Replaces `user:pass@` or `user@` in the authority component with `***@`.
fn sanitize_url(url: &str) -> String {
if let Some(scheme_end) = url.find("://") {
let authority_start = scheme_end + 3;
let rest = &url[authority_start..];
// Find the end of the authority (first `/` after `://`)
let authority_end = rest.find('/').unwrap_or(rest.len());
let authority = &rest[..authority_end];
if let Some(at_pos) = authority.rfind('@') {
// There are credentials; replace them with `***`
return format!("{}***@{}", &url[..authority_start], &rest[at_pos + 1..]);
}
}
url.to_string()
}
/// Real git client that spawns `git` subprocesses.
///
/// Sanitizes environment by removing `GIT_DIR` and `GIT_INDEX_FILE` so that
/// git operations work correctly inside worktree environments (lefthook approach).
pub struct ProcessGitClient;
impl ProcessGitClient {
fn git_command(working_dir: &Path) -> Command {
let mut cmd = Command::new("git");
cmd.current_dir(working_dir);
// Remove env vars that interfere with git in worktree contexts
cmd.env_remove("GIT_DIR");
cmd.env_remove("GIT_INDEX_FILE");
cmd
}
fn run_git(cmd: &mut Command, context: &str) -> Result<(), PresetError> {
let output = cmd.output().map_err(|e| PresetError::GitClone {
reference: context.to_string(),
message: format!("failed to execute git: {e}"),
})?;
if output.status.success() {
Ok(())
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
Err(PresetError::GitClone {
reference: context.to_string(),
message: stderr.trim().to_string(),
})
}
}
}
impl GitClient for ProcessGitClient {
fn clone_shallow(
&self,
url: &str,
dest: &Path,
branch: Option<&str>,
) -> Result<(), PresetError> {
let parent = dest.parent().ok_or_else(|| PresetError::GitClone {
reference: sanitize_url(url),
message: "destination has no parent directory".to_string(),
})?;
let mut cmd = Self::git_command(parent);
cmd.args(["clone", "--quiet", "--depth", "1"]);
if let Some(branch) = branch {
cmd.args(["--branch", branch]);
}
// `--` separates options from positional arguments to prevent
// argument injection via crafted URL strings.
cmd.arg("--");
cmd.arg(url);
cmd.arg(dest);
Self::run_git(&mut cmd, &sanitize_url(url))
}
fn fetch(&self, repo_dir: &Path, branch: Option<&str>) -> Result<(), PresetError> {
let mut cmd = Self::git_command(repo_dir);
cmd.args(["fetch", "--quiet", "--depth", "1", "origin"]);
if let Some(branch) = branch {
// `--` prevents the branch string from being interpreted as an
// option (e.g., `--upload-pack=...`) by git fetch.
cmd.arg("--");
cmd.arg(branch);
}
Self::run_git(&mut cmd, &repo_dir.display().to_string())
}
fn checkout(&self, repo_dir: &Path, git_ref: &str) -> Result<(), PresetError> {
let mut cmd = Self::git_command(repo_dir);
// Place `git_ref` before `--` so it is interpreted as a tree-ish,
// not a pathspec. The trailing `--` prevents ambiguity if a file
// happens to share the same name as the ref.
cmd.args(["checkout", "--quiet", git_ref, "--"]);
Self::run_git(&mut cmd, git_ref)
}
fn rev_parse_head(&self, repo_dir: &Path) -> Result<String, PresetError> {
let mut cmd = Self::git_command(repo_dir);
cmd.args(["rev-parse", "HEAD"]);
let output = cmd.output().map_err(|e| PresetError::GitClone {
reference: repo_dir.display().to_string(),
message: format!("failed to execute git rev-parse: {e}"),
})?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
Err(PresetError::GitClone {
reference: repo_dir.display().to_string(),
message: format!("git rev-parse HEAD failed: {}", stderr.trim()),
})
}
}
fn ls_remote_refs(&self, url: &str) -> Result<Vec<RemoteRef>, PresetError> {
let mut cmd = Command::new("git");
cmd.env_remove("GIT_DIR");
cmd.env_remove("GIT_INDEX_FILE");
// --tags --heads: list both tags and branches; --refs excludes peeled refs (^{})
cmd.args(["ls-remote", "--tags", "--heads", "--refs", "--", url]);
let output = cmd.output().map_err(|e| PresetError::GitClone {
reference: sanitize_url(url),
message: format!("failed to execute git ls-remote: {e}"),
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(PresetError::GitClone {
reference: sanitize_url(url),
message: format!("git ls-remote failed: {}", stderr.trim()),
});
}
// Output format: "<sha>\trefs/tags/<name>" or "<sha>\trefs/heads/<name>"
let stdout = String::from_utf8_lossy(&output.stdout);
let refs = stdout
.lines()
.filter_map(|line| {
let (_sha, refname) = line.split_once('\t')?;
if let Some(name) = refname.strip_prefix("refs/tags/") {
Some(RemoteRef {
name: name.to_string(),
kind: RefKind::Tag,
})
} else {
refname.strip_prefix("refs/heads/").map(|name| RemoteRef {
name: name.to_string(),
kind: RefKind::Branch,
})
}
})
.collect();
Ok(refs)
}
}
#[cfg(test)]
pub mod mock {
use std::cell::RefCell;
use std::collections::VecDeque;
use std::path::Path;
use super::{GitClient, PresetError, RemoteRef};
/// Records of calls made to MockGitClient methods.
#[derive(Debug, Clone)]
pub enum GitCall {
CloneShallow { branch: Option<String> },
Fetch,
Checkout { git_ref: String },
RevParseHead,
LsRemoteRefs { url: String },
}
/// Test double for `GitClient` that returns pre-configured results.
pub struct MockGitClient {
clone_results: RefCell<VecDeque<Result<(), PresetError>>>,
fetch_results: RefCell<VecDeque<Result<(), PresetError>>>,
checkout_results: RefCell<VecDeque<Result<(), PresetError>>>,
rev_parse_results: RefCell<VecDeque<Result<String, PresetError>>>,
ls_remote_refs_results: RefCell<VecDeque<Result<Vec<RemoteRef>, PresetError>>>,
pub calls: RefCell<Vec<GitCall>>,
}
impl Default for MockGitClient {
fn default() -> Self {
Self::new()
}
}
impl MockGitClient {
pub fn new() -> Self {
Self {
clone_results: RefCell::new(VecDeque::new()),
fetch_results: RefCell::new(VecDeque::new()),
checkout_results: RefCell::new(VecDeque::new()),
rev_parse_results: RefCell::new(VecDeque::new()),
ls_remote_refs_results: RefCell::new(VecDeque::new()),
calls: RefCell::new(Vec::new()),
}
}
/// Queue a result for the next `clone_shallow` call.
pub fn on_clone(&self, result: Result<(), PresetError>) -> &Self {
self.clone_results.borrow_mut().push_back(result);
self
}
/// Queue a result for the next `fetch` call.
pub fn on_fetch(&self, result: Result<(), PresetError>) -> &Self {
self.fetch_results.borrow_mut().push_back(result);
self
}
/// Queue a result for the next `checkout` call.
pub fn on_checkout(&self, result: Result<(), PresetError>) -> &Self {
self.checkout_results.borrow_mut().push_back(result);
self
}
/// Queue a result for the next `rev_parse_head` call.
pub fn on_rev_parse(&self, result: Result<String, PresetError>) -> &Self {
self.rev_parse_results.borrow_mut().push_back(result);
self
}
/// Queue a result for the next `ls_remote_refs` call.
pub fn on_ls_remote_refs(&self, result: Result<Vec<RemoteRef>, PresetError>) -> &Self {
self.ls_remote_refs_results.borrow_mut().push_back(result);
self
}
fn pop_result<T>(
results: &RefCell<VecDeque<Result<T, PresetError>>>,
) -> Result<T, PresetError> {
results.borrow_mut().pop_front().unwrap_or_else(|| {
Err(PresetError::GitClone {
reference: "mock".to_string(),
message: "no more mock results queued".to_string(),
})
})
}
}
impl GitClient for MockGitClient {
fn clone_shallow(
&self,
_url: &str,
_dest: &Path,
branch: Option<&str>,
) -> Result<(), PresetError> {
self.calls.borrow_mut().push(GitCall::CloneShallow {
branch: branch.map(String::from),
});
Self::pop_result(&self.clone_results)
}
fn fetch(&self, _repo_dir: &Path, _branch: Option<&str>) -> Result<(), PresetError> {
self.calls.borrow_mut().push(GitCall::Fetch);
Self::pop_result(&self.fetch_results)
}
fn checkout(&self, _repo_dir: &Path, git_ref: &str) -> Result<(), PresetError> {
self.calls.borrow_mut().push(GitCall::Checkout {
git_ref: git_ref.to_string(),
});
Self::pop_result(&self.checkout_results)
}
fn rev_parse_head(&self, _repo_dir: &Path) -> Result<String, PresetError> {
self.calls.borrow_mut().push(GitCall::RevParseHead);
Self::pop_result(&self.rev_parse_results)
}
fn ls_remote_refs(&self, url: &str) -> Result<Vec<RemoteRef>, PresetError> {
self.calls.borrow_mut().push(GitCall::LsRemoteRefs {
url: url.to_string(),
});
Self::pop_result(&self.ls_remote_refs_results)
}
}
}