1use std::io::{Read, Write};
23use std::time::Duration;
24
25use agentmux_common::win32::NoWindow;
26use serde_json::{json, Value};
27
28use crate::mps_client::WpsClient;
29
30const ASK_TIMEOUT: Duration = Duration::from_secs(65);
34
35pub fn owner_repo_of_path(path: &str) -> Option<(String, String)> {
37 let path = path.trim().trim_matches('/');
38 let mut parts = path.split('/');
39 let (owner, repo) = (parts.next()?, parts.next()?);
40 let repo = repo.strip_suffix(".git").unwrap_or(repo);
41 (!owner.is_empty() && !repo.is_empty()).then(|| (owner.to_string(), repo.to_string()))
43}
44
45pub fn parse_request(input: &str) -> Vec<(String, String)> {
47 input
48 .lines()
49 .take_while(|l| !l.trim().is_empty())
50 .filter_map(|l| l.split_once('=').map(|(k, v)| (k.trim().to_string(), v.trim_end_matches('\r').to_string())))
51 .collect()
52}
53
54fn field<'a>(request: &'a [(String, String)], key: &str) -> Option<&'a str> {
55 request.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
56}
57
58pub fn credential_response(token: &str) -> String {
60 format!("username=x-access-token\npassword={token}\n\n")
61}
62
63pub fn repo_of_remote(url: &str) -> Option<(String, String)> {
65 let url = url.trim();
66 let rest = ["https://github.com/", "http://github.com/", "ssh://git@github.com/", "git@github.com:", "git://github.com/"]
67 .iter()
68 .find_map(|p| url.strip_prefix(p))
69 .or_else(|| url.strip_prefix("https://").and_then(|r| r.split_once('@')).and_then(|(_, r)| r.strip_prefix("github.com/")))?;
70 owner_repo_of_path(rest)
71}
72
73pub fn repo_of_gh_command(args: &[String], env_repo: Option<&str>, origin_url: impl FnOnce() -> Option<String>) -> Option<(String, String)> {
76 let mut explicit: Option<String> = None;
78 let mut it = args.iter().peekable();
79 while let Some(a) = it.next() {
80 if a == "-R" || a == "--repo" {
81 explicit = it.next().cloned();
82 } else if let Some(v) = a.strip_prefix("--repo=").or_else(|| a.strip_prefix("-R=")) {
83 explicit = Some(v.to_string());
84 } else if let Some(v) = a.strip_prefix("-R").filter(|v| v.contains('/') && !v.chars().any(char::is_whitespace)) {
85 explicit = Some(v.to_string());
88 }
89 }
90 if let Some(r) = explicit.as_deref().filter(|r| !r.is_empty()) {
91 return repo_of_spec(r);
92 }
93 let env_repo = env_repo.filter(|r| !r.is_empty());
94 if args.first().map(String::as_str) == Some("api") {
96 for a in &args[1..] {
97 let p = a.trim_start_matches('/');
98 if let Some(rest) = p.strip_prefix("repos/") {
99 if rest.starts_with("{owner}/{repo}") {
101 return match env_repo {
102 Some(r) => repo_of_spec(r),
103 None => repo_of_default(&origin_url()?),
104 };
105 }
106 if let Some(found) = owner_repo_of_path(rest) {
107 return Some(found);
108 }
109 }
110 }
111 }
112 if let Some(found) = args.get(2).filter(|_| args[0] != "api").and_then(|a| url_repo(a)).or_else(|| positional_repo(args)) {
114 return Some(found);
115 }
116 if let Some(r) = env_repo {
117 return repo_of_spec(r);
118 }
119 if matches!(args.first().map(String::as_str), None | Some("--version" | "--help" | "help" | "version" | "auth" | "config" | "completion" | "alias" | "extension" | "ext" | "gist" | "search")) {
121 return None;
122 }
123 repo_of_default(&origin_url()?)
124}
125
126pub fn repo_of_default(source: &str) -> Option<(String, String)> {
129 repo_of_remote(source).or_else(|| repo_of_spec(source))
130}
131
132pub fn resolved_default(config_lines: &str) -> Option<Result<String, String>> {
136 config_lines.lines().find_map(|line| {
137 let (key, value) = line.trim().split_once(char::is_whitespace)?;
138 let remote = key.strip_prefix("remote.")?.strip_suffix(".gh-resolved")?;
139 match value.trim() {
140 "" | "other" => None,
141 "base" => Some(Err(remote.to_string())),
142 repo => Some(Ok(repo.to_string())),
143 }
144 })
145}
146
147fn url_repo(arg: &str) -> Option<(String, String)> {
149 let rest = arg.strip_prefix("https://github.com/").or_else(|| arg.strip_prefix("http://github.com/"))?;
150 owner_repo_of_path(rest)
151}
152
153fn positional_repo(args: &[String]) -> Option<(String, String)> {
155 if args.first().map(String::as_str) != Some("repo") {
156 return None;
157 }
158 if !matches!(args.get(1).map(String::as_str), Some("clone" | "view" | "fork" | "edit" | "delete" | "archive" | "rename" | "sync" | "set-default")) {
159 return None;
160 }
161 args[2..].iter().filter(|a| !a.starts_with('-')).find_map(|a| repo_of_spec(a))
162}
163
164pub fn repo_of_spec(spec: &str) -> Option<(String, String)> {
166 let parts: Vec<&str> = spec.trim().split('/').collect();
167 match parts.as_slice() {
168 [owner, repo] => owner_repo_of_path(&format!("{owner}/{repo}")),
169 [host, owner, repo] if host.eq_ignore_ascii_case("github.com") => owner_repo_of_path(&format!("{owner}/{repo}")),
170 _ => None,
171 }
172}
173
174#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct Granted {
178 pub token: String,
179 pub owner_github_id: Option<u64>,
180 pub owner_login: Option<String>,
181 pub bot_slug: Option<String>,
182 pub bot_user_id: Option<u64>,
183}
184
185pub enum Answer {
187 Token(Granted),
188 Refused(String),
189}
190
191pub fn ask(owner: &str, repo: &str) -> Answer {
193 ask_for(owner, repo, None)
194}
195
196const PURPOSE_GIT: &str = "git";
199
200pub fn ask_for(owner: &str, repo: &str, purpose: Option<&str>) -> Answer {
202 let Some(client) = WpsClient::from_env() else {
203 return Answer::Refused("AGENTMUX_LOCAL_URL / AGENTMUX_AUTH_KEY aren't set: run this from an agent's own shell".to_string());
204 };
205 let agent_token = std::env::var("AGENTMUX_AGENT_TOKEN").ok();
206 let rt = match tokio::runtime::Runtime::new() {
207 Ok(rt) => rt,
208 Err(e) => return Answer::Refused(format!("couldn't start: {e}")),
209 };
210 let mut body = json!({ "owner": owner, "repo": repo });
211 if let Some(purpose) = purpose {
212 body["purpose"] = json!(purpose);
213 }
214 match rt.block_on(client.post_json_status("/api/v1/github/token", agent_token.as_deref(), &body, ASK_TIMEOUT)) {
215 Ok((status, answer)) if (200..300).contains(&status) => match answer.get("token").and_then(Value::as_str).filter(|t| !t.is_empty()) {
216 Some(token) => Answer::Token(Granted {
217 token: token.to_string(),
218 owner_github_id: answer.get("ownerGithubId").and_then(Value::as_u64),
219 owner_login: answer.get("ownerLogin").and_then(Value::as_str).map(str::to_string),
220 bot_slug: answer.get("botSlug").and_then(Value::as_str).map(str::to_string),
221 bot_user_id: answer.get("botUserId").and_then(Value::as_u64),
222 }),
223 None => Answer::Refused("AgentMux gave no token".to_string()),
224 },
225 Ok((status, answer)) => Answer::Refused(
226 answer.get("error").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("AgentMux refused ({status})")),
227 ),
228 Err(e) => Answer::Refused(format!("couldn't reach AgentMux: {e}")),
229 }
230}
231
232pub fn run_git_credential(op: &str) -> i32 {
234 if op != "get" {
236 return 0;
237 }
238 let mut input = String::new();
239 let _ = std::io::stdin().read_to_string(&mut input);
240 let request = parse_request(&input);
241 if field(&request, "protocol") != Some("https") || !field(&request, "host").is_some_and(|h| h.eq_ignore_ascii_case("github.com")) {
242 return 1;
244 }
245 let Some((owner, repo)) = field(&request, "path").and_then(owner_repo_of_path) else {
246 eprintln!("agentmux: git asked for GitHub credentials without a repository, so there is no token to give (credential.useHttpPath is off?)");
247 return 1;
248 };
249 match ask_for(&owner, &repo, Some(PURPOSE_GIT)) {
250 Answer::Token(granted) => {
251 let mut out = std::io::stdout();
252 let _ = out.write_all(credential_response(&granted.token).as_bytes());
253 let _ = out.flush();
254 0
255 }
256 Answer::Refused(why) => {
257 eprintln!("agentmux: no GitHub token for {owner}/{repo}: {why}");
258 1
259 }
260 }
261}
262
263pub fn default_repo_source(cwd: Option<&str>) -> Option<String> {
266 let git_config = |args: &[&str]| {
267 let mut cmd = std::process::Command::new("git");
268 if let Some(dir) = cwd {
269 cmd.arg("-C").arg(dir);
270 }
271 cmd.arg("config").args(args).stdin(std::process::Stdio::null()).stderr(std::process::Stdio::null());
272 cmd.no_window();
274 let out = cmd.output().ok()?;
275 out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
276 };
277 match resolved_default(&git_config(&["--get-regexp", r"^remote\..*\.gh-resolved$"]).unwrap_or_default()) {
278 Some(Ok(spec)) => Some(spec),
279 Some(Err(remote)) => git_config(&["--get", &format!("remote.{remote}.url")]),
280 None => git_config(&["--get", "remote.origin.url"]),
281 }
282}
283
284fn repo_of_command_here(gh_args: &[String]) -> Option<(String, String)> {
286 let env_repo = std::env::var("GH_REPO").ok();
287 repo_of_gh_command(gh_args, env_repo.as_deref(), || default_repo_source(None))
288}
289
290pub fn owner_tag(owner_github_id: u64) -> String {
292 format!("<!-- agentmux:owner_github_id={owner_github_id} -->")
293}
294
295fn with_tag(body: &str, tag: &str) -> String {
296 if body.contains("agentmux:owner_github_id=") {
297 body.to_string()
298 } else if body.trim().is_empty() {
299 format!("{tag}\n")
300 } else {
301 format!("{}\n\n{tag}\n", body.trim_end())
302 }
303}
304
305pub fn rewrite_pr_body(args: &[String], tag: &str, read_file: impl Fn(&str) -> Option<String>) -> Vec<String> {
310 let mut out = Vec::with_capacity(args.len());
311 let mut i = 0;
312 while i < args.len() {
313 let a = args[i].as_str();
314 let value = args.get(i + 1);
315 match (a, value) {
316 ("--body" | "-b", Some(v)) => {
317 out.extend([a.to_string(), with_tag(v, tag)]);
318 i += 2;
319 }
320 ("--body-file" | "-F", Some(v)) => {
321 match (v != "-").then(|| read_file(v)).flatten() {
322 Some(text) => out.extend(["--body".to_string(), with_tag(&text, tag)]),
323 None => out.extend([a.to_string(), v.clone()]),
324 }
325 i += 2;
326 }
327 _ => {
328 if let Some(v) = a.strip_prefix("--body=") {
329 out.push(format!("--body={}", with_tag(v, tag)));
330 } else if let Some(v) = a.strip_prefix("--body-file=") {
331 match read_file(v) {
332 Some(text) => out.push(format!("--body={}", with_tag(&text, tag))),
333 None => out.push(a.to_string()),
334 }
335 } else {
336 out.push(a.to_string());
337 }
338 i += 1;
339 }
340 }
341 }
342 out
343}
344
345fn read_body_file(path: &str) -> Option<String> {
347 const MAX_BYTES: u64 = 24_000;
348 let meta = std::fs::metadata(path).ok()?;
349 (meta.is_file() && meta.len() <= MAX_BYTES).then(|| std::fs::read_to_string(path).ok()).flatten()
350}
351
352pub fn run_github_owner_tag(gh_args: &[String]) -> i32 {
356 let mut args = gh_args.to_vec();
357 if let Some((owner, repo)) = repo_of_command_here(gh_args) {
358 if let Answer::Token(Granted { owner_github_id: Some(id), .. }) = ask(&owner, &repo) {
359 let tag = owner_tag(id);
360 args = rewrite_pr_body(gh_args, &tag, read_body_file);
361 }
362 }
363 let mut out = std::io::stdout();
364 for a in &args {
365 let _ = out.write_all(a.as_bytes());
366 let _ = out.write_all(&[0]);
367 }
368 let _ = out.flush();
369 0
370}
371
372fn acts_on_a_repository(gh_args: &[String]) -> bool {
376 let word = gh_args.iter().map(String::as_str).find(|a| !a.starts_with('-'));
377 matches!(word, Some("pr" | "issue" | "run" | "workflow" | "release" | "label" | "cache" | "secret" | "variable" | "ruleset" | "repo" | "api" | "browse"))
378}
379
380const NO_REPOSITORY: &str = "agentmux: this gh command has no GitHub token: it names no repository, and this directory has no github.com remote, so AgentMux can't tell which repository to sign in for. Add -R owner/repo, or run it inside a clone of the repository.";
382
383pub fn run_github_token(gh_args: &[String]) -> i32 {
386 let Some((owner, repo)) = repo_of_command_here(gh_args) else {
387 if acts_on_a_repository(gh_args) {
388 eprintln!("{NO_REPOSITORY}");
389 }
390 return 0;
391 };
392 match ask(&owner, &repo) {
393 Answer::Token(granted) => {
394 println!("{}", granted.token);
395 0
396 }
397 Answer::Refused(why) => {
398 eprintln!("agentmux: no GitHub token for {owner}/{repo}: {why}");
399 0
400 }
401 }
402}
403
404#[cfg(test)]
405pub(crate) mod tests {
406 use super::*;
407
408 fn args(a: &[&str]) -> Vec<String> {
409 a.iter().map(|s| s.to_string()).collect()
410 }
411
412 fn repo(o: &str, r: &str) -> Option<(String, String)> {
413 Some((o.to_string(), r.to_string()))
414 }
415
416 pub(crate) fn stub_srv(status: u16, body: &'static str) -> (String, std::thread::JoinHandle<String>) {
418 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
419 let url = format!("http://{}", listener.local_addr().unwrap());
420 let handle = std::thread::spawn(move || {
421 let (mut stream, _) = listener.accept().unwrap();
422 let mut data = Vec::new();
423 let mut buf = [0u8; 4096];
424 loop {
425 let n = stream.read(&mut buf).unwrap();
426 data.extend_from_slice(&buf[..n]);
427 let text = String::from_utf8_lossy(&data).to_string();
428 if let Some(end) = text.find("\r\n\r\n") {
429 let len = text
430 .lines()
431 .find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0)))
432 .unwrap_or(0);
433 if data.len() >= end + 4 + len {
434 break;
435 }
436 }
437 if n == 0 {
438 break;
439 }
440 }
441 let reply = format!("HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
442 stream.write_all(reply.as_bytes()).unwrap();
443 String::from_utf8_lossy(&data).to_string()
444 });
445 (url, handle)
446 }
447
448 #[test]
449 fn a_token_comes_from_srv_for_the_repository_as_the_calling_agent() {
450 let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
451 let (url, srv) = stub_srv(200, r#"{"token":"ghs_FROM_SRV","expiresAt":1,"botSlug":"muxagent","botUserId":7,"ownerGithubId":42,"ownerLogin":"octo"}"#);
452 std::env::set_var("AGENTMUX_LOCAL_URL", &url);
453 std::env::set_var("AGENTMUX_AUTH_KEY", "key");
454 std::env::set_var("AGENTMUX_AGENT_TOKEN", "agent-token-1");
455 let answer = ask("octo", "hello");
456 let seen = srv.join().unwrap();
457 assert!(matches!(&answer, Answer::Token(t) if t.token == "ghs_FROM_SRV" && t.owner_github_id == Some(42) && t.bot_slug.as_deref() == Some("muxagent")));
458 assert!(seen.starts_with("POST /api/v1/github/token "), "{seen}");
459 let lower = seen.to_ascii_lowercase();
460 assert!(lower.contains("x-agent-token: agent-token-1"), "who is asking is the agent's own token: {seen}");
461 assert!(seen.contains(r#""owner":"octo""#) && seen.contains(r#""repo":"hello""#), "{seen}");
462 assert!(!seen.contains("agent_id"), "no name in the request: srv decides who is asking");
463 }
464
465 #[test]
466 fn git_says_what_its_token_is_for_and_gh_says_nothing() {
467 let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
468 std::env::set_var("AGENTMUX_AUTH_KEY", "key");
469 std::env::set_var("AGENTMUX_AGENT_TOKEN", "agent-token-1");
470 let (url, srv) = stub_srv(200, r#"{"token":"ghs_A"}"#);
471 std::env::set_var("AGENTMUX_LOCAL_URL", &url);
472 let _ = ask_for("octo", "hello", Some(PURPOSE_GIT));
473 assert!(srv.join().unwrap().contains(r#""purpose":"git""#), "the credential helper asks for a push");
474 let (url, srv) = stub_srv(200, r#"{"token":"ghs_A"}"#);
475 std::env::set_var("AGENTMUX_LOCAL_URL", &url);
476 let _ = ask("octo", "hello");
477 assert!(!srv.join().unwrap().contains("purpose"), "a gh command states no purpose: srv reads that as api");
478 }
479
480 #[test]
481 fn a_refusal_is_srvs_own_sentence_never_a_token() {
482 let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
483 let (url, srv) = stub_srv(403, r#"{"error":"the AgentMux GitHub App isn't installed on octo"}"#);
484 std::env::set_var("AGENTMUX_LOCAL_URL", &url);
485 std::env::set_var("AGENTMUX_AUTH_KEY", "key");
486 std::env::remove_var("AGENTMUX_AGENT_TOKEN");
487 let answer = ask("octo", "hello");
488 srv.join().unwrap();
489 assert!(matches!(&answer, Answer::Refused(why) if why == "the AgentMux GitHub App isn't installed on octo"), "refused with srv's words");
490 }
491
492 #[test]
493 fn the_owner_tag_goes_into_the_body_however_it_is_given() {
494 let tag = owner_tag(42);
495 assert_eq!(tag, "<!-- agentmux:owner_github_id=42 -->");
496 let copy = |p: &str| (p != "missing.md").then(|| format!("text of {p}"));
497 let got = rewrite_pr_body(&args(&["pr", "create", "--title", "t", "--body", "Text\n"]), &tag, copy);
498 assert_eq!(got[5], format!("Text\n\n{tag}\n"));
499 let got = rewrite_pr_body(&args(&["pr", "edit", "-b", "x", "--body=y", "--body-file", "f.md", "-F", "-", "--body-file=g.md"]), &tag, copy);
500 assert_eq!(got[2], "-b");
501 assert!(got[3].ends_with(&format!("{tag}
502")));
503 assert_eq!(got[4], format!("--body=y
504
505{tag}
506"));
507 assert_eq!(&got[5..7], &["--body".to_string(), format!("text of f.md\n\n{tag}\n")]);
509 assert_eq!(&got[7..9], &["-F".to_string(), "-".to_string()], "stdin can't be read twice");
510 assert_eq!(got[9], format!("--body=text of g.md\n\n{tag}\n"));
511 let gone = rewrite_pr_body(&args(&["pr", "edit", "-F", "missing.md"]), &tag, copy);
512 assert_eq!(gone, args(&["pr", "edit", "-F", "missing.md"]), "a file that can't be read stays as it is");
513 let again = rewrite_pr_body(&args(&["pr", "create", "-b", &format!("x\n{tag}")]), &tag, copy);
515 assert_eq!(again[3], format!("x\n{tag}"));
516 assert_eq!(rewrite_pr_body(&args(&["pr", "create", "--fill"]), &tag, copy), args(&["pr", "create", "--fill"]));
517 assert_eq!(rewrite_pr_body(&args(&["pr", "create", "-b", ""]), &tag, copy)[3], format!("{tag}\n"));
518 }
519
520 #[test]
521 fn gh_resolved_names_the_default_repository() {
522 assert_eq!(resolved_default("remote.upstream.gh-resolved base\nremote.origin.gh-resolved other"), Some(Err("upstream".to_string())));
523 assert_eq!(resolved_default("remote.origin.gh-resolved octo/hello"), Some(Ok("octo/hello".to_string())));
524 assert_eq!(resolved_default("remote.origin.gh-resolved other"), None);
525 assert_eq!(resolved_default(""), None);
526 }
527
528 #[test]
529 fn git_asks_with_key_value_lines_and_a_path() {
530 let input = "protocol=https\nhost=github.com\npath=octo/hello.git\n\nignored=after-blank\n";
531 let r = parse_request(input);
532 assert_eq!(field(&r, "host"), Some("github.com"));
533 assert_eq!(field(&r, "path").and_then(owner_repo_of_path), repo("octo", "hello"));
534 assert_eq!(field(&r, "ignored"), None);
535 assert_eq!(parse_request("protocol=https\r\nhost=github.com\r\n\r\n").len(), 2);
536 }
537
538 #[test]
539 fn a_path_names_the_repository_and_nothing_else_does() {
540 assert_eq!(owner_repo_of_path("octo/hello"), repo("octo", "hello"));
541 assert_eq!(owner_repo_of_path("/octo/hello.git/"), repo("octo", "hello"));
542 assert_eq!(owner_repo_of_path("octo/hello/info/refs"), repo("octo", "hello"));
543 assert_eq!(owner_repo_of_path("octo"), None);
544 assert_eq!(owner_repo_of_path(""), None);
545 assert_eq!(owner_repo_of_path("/hello"), None);
546 }
547
548 #[test]
549 fn the_credential_is_a_username_and_the_token_and_nothing_stored() {
550 assert_eq!(credential_response("ghs_X"), "username=x-access-token\npassword=ghs_X\n\n");
551 assert_eq!(run_git_credential("store"), 0);
553 assert_eq!(run_git_credential("erase"), 0);
554 }
555
556 #[test]
557 fn github_remotes_in_every_spelling_name_the_repository() {
558 for url in [
559 "https://github.com/octo/hello.git",
560 "https://github.com/octo/hello",
561 "https://user@github.com/octo/hello.git",
562 "git@github.com:octo/hello.git",
563 "ssh://git@github.com/octo/hello.git",
564 "git://github.com/octo/hello",
565 ] {
566 assert_eq!(repo_of_remote(url), repo("octo", "hello"), "{url}");
567 }
568 assert_eq!(repo_of_remote("https://gitlab.com/octo/hello.git"), None);
569 assert_eq!(repo_of_remote("https://github.example.com/octo/hello.git"), None);
570 assert_eq!(repo_of_remote("/home/me/repo"), None);
571 }
572
573 #[test]
574 fn gh_is_about_the_repository_it_names_else_the_working_directorys() {
575 let origin = || Some("https://github.com/home/checkout.git".to_string());
576 assert_eq!(repo_of_gh_command(&args(&["pr", "create"]), None, origin), repo("home", "checkout"));
577 assert_eq!(repo_of_gh_command(&args(&["pr", "list", "-R", "octo/hello"]), None, origin), repo("octo", "hello"));
578 assert_eq!(repo_of_gh_command(&args(&["pr", "list", "--repo", "github.com/octo/hello"]), None, origin), repo("octo", "hello"));
579 assert_eq!(repo_of_gh_command(&args(&["pr", "list", "--repo=octo/hello"]), None, origin), repo("octo", "hello"));
580 assert_eq!(repo_of_gh_command(&args(&["pr", "create", "-Rocto/hello"]), None, origin), repo("octo", "hello"));
582 assert_eq!(repo_of_gh_command(&args(&["pr", "create", "-R=octo/hello"]), None, origin), repo("octo", "hello"));
583 assert_eq!(repo_of_gh_command(&args(&["-Rocto/hello", "pr", "edit", "7"]), None, origin), repo("octo", "hello"));
584 assert_eq!(repo_of_gh_command(&args(&["pr", "create", "--title", "-Rework parser"]), None, origin), repo("home", "checkout"));
586 assert_eq!(repo_of_gh_command(&args(&["pr", "create", "--title", "-Rework/a b"]), None, origin), repo("home", "checkout"));
587 assert_eq!(repo_of_gh_command(&args(&["pr", "list"]), Some("env/repo"), origin), repo("env", "repo"));
588 assert_eq!(repo_of_gh_command(&args(&["api", "repos/octo/hello/pulls"]), None, origin), repo("octo", "hello"));
589 assert_eq!(repo_of_gh_command(&args(&["api", "repos/{owner}/{repo}/issues"]), None, origin), repo("home", "checkout"));
591 assert_eq!(repo_of_gh_command(&args(&["api", "repos/octo/second/issues"]), Some("octo/first"), origin), repo("octo", "second"));
593 assert_eq!(repo_of_gh_command(&args(&["api", "repos/{owner}/{repo}/issues"]), Some("octo/first"), origin), repo("octo", "first"));
594 assert_eq!(repo_of_gh_command(&args(&["pr", "create", "--body", "https://github.com/other/private/issues/1"]), None, origin), repo("home", "checkout"));
596 assert_eq!(repo_of_gh_command(&args(&["pr", "view", "https://github.com/other/private/pull/1"]), None, origin), repo("other", "private"));
598 assert_eq!(repo_of_gh_command(&args(&["repo", "clone", "other/private", "dir"]), None, || None), repo("other", "private"));
599 assert_eq!(repo_of_gh_command(&args(&["repo", "view", "--json", "name", "o/r"]), None, origin), repo("o", "r"));
600 assert_eq!(repo_of_gh_command(&args(&["pr", "create"]), None, || Some("up/stream".to_string())), repo("up", "stream"));
602 assert_eq!(repo_of_gh_command(&args(&["api", "/repos/octo/hello/issues", "-f", "title=x"]), None, origin), repo("octo", "hello"));
603 assert_eq!(repo_of_gh_command(&args(&["pr", "list", "-R", "ghe.example.com/octo/hello"]), None, origin), None);
605 }
606
607 #[test]
608 fn gh_commands_that_name_no_repository_get_no_token_and_no_noise() {
609 let origin = || Some("https://github.com/home/checkout.git".to_string());
610 for a in [&["--version"][..], &["auth", "status"], &["config", "list"], &["search", "repos", "x"], &[]] {
611 assert_eq!(repo_of_gh_command(&args(a), None, origin), None, "{a:?}");
612 }
613 assert_eq!(repo_of_gh_command(&args(&["pr", "list"]), None, || None), None);
615 }
616
617 #[test]
618 fn a_command_that_needed_a_repository_and_found_none_is_told_where_it_comes_from() {
619 for a in [&["pr", "create"][..], &["issue", "list"], &["api", "/user"], &["release", "view"]] {
620 assert!(acts_on_a_repository(&args(a)), "{a:?}");
621 }
622 for a in [&["--version"][..], &["auth", "status"], &["search", "repos", "x"], &["config", "list"], &[]] {
623 assert!(!acts_on_a_repository(&args(a)), "{a:?}");
624 }
625 assert!(NO_REPOSITORY.contains("-R owner/repo") && NO_REPOSITORY.contains("clone"), "it says what to do");
626 assert!(!NO_REPOSITORY.contains("gh auth login"));
627 }
628}