git checks: honor -R owner/name, refuse arguments it doesn't take
`checks` read only its first argument as a pull request number, so `["19", "-R", "owner/name"]` dropped the flag and answered with this checkout's #19. It now reads `-R`/`--repo`/`--repo=` as `gh` does (owner/name, or host/owner/name), reads that repository's pull request and its checks, and names the repository in the answer. `-R` without a number is refused, since the branch lookup only knows this checkout, and so is any flag or second number rather than being skipped.
This commit is contained in:
@@ -78,7 +78,7 @@ impl Tool for GitTool {
|
||||
"args": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "What the action operates on: paths for `add`, a branch for `checkout`, a subcommand for `stash`, a `gh pr` command line for `pr` (e.g. [\"create\", \"--title\", \"...\", \"--body\", \"...\"]; the branch is pushed for you if it has no upstream), a `gh issue` command line for `issue` (e.g. [\"view\", \"12\", \"--comments\"]), a PR number for `checks` (default: this branch's), otherwise git's own flags. Never the commit message."
|
||||
"description": "What the action operates on: paths for `add`, a branch for `checkout`, a subcommand for `stash`, a `gh pr` command line for `pr` (e.g. [\"create\", \"--title\", \"...\", \"--body\", \"...\"]; the branch is pushed for you if it has no upstream), a `gh issue` command line for `issue` (e.g. [\"view\", \"12\", \"--comments\"]), a PR number for `checks` (default: this branch's), with `-R owner/name` for another repository's, otherwise git's own flags. Never the commit message."
|
||||
}
|
||||
},
|
||||
"required": ["action"]
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! cannot see. Reading only; re-running a job stays behind the permission engine's `ask`.
|
||||
|
||||
use luxe_core::github::{
|
||||
Branches, CheckLog, Checks, Discovery, FailingCheck, GitHubError, PullRequests,
|
||||
Branches, CheckLog, Checks, Discovery, FailingCheck, GitHubError, PullRequests, Repository,
|
||||
};
|
||||
use std::path::Path;
|
||||
|
||||
@@ -27,27 +27,23 @@ struct Target {
|
||||
pending: Option<usize>,
|
||||
}
|
||||
|
||||
/// What `checks` was asked about, read from its `args`.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct Request {
|
||||
/// Pull request named, when one was
|
||||
number: Option<u64>,
|
||||
/// Repository named with `-R`, when it isn't this checkout's
|
||||
repository: Option<Repository>,
|
||||
}
|
||||
|
||||
/// Why checks are failing on the branch's pull request, on pull request `#n` when `args` names one,
|
||||
/// or on `HEAD` when the branch has no pull request.
|
||||
/// or on `HEAD` when the branch has no pull request. `-R owner/name` reads another repository's.
|
||||
pub(super) async fn checks(
|
||||
github: &(impl Discovery + PullRequests + Branches + Checks + ?Sized),
|
||||
cwd: &Path,
|
||||
args: &[String],
|
||||
) -> Result<String, String> {
|
||||
let repository = github.repository(cwd).await.map_err(|error| failure(&error))?;
|
||||
let target = match args.first().map(|arg| arg.trim_start_matches('#')) {
|
||||
Some(number) => {
|
||||
let number: u64 =
|
||||
number.parse().map_err(|_| format!("`{number}` is not a pull request number."))?;
|
||||
let pr = github.pull_request(&repository, number).await.map_err(|e| failure(&e))?;
|
||||
Target {
|
||||
oid: pr.head_oid,
|
||||
name: format!("#{} · {}", pr.number, luxe_core::github::untrusted(&pr.title, 120)),
|
||||
pending: Some(pr.checks.pending),
|
||||
}
|
||||
}
|
||||
None => branch_target(github, cwd, &repository).await?,
|
||||
};
|
||||
let (repository, target) = resolve(github, cwd, parse_request(args)?).await?;
|
||||
let failing = github
|
||||
.failing_checks(&repository, &target.oid, LOG_TAIL)
|
||||
.await
|
||||
@@ -55,11 +51,120 @@ pub(super) async fn checks(
|
||||
Ok(render(&target, &failing))
|
||||
}
|
||||
|
||||
/// Why `-R` alone is refused: the branch-to-pull-request lookup only knows this checkout.
|
||||
const REPO_NEEDS_NUMBER: &str = "Name the pull request as well as `-R`: the branch here belongs \
|
||||
to this checkout, not that repository.";
|
||||
|
||||
/// The repository and commit `request` asks about. A repository named with `-R` is named in the
|
||||
/// answer too, so it can't be mistaken for this checkout's.
|
||||
async fn resolve(
|
||||
github: &(impl Discovery + PullRequests + Branches + ?Sized),
|
||||
cwd: &Path,
|
||||
request: Request,
|
||||
) -> Result<(Repository, Target), String> {
|
||||
if let Some(repository) = request.repository {
|
||||
let number = request.number.ok_or(REPO_NEEDS_NUMBER)?;
|
||||
let mut target = named_target(github, &repository, number).await?;
|
||||
target.name = format!("{}{}", repository.slug(), target.name);
|
||||
return Ok((repository, target));
|
||||
}
|
||||
let repository = github.repository(cwd).await.map_err(|error| failure(&error))?;
|
||||
let target = match request.number {
|
||||
Some(number) => named_target(github, &repository, number).await?,
|
||||
None => branch_target(github, cwd, &repository).await?,
|
||||
};
|
||||
Ok((repository, target))
|
||||
}
|
||||
|
||||
/// The pull request number and `-R` repository in `args`. Anything else is refused rather than
|
||||
/// dropped: an argument skipped in silence answers a different question than the one asked.
|
||||
fn parse_request(args: &[String]) -> Result<Request, String> {
|
||||
let mut request = Request { number: None, repository: None };
|
||||
let mut args = args.iter().map(String::as_str);
|
||||
while let Some(arg) = args.next() {
|
||||
if let Some(slug) = repo_flag(arg, &mut args)? {
|
||||
request.repository = Some(repository_from_slug(slug)?);
|
||||
} else if request.number.replace(pull_request_number(arg)?).is_some() {
|
||||
return Err("`checks` reads one pull request at a time.".into());
|
||||
}
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
/// The repository `arg` names when it is `-R`/`--repo` (taking the next argument) or `--repo=`.
|
||||
fn repo_flag<'a>(
|
||||
arg: &'a str,
|
||||
rest: &mut impl Iterator<Item = &'a str>,
|
||||
) -> Result<Option<&'a str>, String> {
|
||||
match arg {
|
||||
"-R" | "--repo" => {
|
||||
rest.next().map(Some).ok_or_else(|| "`-R` needs a repository: `-R owner/name`.".into())
|
||||
}
|
||||
other => Ok(other.strip_prefix("--repo=")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `arg` as a pull request number, `#` or not; a flag `checks` doesn't know is refused by name.
|
||||
fn pull_request_number(arg: &str) -> Result<u64, String> {
|
||||
if arg.starts_with('-') {
|
||||
return Err(format!(
|
||||
"`checks` doesn't take `{arg}`. It takes a pull request number, and `-R owner/name` \
|
||||
for a repository other than this checkout's."
|
||||
));
|
||||
}
|
||||
let number = arg.trim_start_matches('#');
|
||||
number.parse().map_err(|_| format!("`{number}` is not a pull request number."))
|
||||
}
|
||||
|
||||
/// The repository `owner/name` names on github.com, or `host/owner/name` on another host, as
|
||||
/// `gh -R` reads it.
|
||||
fn repository_from_slug(slug: &str) -> Result<Repository, String> {
|
||||
let (host, owner, name) = slug_parts(slug)
|
||||
.ok_or_else(|| format!("`{slug}` is not a repository: `-R` takes owner/name."))?;
|
||||
Ok(Repository {
|
||||
host: host.to_ascii_lowercase(),
|
||||
owner: owner.to_string(),
|
||||
name: name.to_string(),
|
||||
// Reading a pull request's checks never consults either, so neither is looked up
|
||||
default_branch: String::new(),
|
||||
remote: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Host, owner and name, when each part of `slug` is one GitHub would accept.
|
||||
fn slug_parts(slug: &str) -> Option<(&str, &str, &str)> {
|
||||
let valid = |part: &str| {
|
||||
!part.is_empty()
|
||||
&& part.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
|
||||
};
|
||||
let parts: Vec<&str> = slug.split('/').collect();
|
||||
let (host, owner, name) = match parts.as_slice() {
|
||||
[owner, name] => ("github.com", *owner, *name),
|
||||
[host, owner, name] => (*host, *owner, *name),
|
||||
_ => return None,
|
||||
};
|
||||
[host, owner, name].into_iter().all(valid).then_some((host, owner, name))
|
||||
}
|
||||
|
||||
/// Pull request `number`'s head, by its number and title.
|
||||
async fn named_target(
|
||||
github: &(impl PullRequests + ?Sized),
|
||||
repository: &Repository,
|
||||
number: u64,
|
||||
) -> Result<Target, String> {
|
||||
let pr = github.pull_request(repository, number).await.map_err(|e| failure(&e))?;
|
||||
Ok(Target {
|
||||
oid: pr.head_oid,
|
||||
name: format!("#{} · {}", pr.number, luxe_core::github::untrusted(&pr.title, 120)),
|
||||
pending: Some(pr.checks.pending),
|
||||
})
|
||||
}
|
||||
|
||||
/// The branch's pull request head, or `HEAD` when there is no pull request to ask about.
|
||||
async fn branch_target(
|
||||
github: &(impl Branches + ?Sized),
|
||||
cwd: &Path,
|
||||
repository: &luxe_core::github::Repository,
|
||||
repository: &Repository,
|
||||
) -> Result<Target, String> {
|
||||
let head = luxe_core::github::branch_head(cwd).await;
|
||||
if let Some(head) = head {
|
||||
|
||||
@@ -108,7 +108,8 @@ fn a_short_oid_is_seven_characters_or_all_of_it() {
|
||||
assert_eq!(short("abc"), "abc");
|
||||
}
|
||||
|
||||
/// A GitHub double with one pull request, #7, whose head has one failing Actions job.
|
||||
/// A GitHub double for this checkout's `me/app`, whose pull request #7 has one failing Actions job,
|
||||
/// and for `other/site`, whose #19 has one too: reachable only by naming that repository.
|
||||
struct Scripted {
|
||||
signed_in: bool,
|
||||
/// Whether the branch has a pull request
|
||||
@@ -148,15 +149,17 @@ impl luxe_core::github::Discovery for Scripted {
|
||||
impl luxe_core::github::PullRequests for Scripted {
|
||||
async fn pull_request(
|
||||
&self,
|
||||
_: &luxe_core::github::Repository,
|
||||
repository: &luxe_core::github::Repository,
|
||||
number: u64,
|
||||
) -> Result<luxe_core::github::PullRequest, GitHubError> {
|
||||
if number != 7 {
|
||||
return Err(GitHubError::NotFound);
|
||||
}
|
||||
let (title, head_oid) = match (repository.slug().as_str(), number) {
|
||||
("me/app", 7) => ("Topic", "7777777aaaa"),
|
||||
("other/site", 19) => ("Site", "1919191bbbb"),
|
||||
_ => return Err(GitHubError::NotFound),
|
||||
};
|
||||
Ok(luxe_core::github::PullRequest {
|
||||
number: 7,
|
||||
title: "Topic".into(),
|
||||
number,
|
||||
title: title.into(),
|
||||
body: String::new(),
|
||||
url: String::new(),
|
||||
author: luxe_core::github::Author { login: "me".into(), bot: false },
|
||||
@@ -165,7 +168,7 @@ impl luxe_core::github::PullRequests for Scripted {
|
||||
base_ref: "main".into(),
|
||||
base_oid: "b".into(),
|
||||
head_ref: "topic".into(),
|
||||
head_oid: "7777777aaaa".into(),
|
||||
head_oid: head_oid.into(),
|
||||
cross_repository: false,
|
||||
review_decision: None,
|
||||
checks: luxe_core::github::CheckRollup { pending: 1, ..Default::default() },
|
||||
@@ -261,14 +264,17 @@ impl luxe_core::github::Branches for Scripted {
|
||||
impl luxe_core::github::Checks for Scripted {
|
||||
async fn failing_checks(
|
||||
&self,
|
||||
_: &luxe_core::github::Repository,
|
||||
repository: &luxe_core::github::Repository,
|
||||
head_oid: &str,
|
||||
log_tail: usize,
|
||||
) -> Result<Vec<FailingCheck>, GitHubError> {
|
||||
assert_eq!(log_tail, LOG_TAIL);
|
||||
if head_oid != "7777777aaaa" {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let owner = match head_oid {
|
||||
"7777777aaaa" => "me/app",
|
||||
"1919191bbbb" => "other/site",
|
||||
_ => return Ok(Vec::new()),
|
||||
};
|
||||
assert_eq!(repository.slug(), owner, "checks are read where the pull request lives");
|
||||
Ok(vec![check("test", CheckLog::NotRead)])
|
||||
}
|
||||
}
|
||||
@@ -292,6 +298,67 @@ async fn a_named_pull_request_reads_its_head() {
|
||||
assert!(error.contains("gh auth login"), "{error}");
|
||||
}
|
||||
|
||||
/// The break this catches: `-R` dropped in silence, which reads the same number in this checkout's
|
||||
/// repository instead, a different pull request entirely or none at all.
|
||||
#[tokio::test]
|
||||
async fn a_repository_named_with_r_is_the_one_read() {
|
||||
let github = Scripted { signed_in: true, pull_request: true };
|
||||
let spellings: [&[&str]; 3] = [
|
||||
&["19", "-R", "other/site"],
|
||||
&["--repo", "other/site", "#19"],
|
||||
&["--repo=other/site", "19"],
|
||||
];
|
||||
for args in spellings {
|
||||
let args: Vec<String> = args.iter().map(|arg| arg.to_string()).collect();
|
||||
let text = checks(&github, Path::new("."), &args).await.unwrap();
|
||||
assert!(text.starts_with("1 check failing on other/site#19 · Site (1919191)."), "{text}");
|
||||
}
|
||||
|
||||
let error = checks(&github, Path::new("."), &["19".into()]).await.unwrap_err();
|
||||
assert!(error.contains("never pushed has no checks"), "#19 isn't this checkout's: {error}");
|
||||
}
|
||||
|
||||
/// The break this catches: an argument `checks` doesn't understand skipped rather than refused.
|
||||
#[tokio::test]
|
||||
async fn an_argument_checks_does_not_take_is_refused() {
|
||||
let github = Scripted { signed_in: true, pull_request: true };
|
||||
let refused = |args: &[&str]| {
|
||||
let args: Vec<String> = args.iter().map(|arg| arg.to_string()).collect();
|
||||
let github = &github;
|
||||
async move { checks(github, Path::new("."), &args).await.unwrap_err() }
|
||||
};
|
||||
|
||||
let error = refused(&["7", "--json"]).await;
|
||||
assert!(error.contains("doesn't take `--json`"), "{error}");
|
||||
let error = refused(&["7", "8"]).await;
|
||||
assert!(error.contains("one pull request at a time"), "{error}");
|
||||
let error = refused(&["7", "-R"]).await;
|
||||
assert!(error.contains("`-R` needs a repository"), "{error}");
|
||||
let error = refused(&["-R", "other/site"]).await;
|
||||
assert_eq!(error, REPO_NEEDS_NUMBER, "no branch here belongs to that repository");
|
||||
let error = refused(&["7", "-R", "luxe"]).await;
|
||||
assert!(error.contains("`luxe` is not a repository"), "{error}");
|
||||
}
|
||||
|
||||
/// `-R` reads a repository the way `gh -R` does, and refuses what GitHub couldn't name.
|
||||
#[test]
|
||||
fn a_repository_is_owner_and_name_or_host_owner_and_name() {
|
||||
let on_github = repository_from_slug("evanwhittaker/luxe").unwrap();
|
||||
assert_eq!(
|
||||
(on_github.host.as_str(), on_github.slug().as_str()),
|
||||
("github.com", "evanwhittaker/luxe")
|
||||
);
|
||||
let elsewhere = repository_from_slug("GHE.example.com/team/app.rs").unwrap();
|
||||
assert_eq!(
|
||||
(elsewhere.host.as_str(), elsewhere.slug().as_str()),
|
||||
("ghe.example.com", "team/app.rs")
|
||||
);
|
||||
|
||||
for slug in ["luxe", "a/b/c/d", "owner/", "/name", "my owner/app", "owner/app?x=1", ""] {
|
||||
assert!(repository_from_slug(slug).is_err(), "`{slug}` names no repository");
|
||||
}
|
||||
}
|
||||
|
||||
/// With nothing named, the branch's own pull request is the one read.
|
||||
#[tokio::test]
|
||||
async fn the_branchs_pull_request_is_the_default() {
|
||||
|
||||
Reference in New Issue
Block a user