返回 CodeWhale
cli.rs
根目录 / crates / engine / src / tools / github / cli.rs
1 //! Command construction: every `gh` and `git` process this tool runs.
2 //!
3 //! Nothing above this file assembles an argv or resolves a binary path, so
4 //! "what did the tool actually shell out to" has exactly one answer.
5
6 use serde_json::Value;
7
8 use crate::tools::spec::{ToolContext, ToolError};
9 use codewhale_dependencies::ExternalTool;
10
11 const DEFAULT_GH: &str = "/opt/homebrew/bin/gh";
12 const FALLBACK_GH_PATHS: &[&str] = &[
13 "/usr/bin/gh", // Linux system package manager
14 "/usr/local/bin/gh", // macOS Intel Homebrew / manual install
15 "/home/linuxbrew/.linuxbrew/bin/gh", // Linux Homebrew (official prefix)
16 "/opt/homebrew/bin/gh", // macOS Apple Silicon Homebrew
17 ];
18
19 const GH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
20
21 fn gh_bin() -> String {
22 if let Ok(bin) = std::env::var("CODEWHALE_GH_BIN").or_else(|_| std::env::var("DEEPSEEK_GH_BIN"))
23 {
24 return bin;
25 }
26 for path in FALLBACK_GH_PATHS {
27 if std::path::Path::new(path).is_file() {
28 return path.to_string();
29 }
30 }
31 DEFAULT_GH.to_string()
32 }
33
34 pub(super) async fn run_gh_text(context: &ToolContext, args: &[&str]) -> Result<String, ToolError> {
35 let mut command = tokio::process::Command::new(gh_bin());
36 codewhale_util::utils::suppress_tokio_console_window(&mut command);
37 command
38 .args(args)
39 .env("GH_PROMPT_DISABLED", "1")
40 .env("GIT_TERMINAL_PROMPT", "0")
41 .current_dir(&context.workspace);
42 let cancel = context.cancel_token.clone().unwrap_or_default();
43 let stop = async {
44 tokio::select! {
45 () = tokio::time::sleep(GH_TIMEOUT) => {}
46 () = cancel.cancelled() => {}
47 }
48 };
49 let run = codewhale_runtime::process_tree::contained_output_until(&mut command, stop)
50 .await
51 .map_err(|e| {
52 if e.kind() == std::io::ErrorKind::NotFound {
53 ToolError::not_available("gh CLI not found; install it or set DEEPSEEK_GH_BIN")
54 } else {
55 ToolError::execution_failed(format!("failed to run gh: {e}"))
56 }
57 })?;
58 if run.stopped {
59 return Err(if cancel.is_cancelled() {
60 ToolError::cancelled("gh cancelled")
61 } else {
62 ToolError::execution_failed(format!(
63 "gh {} timed out after {}s",
64 args.join(" "),
65 GH_TIMEOUT.as_secs()
66 ))
67 });
68 }
69 let out = run.output;
70 if !out.status.success() {
71 return Err(ToolError::execution_failed(format!(
72 "gh {} failed: {}",
73 args.join(" "),
74 String::from_utf8_lossy(&out.stderr).trim()
75 )));
76 }
77 Ok(String::from_utf8_lossy(&out.stdout).to_string())
78 }
79
80 pub(super) async fn run_gh_json(context: &ToolContext, args: &[&str]) -> Result<Value, ToolError> {
81 let text = run_gh_text(context, args).await?;
82 serde_json::from_str(&text).map_err(|e| ToolError::execution_failed(e.to_string()))
83 }
84
85 pub(super) fn ensure_github_repo(context: &ToolContext) -> Result<(), ToolError> {
86 let out = codewhale_dependencies::Git::output(
87 &["rev-parse", "--is-inside-work-tree"],
88 &context.workspace,
89 )
90 .map_err(|e| ToolError::execution_failed(format!("failed to run git: {e}")))?;
91 if out.status.success() {
92 Ok(())
93 } else {
94 Err(ToolError::not_available(
95 "current workspace is not a git repository",
96 ))
97 }
98 }
99
100 pub(super) fn git_status_porcelain(context: &ToolContext) -> Result<String, ToolError> {
101 let out = codewhale_dependencies::Git::status_command(&context.workspace)
102 .map_err(|e| ToolError::execution_failed(format!("failed to prepare git status: {e}")))?
103 .arg("--porcelain")
104 .output()
105 .map_err(|e| ToolError::execution_failed(format!("failed to run git status: {e}")))?;
106 if !out.status.success() {
107 return Err(ToolError::execution_failed(format!(
108 "git status failed ({}); cannot verify that the worktree is clean",
109 out.status
110 )));
111 }
112 Ok(String::from_utf8_lossy(&out.stdout).to_string())
113 }
114
115 /// One captured Core repo selection, reused for every step (including comment-before-close).
116 pub(super) struct HostTarget {
117 repo: String,
118 host: String,
119 }
120 pub(super) async fn host_target(
121 context: &ToolContext,
122 cancel: &tokio_util::sync::CancellationToken,
123 ) -> Result<HostTarget, ToolError> {
124 let override_repo = std::env::var("GH_REPO")
125 .ok()
126 .filter(|value| !value.is_empty());
127 let (host, repo) = if let Some(repo) = override_repo {
128 let parts = repo.split('/').collect::<Vec<_>>();
129 match parts.as_slice() {
130 [owner, name] => (
131 std::env::var("GH_HOST").unwrap_or_else(|_| "github.com".into()),
132 format!("{owner}/{name}"),
133 ),
134 [host, owner, name] => (host.to_string(), format!("{owner}/{name}")),
135 _ => {
136 return Err(ToolError::invalid_input(
137 "GitHub repository override is invalid",
138 ));
139 }
140 }
141 } else {
142 let remote = host_git(context, &["remote", "get-url", "origin"], cancel).await?;
143 let remote = remote.trim();
144 let parsed = if remote.contains("://") {
145 url::Url::parse(remote)
146 } else if let Some((host, path)) = remote.split_once(':') {
147 url::Url::parse(&format!("ssh://{host}/{path}"))
148 } else {
149 return Err(ToolError::not_available(
150 "GitHub requires a network origin repository",
151 ));
152 };
153 let url = parsed.map_err(|_| ToolError::invalid_input("GitHub origin is invalid"))?;
154 if !matches!(url.scheme(), "https" | "http" | "ssh")
155 || url.password().is_some()
156 || url.query().is_some()
157 || url.fragment().is_some()
158 {
159 return Err(ToolError::invalid_input("GitHub origin is invalid"));
160 }
161 let host = std::env::var("GH_HOST")
162 .ok()
163 .filter(|host| !host.is_empty())
164 .or_else(|| url.host_str().map(str::to_string))
165 .ok_or_else(|| ToolError::invalid_input("GitHub origin host missing"))?;
166 (
167 host,
168 url.path()
169 .trim_matches('/')
170 .trim_end_matches(".git")
171 .to_string(),
172 )
173 };
174 if host.is_empty()
175 || host
176 .chars()
177 .any(|c| !c.is_ascii_alphanumeric() && !matches!(c, '.' | '-'))
178 || repo.split('/').count() != 2
179 || repo.split('/').any(|part| {
180 part.is_empty()
181 || part
182 .chars()
183 .any(|c| !c.is_ascii_alphanumeric() && !matches!(c, '.' | '_' | '-'))
184 })
185 {
186 return Err(ToolError::invalid_input(
187 "GitHub repository selection is invalid",
188 ));
189 }
190 Ok(HostTarget {
191 repo: format!("{host}/{repo}"),
192 host,
193 })
194 }
195 pub(super) async fn host_gh(
196 context: &ToolContext,
197 target: &HostTarget,
198 args: &[&str],
199 input: Option<&[u8]>,
200 cancel: &tokio_util::sync::CancellationToken,
201 ) -> Result<String, ToolError> {
202 use codewhale_net::network_policy::Decision;
203 if context
204 .tool_authority
205 .as_ref()
206 .is_some_and(|authority| authority.network_access == Some(false))
207 {
208 return Err(ToolError::permission_denied(
209 "GitHub network access exceeds the current authority",
210 ));
211 }
212 if context
213 .network_policy
214 .as_ref()
215 .is_some_and(|policy| policy.evaluate(&target.host, "github") != Decision::Allow)
216 {
217 return Err(ToolError::permission_denied(
218 "GitHub access is blocked or awaiting network approval",
219 ));
220 }
221 let mut command = if let Ok(binary) =
222 std::env::var("CODEWHALE_GH_BIN").or_else(|_| std::env::var("DEEPSEEK_GH_BIN"))
223 {
224 tokio::process::Command::new(binary)
225 } else {
226 codewhale_dependencies::Gh::tokio_command()
227 .ok_or_else(|| ToolError::not_available("gh CLI is unavailable"))?
228 };
229 codewhale_util::utils::suppress_tokio_console_window(&mut command);
230 command
231 .args(args)
232 .args(["--repo", &target.repo])
233 .env("GH_HOST", &target.host)
234 .env_remove("GH_REPO")
235 .env("GH_PROMPT_DISABLED", "1")
236 .env("GH_PAGER", "cat")
237 .env("GIT_TERMINAL_PROMPT", "0")
238 .current_dir(&context.workspace);
239 host_output(&mut command, input.unwrap_or_default(), cancel, "GitHub").await
240 }
241 pub(super) async fn host_git(
242 context: &ToolContext,
243 args: &[&str],
244 cancel: &tokio_util::sync::CancellationToken,
245 ) -> Result<String, ToolError> {
246 let mut command = codewhale_dependencies::Git::tokio_command()
247 .ok_or_else(|| ToolError::not_available("git is unavailable"))?;
248 command.args(args).current_dir(&context.workspace);
249 host_output(&mut command, &[], cancel, "Git repository inspection").await
250 }
251 pub(super) async fn host_git_status(
252 context: &ToolContext,
253 cancel: &tokio_util::sync::CancellationToken,
254 ) -> Result<String, ToolError> {
255 let command = codewhale_dependencies::Git::status_command(&context.workspace)
256 .map_err(|error| ToolError::not_available(format!("git is unavailable: {error}")))?;
257 let mut command = tokio::process::Command::from(command);
258 command.arg("--porcelain=v1");
259 host_output(&mut command, &[], cancel, "Git repository inspection").await
260 }
261 async fn host_output(
262 command: &mut tokio::process::Command,
263 input: &[u8],
264 cancel: &tokio_util::sync::CancellationToken,
265 label: &str,
266 ) -> Result<String, ToolError> {
267 if cancel.is_cancelled() {
268 return Err(ToolError::not_available("GitHub operation cancelled"));
269 }
270 let output = codewhale_runtime::process_tree::contained_output_with_input_bounded(
271 command,
272 input.to_vec(),
273 1024 * 1024,
274 64 * 1024,
275 cancel.cancelled(),
276 )
277 .await
278 .map_err(|_| {
279 ToolError::execution_failed(format!(
280 "{label} process failed or exceeded its output bound"
281 ))
282 })?;
283 if output.stopped {
284 return Err(ToolError::cancelled("GitHub operation cancelled"));
285 }
286 if !output.output.status.success() {
287 return Err(ToolError::execution_failed(format!(
288 "{label} process failed; private command arguments and diagnostics were withheld"
289 )));
290 }
291 String::from_utf8(output.output.stdout)
292 .map_err(|_| ToolError::execution_failed(format!("{label} output was not UTF-8")))
293 }
294
295 #[cfg(all(test, unix))]
296 mod host_tests {
297 use super::*;
298 #[tokio::test(flavor = "current_thread")]
299 async fn bounded_github_output_refuses_oversize_and_cancelled_children() {
300 let mut command = tokio::process::Command::new("sh");
301 command.args(["-c", "head -c 1048584 /dev/zero"]);
302 let error = host_output(
303 &mut command,
304 &[],
305 &tokio_util::sync::CancellationToken::new(),
306 "GitHub",
307 )
308 .await
309 .unwrap_err()
310 .to_string();
311 assert!(error.contains("bound"));
312 let mut command = tokio::process::Command::new("sh");
313 command.args(["-c", "sleep 30"]);
314 let cancel = tokio_util::sync::CancellationToken::new();
315 let stop = cancel.clone();
316 let (done_tx, done_rx) = tokio::sync::oneshot::channel();
317 tokio::spawn(async move {
318 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
319 stop.cancel();
320 done_tx.send(()).unwrap();
321 });
322 let result = tokio::time::timeout(
323 std::time::Duration::from_secs(2),
324 host_output(&mut command, &[], &cancel, "GitHub"),
325 )
326 .await
327 .unwrap();
328 assert!(result.unwrap_err().to_string().contains("cancelled"));
329 done_rx.await.unwrap();
330 }
331 }
332
332 lines RUST