Skip to main content

agentmux_bashwrap/
github.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! GitHub tokens for an agent's `git` and `gh`.
5//!
6//! - `git-credential <get|store|erase>`: git's credential helper protocol. srv puts it in the
7//!   environment of an agent whose person connected GitHub through AgentMux Cloud
8//!   (`credential.https://github.com.helper`), after an empty helper that clears the list, so no
9//!   other helper's login (the person's, a stored token) is ever asked. For `get` it asks srv for
10//!   the AgentMux GitHub App's token for the repository in the request's path; `store` and `erase`
11//!   do nothing, so a token is never written down.
12//! - `github-token -- <gh args>`: what the `gh` shell function this wrapper exports calls
13//!   (`shim_functions.rs`). It finds the repository the command is about (`-R`, `GH_REPO`, the
14//!   path of `gh api repos/o/r/…`, else the working directory's `origin`) and prints a token for
15//!   it, or prints nothing and says why on stderr. The function then runs `gh` with that token, or
16//!   with none: never with another credential.
17//!
18//! Both ask `POST /api/v1/github/token`; who is asking is decided by srv from the agent's token
19//! (`AGENTMUX_AGENT_TOKEN`), and the answer is the narrowed installation token or a sentence for
20//! the person. The token is never logged here.
21
22use 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
30/// srv may call AgentMux Cloud twice (a revalidation, then the mint), or wait on the host's `gh-agent` for a fresh token (up to
31/// 50 s, `identity::gh_agent_token`), and then says why it has none: this waits a little longer than that, so the answer
32/// reaches the command. A stuck call still must not hold a `git push` forever.
33const ASK_TIMEOUT: Duration = Duration::from_secs(65);
34
35/// The repository named by a git credential request's `path`: `owner/repo` or `owner/repo.git`.
36pub 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    // Anything after the repository (a `/info/refs`-style tail) is ignored.
42    (!owner.is_empty() && !repo.is_empty()).then(|| (owner.to_string(), repo.to_string()))
43}
44
45/// `key=value` lines up to a blank line, as git writes them.
46pub 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
58/// What git is told when srv gave a token.
59pub fn credential_response(token: &str) -> String {
60    format!("username=x-access-token\npassword={token}\n\n")
61}
62
63/// `owner/repo` of a GitHub remote URL (https, scp-style ssh or ssh://), for github.com only.
64pub 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
73/// The repository `gh` is about to act on, from its arguments and environment, else from the working
74/// directory's `origin`. `None` when the command names no repository (e.g. `gh --version`).
75pub fn repo_of_gh_command(args: &[String], env_repo: Option<&str>, origin_url: impl FnOnce() -> Option<String>) -> Option<(String, String)> {
76    // -R/--repo [HOST/]OWNER/REPO
77    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            // `-Rowner/repo`, the value written against the flag. Text that merely begins with `-R` (a title like
86            // `-Rework parser`) has no `/` or has a space, and is not taken for a repository.
87            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    // gh api repos/OWNER/REPO/…: a literal endpoint names its repository, whatever GH_REPO says.
95    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                // gh fills `{owner}/{repo}` from GH_REPO, else the working directory's repository.
100                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    // A pull request or issue named by its URL (`gh pr view <url>`), or a repository named on the command line.
113    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    // gh needs no repository for these.
120    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
126/// The repository for what [`default_repo_source`] found: a remote's URL, or an `OWNER/REPO` set with
127/// `gh repo set-default`.
128pub fn repo_of_default(source: &str) -> Option<(String, String)> {
129    repo_of_remote(source).or_else(|| repo_of_spec(source))
130}
131
132/// What `gh` takes as the default repository, from the lines of
133/// `git config --get-regexp '^remote\..*\.gh-resolved$'` (`gh repo set-default`, and a fork cloned
134/// with `gh repo clone`): `Ok(OWNER/REPO)` as set, `Err(remote)` for "the repository of that remote".
135pub 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
147/// The repository of a `https://github.com/OWNER/REPO/…` argument (`gh pr view <url>`).
148fn 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
153/// The repository `gh repo <verb> OWNER/REPO` is about, when it takes one as an argument.
154fn 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
164/// `[HOST/]OWNER/REPO`; a host other than github.com is not ours.
165pub 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/// What `POST /api/v1/github/token` granted: the token, who the App's bot is, and who the agent
175/// works for (the account's own GitHub id and login).
176#[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
185/// The answer of `POST /api/v1/github/token`: a token, or what to tell the person.
186pub enum Answer {
187    Token(Granted),
188    Refused(String),
189}
190
191/// Ask srv for the token a `gh` command uses for `owner/repo`.
192pub fn ask(owner: &str, repo: &str) -> Answer {
193    ask_for(owner, repo, None)
194}
195
196/// What git's credential helper says the token is for: a push. srv gives a container a token that writes contents only to
197/// this ask, and never believes it for more than that.
198const PURPOSE_GIT: &str = "git";
199
200/// Ask srv for a token for `owner/repo`; `purpose` says what it is for (`git` from the credential helper).
201pub 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
232/// `git-credential <op>`: git's helper protocol. Exit code 0 with the credential on stdout, or 1.
233pub fn run_git_credential(op: &str) -> i32 {
234    // Never store: a token lasts an hour and is minted per request.
235    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        // Not GitHub: nothing to give, and nothing to say.
243        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
263/// The repository `gh` itself would act on, as a remote's URL or an `OWNER/REPO`: the one it was
264/// told (`gh repo set-default`, a cloned fork's parent), else `origin`'s. `cwd` is where `git -C` points.
265pub 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        // Windows: git is a console program, and this process has no console of its own.
273        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
284/// The repository a `gh` command is about, for [`run_github_token`] and [`run_github_owner_tag`].
285fn 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
290/// What marks a PR as the work of a person's agent: the id of the GitHub account it works for.
291pub 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
305/// `gh pr create` / `gh pr edit` arguments with `tag` added to the PR's body: `--body`/`-b` text,
306/// or a `--body-file`/`-F` file, whose text (read by `read_file`) becomes the `--body` (stdin can't
307/// be read twice, and a file too big to pass stays as it is). Arguments that give no body
308/// (`--fill`, a prompt) are left alone.
309pub 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
345/// The text of a PR body file, if it is small enough to go on a command line.
346fn 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
352/// `github-owner-tag -- <gh args>`: the arguments of a `gh pr create` or `gh pr edit` with the owner
353/// tag in its body, each followed by a NUL byte, for the `gh` function to run `gh` with. The
354/// arguments unchanged when there is no owner to name or no body to put it in.
355pub 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
372/// Whether a `gh` command is one that acts on a repository (a pull request, an issue, a run, a release, an API
373/// call...), so a repository it does not name and the working directory does not give leaves it with no token.
374/// `gh --version`, `gh auth status`, `gh search` and the like need none.
375fn 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
380/// What a command that acts on a repository, and found none, is told: where the repository comes from.
381const 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
383/// `github-token -- <gh args>`: print a token for the repository the `gh` command is about; with
384/// none, say why on stderr (when there is a repository, or the command needed one) and print nothing.
385pub 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    /// srv, as a one-shot stub: answers one request with `status` and `body`, and returns what it was sent.
417    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        // A body file's text goes in as the body.
508        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        // Already there: not twice. No body: nothing to add it to.
514        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        // store and erase are never an error and never keep anything.
552        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        // The value written against the flag names the repository too, with or without the `=`.
581        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        // A value that only begins with `-R` is text, not a repository: the working directory's repository stays.
585        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        // gh fills the placeholders from the working directory's repository.
590        assert_eq!(repo_of_gh_command(&args(&["api", "repos/{owner}/{repo}/issues"]), None, origin), repo("home", "checkout"));
591        // A literal endpoint beats GH_REPO; the placeholders follow it.
592        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        // A URL in a flag's value (a body that links elsewhere) is not the target.
595        assert_eq!(repo_of_gh_command(&args(&["pr", "create", "--body", "https://github.com/other/private/issues/1"]), None, origin), repo("home", "checkout"));
596        // A URL or a repository on the command line is the target, not the checkout.
597        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        // The repository set with `gh repo set-default` is a spec, not a URL.
601        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        // A repository on another host isn't ours to give a token for.
604        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        // Not in a git checkout: no origin, no token.
614        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}