Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
386
crates/luxe-tools/src/git/args.rs
Normal file
386
crates/luxe-tools/src/git/args.rs
Normal file
@@ -0,0 +1,386 @@
|
||||
//! Argument normalization for `git commit` — permissive at the edge, strict in the core.
|
||||
//!
|
||||
//! The tool's real invariant is that git receives a message from somewhere. *Where the caller put
|
||||
//! it* is not one: a model that sends `args: ["-m", "…"]` instead of `message` has said what it
|
||||
//! means, and refusing it costs failed calls and a fallback to `bash`.
|
||||
//!
|
||||
//! So: lift the message out of whichever spelling arrived, then be strict about what actually
|
||||
//! matters. The schema still advertises exactly one spelling, so nothing here is a second contract
|
||||
//! to keep.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// Keys accepted for the commit message, canonical first.
|
||||
const MESSAGE_KEYS: [&str; 4] = ["message", "msg", "commit_message", "commitMessage"];
|
||||
|
||||
/// Flags that hand git a message from somewhere other than `-m`, so a call carrying one needs no
|
||||
/// `message` of its own.
|
||||
///
|
||||
/// Verified against git rather than assumed: each of these commits without `-m`, and combining one
|
||||
/// with `-m` is an error git refuses outright ("Only one of -c/-C/-F/--fixup can be used"), so
|
||||
/// demanding a message unconditionally would put them out of reach.
|
||||
const MESSAGE_SOURCES: [&str; 9] = [
|
||||
"--no-edit",
|
||||
"-F",
|
||||
"--file",
|
||||
"-C",
|
||||
"--reuse-message",
|
||||
"-c",
|
||||
"--reedit-message",
|
||||
"--fixup",
|
||||
"--squash",
|
||||
];
|
||||
|
||||
/// Short `git commit` flags that take no value, and so may cluster ahead of an `m` (`-am`).
|
||||
///
|
||||
/// An allow-list rather than "any letter", because `-F`, `-C`, `-c` and `-S` all take one: reading
|
||||
/// `-Fm` as a message flag would silently reinterpret "take the message from the file named `m`".
|
||||
const CLUSTERABLE: &str = "asnevqoip";
|
||||
|
||||
/// The canonical shape, repeated on every failure so a correction needs no second look.
|
||||
const USAGE: &str = "Expected: {\"action\": \"commit\", \"message\": \"Subject line\\n\\nOptional \
|
||||
body.\"}";
|
||||
|
||||
/// Why a commit call could not be understood, with enough detail to fix it in one move.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum CommitError {
|
||||
/// Nothing in the call carries a message, and no flag supplies one either.
|
||||
NoMessage {
|
||||
/// Top-level keys the call actually arrived with.
|
||||
received: Vec<String>,
|
||||
},
|
||||
/// `--amend` with no new message and no `--no-edit`, which git can only resolve by opening an
|
||||
/// editor there is nobody to type into.
|
||||
AmendNeedsNoEdit,
|
||||
}
|
||||
|
||||
impl CommitError {
|
||||
/// A message that names what arrived, what was expected, and the shape to send.
|
||||
pub(crate) fn message(&self) -> String {
|
||||
match self {
|
||||
Self::NoMessage { received } => format!(
|
||||
"Error: no commit message. Received keys: {}. Pass it as `message` — `args` is for \
|
||||
git's other flags, so a message put there is a flag git does not have.\n{USAGE}\n\
|
||||
A commit that takes its message from elsewhere needs no `message`: \
|
||||
`--amend --no-edit`, `-F <file>`, `-C <commit>`, `--fixup=<commit>`.",
|
||||
render_keys(received)
|
||||
),
|
||||
Self::AmendNeedsNoEdit => format!(
|
||||
"Error: `--amend` with no message. Add `--no-edit` to keep the existing one, or \
|
||||
pass `message` to replace it.\nExpected: {{\"action\": \"commit\", \"args\": \
|
||||
[\"--amend\", \"--no-edit\"]}}\n{USAGE}"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The full argument list for a `commit` call, starting at `commit`.
|
||||
///
|
||||
/// `extra` is the call's `args` array, already extracted.
|
||||
pub(crate) fn commit_args(call: &Value, extra: &[String]) -> Result<Vec<String>, CommitError> {
|
||||
// The advertised spelling wins outright, and `args` then passes through untouched: a second
|
||||
// `-m` there is git's own way of writing a second paragraph, and lifting it out would quietly
|
||||
// drop what the caller asked for.
|
||||
if let Some(message) = first_string(call, &MESSAGE_KEYS) {
|
||||
return Ok(assemble(Some(message), extra.to_vec()));
|
||||
}
|
||||
|
||||
let (lifted, rest) = lift_message_flag(extra);
|
||||
if let Some(message) = lifted {
|
||||
return Ok(assemble(Some(message), rest));
|
||||
}
|
||||
|
||||
// A lone argument that is not a flag can only be the message. Git would read it as a pathspec,
|
||||
// and a pathspec commit with no message anywhere has nowhere to get one from — the editor is
|
||||
// closed — so the reading that lets the call succeed is the only one worth taking.
|
||||
if let [only] = rest.as_slice() {
|
||||
if !only.starts_with('-') {
|
||||
return Ok(assemble(Some(only.clone()), Vec::new()));
|
||||
}
|
||||
}
|
||||
|
||||
if carries_its_own_message(&rest) {
|
||||
return Ok(assemble(None, rest));
|
||||
}
|
||||
if rest.iter().any(|arg| arg == "--amend") {
|
||||
return Err(CommitError::AmendNeedsNoEdit);
|
||||
}
|
||||
Err(CommitError::NoMessage { received: keys_of(call) })
|
||||
}
|
||||
|
||||
/// Put the message where git wants it, ahead of whatever else the caller sent.
|
||||
fn assemble(message: Option<String>, rest: Vec<String>) -> Vec<String> {
|
||||
let mut args = vec!["commit".to_string()];
|
||||
if let Some(message) = message {
|
||||
args.push("-m".to_string());
|
||||
args.push(message);
|
||||
}
|
||||
args.extend(rest);
|
||||
args
|
||||
}
|
||||
|
||||
/// Pull a `-m`/`--message` value out of a raw git argument list, returning it and what is left.
|
||||
///
|
||||
/// Every spelling git itself takes: `-m x`, `-mx`, `-am x`, `--message x`, `--message=x`. Only the
|
||||
/// first is lifted — a later `-m` is a second paragraph and stays where it is.
|
||||
fn lift_message_flag(args: &[String]) -> (Option<String>, Vec<String>) {
|
||||
let mut message: Option<String> = None;
|
||||
let mut rest = Vec::with_capacity(args.len());
|
||||
let mut iter = args.iter();
|
||||
|
||||
while let Some(arg) = iter.next() {
|
||||
if message.is_some() {
|
||||
rest.push(arg.clone());
|
||||
continue;
|
||||
}
|
||||
if arg == "--message" {
|
||||
message = iter.next().cloned();
|
||||
continue;
|
||||
}
|
||||
if let Some(value) = arg.strip_prefix("--message=") {
|
||||
message = Some(value.to_string());
|
||||
continue;
|
||||
}
|
||||
match split_short_message(arg) {
|
||||
Some((companions, attached)) => {
|
||||
if let Some(companions) = companions {
|
||||
rest.push(companions);
|
||||
}
|
||||
message = match attached {
|
||||
Some(value) => Some(value),
|
||||
None => iter.next().cloned(),
|
||||
};
|
||||
}
|
||||
None => rest.push(arg.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
(message, rest)
|
||||
}
|
||||
|
||||
/// Split a short-flag cluster carrying `m` into the flags beside it and any attached value.
|
||||
///
|
||||
/// `-m` → `(None, None)`, `-am` → `(Some("-a"), None)`, `-mwip` → `(None, Some("wip"))`. Anything
|
||||
/// that is not a `git commit` message flag returns `None` and is left alone.
|
||||
fn split_short_message(arg: &str) -> Option<(Option<String>, Option<String>)> {
|
||||
let cluster = arg.strip_prefix('-').filter(|rest| !rest.starts_with('-'))?;
|
||||
let at = cluster.find('m')?;
|
||||
let (companions, attached) = cluster.split_at(at);
|
||||
if !companions.chars().all(|flag| CLUSTERABLE.contains(flag)) {
|
||||
return None;
|
||||
}
|
||||
let attached = attached.strip_prefix('m').filter(|value| !value.is_empty());
|
||||
let companions = (!companions.is_empty()).then(|| format!("-{companions}"));
|
||||
Some((companions, attached.map(ToOwned::to_owned)))
|
||||
}
|
||||
|
||||
/// Whether these arguments already tell git where the message comes from.
|
||||
fn carries_its_own_message(args: &[String]) -> bool {
|
||||
args.iter().any(|arg| {
|
||||
MESSAGE_SOURCES.iter().any(|flag| match flag.strip_prefix("--") {
|
||||
// A long flag attaches its value with `=`: `--fixup=HEAD`.
|
||||
Some(_) => arg == flag || arg.strip_prefix(flag).is_some_and(|v| v.starts_with('=')),
|
||||
// A short one just runs into it: `-CHEAD`. No long flag can be caught here, because a
|
||||
// long flag's second character is always `-` and no short flag's is.
|
||||
None => arg.starts_with(flag),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn keys_of(value: &Value) -> Vec<String> {
|
||||
value.as_object().map(|map| map.keys().cloned().collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn render_keys(keys: &[String]) -> String {
|
||||
if keys.is_empty() {
|
||||
return "(none)".to_string();
|
||||
}
|
||||
keys.join(", ")
|
||||
}
|
||||
|
||||
/// The first alias present and non-blank.
|
||||
///
|
||||
/// Blank is not a message: git refuses an empty one ("Aborting commit due to empty commit
|
||||
/// message"), so accepting it here would only move the failure somewhere less legible.
|
||||
fn first_string(value: &Value, keys: &[&str]) -> Option<String> {
|
||||
keys.iter()
|
||||
.find_map(|key| value.get(*key).and_then(Value::as_str))
|
||||
.filter(|text| !text.trim().is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
/// The full `gh` argument list for a `pr` or `issue` call, defaulting to listing them.
|
||||
///
|
||||
/// Every argument is forwarded: dropping them would send `pr create --title … --body …` to `gh` as
|
||||
/// a bare `gh pr create`, which does not fail loudly but *prompts* for the title it was already
|
||||
/// handed, from behind a TUI that owns the screen.
|
||||
pub(super) fn gh_args(kind: &str, requested: &[String]) -> Vec<String> {
|
||||
let mut args = vec![kind.to_string()];
|
||||
if requested.is_empty() {
|
||||
args.push("list".to_string());
|
||||
} else {
|
||||
args.extend(requested.iter().cloned());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
/// Whether a `pr` call is trying to open a pull request, as opposed to reading about one.
|
||||
///
|
||||
/// Only `create` has a precondition the caller can get wrong, so only `create` gets the preflight.
|
||||
pub(super) fn is_pr_create(requested: &[String]) -> bool {
|
||||
requested.first().is_some_and(|subaction| subaction == "create")
|
||||
}
|
||||
|
||||
/// The full `git stash` argument list, defaulting to `stash push`.
|
||||
///
|
||||
/// Every argument is forwarded, as in [`gh_args`]: a dropped `-m wip` loses the label that was the
|
||||
/// entire point of naming the stash, and any way to find the entry again.
|
||||
pub(super) fn stash_args(requested: &[String]) -> Vec<String> {
|
||||
let mut args = vec!["stash".to_string()];
|
||||
if requested.is_empty() {
|
||||
args.push("push".to_string());
|
||||
} else {
|
||||
args.extend(requested.iter().cloned());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn owned(args: &[&str]) -> Vec<String> {
|
||||
args.iter().map(|arg| (*arg).to_string()).collect()
|
||||
}
|
||||
|
||||
/// The shapes a real session produced, all of which were refused.
|
||||
///
|
||||
/// Taken from a transcript, not imagined: the model tried `["-m", msg]`, then `[msg]`, got
|
||||
/// "'message' argument is required for commit" both times, and went to `bash`.
|
||||
#[test]
|
||||
fn every_spelling_a_model_reaches_for_becomes_the_same_commit() {
|
||||
let expected = owned(&["commit", "-m", "Animate the loading spinner"]);
|
||||
let cases = [
|
||||
json!({"action": "commit", "message": "Animate the loading spinner"}),
|
||||
json!({"action": "commit", "args": ["-m", "Animate the loading spinner"]}),
|
||||
json!({"action": "commit", "args": ["Animate the loading spinner"]}),
|
||||
json!({"action": "commit", "args": ["--message", "Animate the loading spinner"]}),
|
||||
json!({"action": "commit", "args": ["--message=Animate the loading spinner"]}),
|
||||
json!({"action": "commit", "args": ["-mAnimate the loading spinner"]}),
|
||||
];
|
||||
for call in cases {
|
||||
let extra = extra_of(&call);
|
||||
assert_eq!(commit_args(&call, &extra).unwrap(), expected, "{call}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A clustered `-am` keeps the flag it was clustered with.
|
||||
#[test]
|
||||
fn a_short_cluster_surrenders_the_message_and_keeps_its_flags() {
|
||||
let call = json!({"action": "commit", "args": ["-am", "wip"]});
|
||||
assert_eq!(
|
||||
commit_args(&call, &extra_of(&call)).unwrap(),
|
||||
owned(&["commit", "-m", "wip", "-a"])
|
||||
);
|
||||
|
||||
// `-F` takes a value, so `-Fm` is the file named `m` and must survive untouched.
|
||||
assert_eq!(split_short_message("-Fm"), None);
|
||||
assert_eq!(split_short_message("-Sm"), None);
|
||||
assert_eq!(split_short_message("--amend"), None);
|
||||
assert_eq!(split_short_message("-a"), None);
|
||||
}
|
||||
|
||||
/// The advertised spelling wins, and a `-m` in `args` stays put rather than being dropped —
|
||||
/// repeated `-m` is how git writes a second paragraph.
|
||||
#[test]
|
||||
fn the_canonical_spelling_wins_without_discarding_the_other() {
|
||||
let call = json!({"action": "commit", "message": "subject", "args": ["-m", "body"]});
|
||||
assert_eq!(
|
||||
commit_args(&call, &extra_of(&call)).unwrap(),
|
||||
owned(&["commit", "-m", "subject", "-m", "body"])
|
||||
);
|
||||
}
|
||||
|
||||
/// Flags git accepts a message *from* need no message of their own. Every one of these was
|
||||
/// unreachable while `message` was unconditionally required.
|
||||
#[test]
|
||||
fn a_commit_that_names_its_own_message_source_needs_no_message() {
|
||||
for args in [
|
||||
vec!["--amend", "--no-edit"],
|
||||
vec!["-F", "msg.txt"],
|
||||
vec!["--file=msg.txt"],
|
||||
vec!["-C", "HEAD"],
|
||||
vec!["--reuse-message=HEAD"],
|
||||
vec!["--fixup=HEAD"],
|
||||
vec!["--squash", "HEAD"],
|
||||
// Attached to the flag, which is how git spells these as often as not.
|
||||
vec!["-Fmsg.txt"],
|
||||
vec!["-CHEAD"],
|
||||
vec!["-cHEAD"],
|
||||
] {
|
||||
let call = json!({"action": "commit", "args": args});
|
||||
let extra = extra_of(&call);
|
||||
let built = commit_args(&call, &extra).unwrap_or_else(|e| panic!("{args:?}: {e:?}"));
|
||||
assert_eq!(built[0], "commit");
|
||||
assert!(!built.contains(&"-m".to_string()), "{args:?} got an -m it did not ask for");
|
||||
}
|
||||
}
|
||||
|
||||
/// `--amend` alone would send git to an editor nobody can reach, so it is refused *here*, where
|
||||
/// the reply can name the two ways out.
|
||||
#[test]
|
||||
fn amending_without_a_message_says_which_two_things_would_work() {
|
||||
let call = json!({"action": "commit", "args": ["--amend"]});
|
||||
let error = commit_args(&call, &extra_of(&call)).unwrap_err();
|
||||
assert_eq!(error, CommitError::AmendNeedsNoEdit);
|
||||
let text = error.message();
|
||||
assert!(text.contains("--no-edit"), "{text}");
|
||||
assert!(text.contains("message"), "{text}");
|
||||
}
|
||||
|
||||
/// The refusal that started this: it named the key and never the shape.
|
||||
#[test]
|
||||
fn a_refusal_shows_the_call_that_would_have_worked() {
|
||||
let call = json!({"action": "commit", "args": ["-a"]});
|
||||
let error = commit_args(&call, &extra_of(&call)).unwrap_err();
|
||||
let text = error.message();
|
||||
|
||||
assert!(text.contains("action, args"), "names what arrived: {text}");
|
||||
assert!(text.contains("\"message\""), "and the shape to send: {text}");
|
||||
assert!(text.contains("--amend --no-edit"), "and the way out that needs none: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blank_message_is_no_message() {
|
||||
for blank in ["", " ", "\n"] {
|
||||
let call = json!({"action": "commit", "message": blank});
|
||||
assert!(commit_args(&call, &[]).is_err(), "{blank:?} is not a commit message");
|
||||
}
|
||||
}
|
||||
|
||||
/// Flags beside the message keep their order and their place after it.
|
||||
#[test]
|
||||
fn other_flags_survive_in_order() {
|
||||
let call = json!({"action": "commit", "message": "m", "args": ["--amend", "--", "a.rs"]});
|
||||
assert_eq!(
|
||||
commit_args(&call, &extra_of(&call)).unwrap(),
|
||||
owned(&["commit", "-m", "m", "--amend", "--", "a.rs"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_call_reports_no_keys_rather_than_an_empty_list() {
|
||||
let error = commit_args(&json!({}), &[]).unwrap_err();
|
||||
assert!(error.message().contains("(none)"), "{}", error.message());
|
||||
}
|
||||
|
||||
fn extra_of(call: &Value) -> Vec<String> {
|
||||
call.get("args")
|
||||
.and_then(|value| value.as_array())
|
||||
.map(|values| {
|
||||
values.iter().filter_map(|v| v.as_str().map(String::from)).collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
191
crates/luxe-tools/src/git/checks.rs
Normal file
191
crates/luxe-tools/src/git/checks.rs
Normal file
@@ -0,0 +1,191 @@
|
||||
//! `git` `checks` — why CI is failing, bounded.
|
||||
//!
|
||||
//! `gh run view --log-failed` prints every line of every failing step: 3,671 lines for one Clippy
|
||||
//! step on luxe-dev, with the error in the last dozen. This reads the same logs through GitHub
|
||||
//! and keeps the tail of each failing step, says how much it left out, and also lists the failing
|
||||
//! checks that are not Actions jobs at all — a commit status from another CI, which that command
|
||||
//! 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,
|
||||
};
|
||||
use std::path::Path;
|
||||
|
||||
/// Lines kept from the end of each failing step's log.
|
||||
pub(super) const LOG_TAIL: usize = 30;
|
||||
|
||||
/// Longest the whole answer may run, in lines, whatever the number of failures.
|
||||
pub(super) const MAX_LINES: usize = 200;
|
||||
|
||||
/// The commit whose checks were read, and how it was chosen.
|
||||
struct Target {
|
||||
/// Tip of what was asked about
|
||||
oid: String,
|
||||
/// What to call it: the pull request, or the commit when there is none
|
||||
name: String,
|
||||
/// Checks still running, when the pull request said
|
||||
pending: Option<usize>,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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 failing = github
|
||||
.failing_checks(&repository, &target.oid, LOG_TAIL)
|
||||
.await
|
||||
.map_err(|error| failure(&error))?;
|
||||
Ok(render(&target, &failing))
|
||||
}
|
||||
|
||||
/// 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,
|
||||
) -> Result<Target, String> {
|
||||
let head = luxe_core::github::branch_head(cwd).await;
|
||||
if let Some(head) = head {
|
||||
let status = github.branch_status(repository, &head).await.map_err(|e| failure(&e))?;
|
||||
if let Some(pr) = status.pull_request {
|
||||
return Ok(Target {
|
||||
oid: pr.head_oid,
|
||||
name: format!("#{} · {}", pr.number, pr.title),
|
||||
pending: Some(pr.checks.pending),
|
||||
});
|
||||
}
|
||||
}
|
||||
let oid = head_commit(cwd).await.ok_or("This checkout has no commit to read checks for.")?;
|
||||
let name = format!("{} (this branch has no pull request)", short(&oid));
|
||||
Ok(Target { oid, name, pending: None })
|
||||
}
|
||||
|
||||
async fn head_commit(cwd: &Path) -> Option<String> {
|
||||
let program =
|
||||
luxe_core::program::resolve("git").unwrap_or_else(|| std::path::PathBuf::from("git"));
|
||||
let command = luxe_core::program::captured_command(program, &["rev-parse", "HEAD"], cwd);
|
||||
let output =
|
||||
luxe_core::program::run_bounded(command, std::time::Duration::from_secs(10)).await.ok()?;
|
||||
let oid = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
(output.status.success() && !oid.is_empty()).then_some(oid)
|
||||
}
|
||||
|
||||
/// The answer: each failing check, where to read it, and the end of each failing step.
|
||||
fn render(target: &Target, failing: &[FailingCheck]) -> String {
|
||||
let running = match target.pending {
|
||||
Some(0) | None => String::new(),
|
||||
Some(1) => " 1 check is still running.".to_string(),
|
||||
Some(count) => format!(" {count} checks are still running."),
|
||||
};
|
||||
if failing.is_empty() {
|
||||
return format!("No checks are failing on {}.{running}", target.name);
|
||||
}
|
||||
let count = match failing.len() {
|
||||
1 => "1 check".to_string(),
|
||||
count => format!("{count} checks"),
|
||||
};
|
||||
let mut lines =
|
||||
vec![format!("{count} failing on {} ({}).{running}", target.name, short(&target.oid))];
|
||||
for check in failing {
|
||||
lines.push(String::new());
|
||||
let summary = check.summary.as_deref().map(|text| format!(": {text}")).unwrap_or_default();
|
||||
lines.push(format!("{} — {}{summary}", check.name, check.outcome));
|
||||
if !check.url.is_empty() {
|
||||
lines.push(format!(" {}", check.url));
|
||||
}
|
||||
match &check.log {
|
||||
CheckLog::NotActions => {
|
||||
lines.push(
|
||||
" Not a GitHub Actions job, so there is no log here; the link has it.".into(),
|
||||
);
|
||||
}
|
||||
CheckLog::NotRead => lines.push(
|
||||
" Log not read: only the first few failing jobs are. The link, or `gh run view \
|
||||
--job <id> --log-failed`, has it."
|
||||
.into(),
|
||||
),
|
||||
CheckLog::Unreadable(reason) => lines.push(format!(" Log unreadable: {reason}")),
|
||||
CheckLog::Steps(steps) if steps.is_empty() => {
|
||||
lines.push(" No failing step printed a log.".into());
|
||||
}
|
||||
CheckLog::Steps(steps) => {
|
||||
for step in steps {
|
||||
let name = match step.name.as_str() {
|
||||
"UNKNOWN STEP" => "the job's log (gh could not split it by step)".into(),
|
||||
name => format!("step \"{name}\""),
|
||||
};
|
||||
let shown = match (step.omitted, step.after) {
|
||||
(0, 0) => format!(" {name}:"),
|
||||
(omitted, 0) => format!(
|
||||
" {name}, last {} of {} lines:",
|
||||
step.tail.len(),
|
||||
step.tail.len() + omitted
|
||||
),
|
||||
(omitted, after) => format!(
|
||||
" {name}, the {} up to its last error, of {}:",
|
||||
match step.tail.len() {
|
||||
1 => "line".to_string(),
|
||||
count => format!("{count} lines"),
|
||||
},
|
||||
step.tail.len() + omitted + after
|
||||
),
|
||||
};
|
||||
lines.push(shown);
|
||||
lines.extend(step.tail.iter().map(|line| format!(" {line}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::output_limit::cap_lines(
|
||||
&lines.join("\n"),
|
||||
MAX_LINES,
|
||||
"lines of check output",
|
||||
"ask about one pull request at a time, or open a check's link",
|
||||
)
|
||||
}
|
||||
|
||||
/// What went wrong, as the sentence the model acts on.
|
||||
fn failure(error: &GitHubError) -> String {
|
||||
match error {
|
||||
GitHubError::NotInstalled => {
|
||||
"The GitHub CLI (`gh`) is not installed. Install it and run `gh auth login`.".into()
|
||||
}
|
||||
GitHubError::NotAuthenticated { .. } => {
|
||||
"The GitHub CLI is not signed in. The user needs to run `gh auth login`.".into()
|
||||
}
|
||||
GitHubError::NotGitHub => "This repository has no remote on GitHub.".into(),
|
||||
GitHubError::NotFound => {
|
||||
"GitHub has no such pull request or commit that this account can see; \
|
||||
a commit that was never pushed has no checks."
|
||||
.into()
|
||||
}
|
||||
GitHubError::RateLimited => {
|
||||
"GitHub's rate limit for this account is spent; it refills within the hour.".into()
|
||||
}
|
||||
other => format!("Could not read the checks: {other}."),
|
||||
}
|
||||
}
|
||||
|
||||
fn short(oid: &str) -> &str {
|
||||
oid.get(..7).unwrap_or(oid)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
344
crates/luxe-tools/src/git/checks/tests.rs
Normal file
344
crates/luxe-tools/src/git/checks/tests.rs
Normal file
@@ -0,0 +1,344 @@
|
||||
use super::*;
|
||||
use luxe_core::github::FailedStep;
|
||||
|
||||
fn target(pending: Option<usize>) -> Target {
|
||||
Target {
|
||||
oid: "1ee6ffe1e7cc5e51a79ec5df24e7e8db03f237b5".into(),
|
||||
name: "#119 · Bump getrandom".into(),
|
||||
pending,
|
||||
}
|
||||
}
|
||||
|
||||
fn check(name: &str, log: CheckLog) -> FailingCheck {
|
||||
FailingCheck {
|
||||
name: name.into(),
|
||||
outcome: "failure".into(),
|
||||
url: format!("https://github.com/o/r/actions/runs/1/job/{name}"),
|
||||
summary: None,
|
||||
log,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_failing_says_so_and_what_is_still_running() {
|
||||
assert_eq!(render(&target(Some(0)), &[]), "No checks are failing on #119 · Bump getrandom.");
|
||||
assert_eq!(
|
||||
render(&target(Some(2)), &[]),
|
||||
"No checks are failing on #119 · Bump getrandom. 2 checks are still running."
|
||||
);
|
||||
assert!(render(&target(Some(1)), &[]).ends_with("1 check is still running."));
|
||||
assert!(render(&target(None), &[]).ends_with("getrandom."));
|
||||
}
|
||||
|
||||
/// Each kind of failure says where its log is, and a cut tail says how much it left out.
|
||||
#[test]
|
||||
fn every_failure_says_where_its_log_is() {
|
||||
let steps = CheckLog::Steps(vec![FailedStep {
|
||||
name: "Clippy (deny warnings)".into(),
|
||||
tail: vec!["error[E0425]: cannot find function".into(), "##[error]exit 101".into()],
|
||||
omitted: 59,
|
||||
after: 0,
|
||||
}]);
|
||||
let failing = [
|
||||
check("clippy", steps),
|
||||
FailingCheck {
|
||||
summary: Some("#20260924.53 failed".into()),
|
||||
..check("Azure Pipelines CI", CheckLog::NotActions)
|
||||
},
|
||||
check("windows", CheckLog::Unreadable("HTTP 410: logs expired".into())),
|
||||
check("macos", CheckLog::NotRead),
|
||||
check("empty", CheckLog::Steps(Vec::new())),
|
||||
check(
|
||||
"short",
|
||||
CheckLog::Steps(vec![FailedStep {
|
||||
name: "Build".into(),
|
||||
tail: vec!["oops".into()],
|
||||
omitted: 0,
|
||||
after: 0,
|
||||
}]),
|
||||
),
|
||||
check(
|
||||
"whole",
|
||||
CheckLog::Steps(vec![FailedStep {
|
||||
name: "UNKNOWN STEP".into(),
|
||||
tail: vec!["##[error]exit 1".into()],
|
||||
omitted: 5_000,
|
||||
after: 40,
|
||||
}]),
|
||||
),
|
||||
];
|
||||
let text = render(&target(Some(1)), &failing);
|
||||
assert!(text.starts_with(
|
||||
"7 checks failing on #119 · Bump getrandom (1ee6ffe). 1 check is still running."
|
||||
));
|
||||
for expected in [
|
||||
"clippy — failure\n https://github.com/o/r/actions/runs/1/job/clippy",
|
||||
" step \"Clippy (deny warnings)\", last 2 of 61 lines:\n error[E0425]",
|
||||
"Azure Pipelines CI — failure: #20260924.53 failed",
|
||||
"Not a GitHub Actions job",
|
||||
"Log unreadable: HTTP 410: logs expired",
|
||||
"Log not read: only the first few",
|
||||
"No failing step printed a log.",
|
||||
" step \"Build\":\n oops",
|
||||
" the job's log (gh could not split it by step), the line up to its last error, of \
|
||||
5041:",
|
||||
] {
|
||||
assert!(text.contains(expected), "{expected:?} in:\n{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flood_of_failures_is_capped_and_says_so() {
|
||||
let tail: Vec<String> = (0..LOG_TAIL).map(|n| format!("line {n}")).collect();
|
||||
let failing: Vec<FailingCheck> = (0..20)
|
||||
.map(|n| {
|
||||
let step =
|
||||
FailedStep { name: "Test".into(), tail: tail.clone(), omitted: 900, after: 0 };
|
||||
check(&format!("job {n}"), CheckLog::Steps(vec![step]))
|
||||
})
|
||||
.collect();
|
||||
let text = render(&target(None), &failing);
|
||||
assert!(text.lines().count() <= MAX_LINES + 2, "{}", text.lines().count());
|
||||
assert!(text.contains("lines of check output"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_oid_is_seven_characters_or_all_of_it() {
|
||||
assert_eq!(short("1ee6ffe1e7cc"), "1ee6ffe");
|
||||
assert_eq!(short("abc"), "abc");
|
||||
}
|
||||
|
||||
/// A GitHub double with one pull request, #7, whose head has one failing Actions job.
|
||||
struct Scripted {
|
||||
signed_in: bool,
|
||||
/// Whether the branch has a pull request
|
||||
pull_request: bool,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl luxe_core::github::Discovery for Scripted {
|
||||
async fn account(&self, _: Option<&str>) -> Result<luxe_core::github::Account, GitHubError> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn repository(&self, _: &Path) -> Result<luxe_core::github::Repository, GitHubError> {
|
||||
if !self.signed_in {
|
||||
return Err(GitHubError::NotAuthenticated { host: None });
|
||||
}
|
||||
Ok(luxe_core::github::Repository {
|
||||
host: "github.com".into(),
|
||||
owner: "me".into(),
|
||||
name: "app".into(),
|
||||
default_branch: "main".into(),
|
||||
remote: Some("origin".into()),
|
||||
})
|
||||
}
|
||||
|
||||
async fn search(
|
||||
&self,
|
||||
_host: &str,
|
||||
_query: &str,
|
||||
_after: Option<&str>,
|
||||
) -> Result<luxe_core::github::SearchPage, GitHubError> {
|
||||
Ok(luxe_core::github::SearchPage::default())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl luxe_core::github::PullRequests for Scripted {
|
||||
async fn pull_request(
|
||||
&self,
|
||||
_: &luxe_core::github::Repository,
|
||||
number: u64,
|
||||
) -> Result<luxe_core::github::PullRequest, GitHubError> {
|
||||
if number != 7 {
|
||||
return Err(GitHubError::NotFound);
|
||||
}
|
||||
Ok(luxe_core::github::PullRequest {
|
||||
number: 7,
|
||||
title: "Topic".into(),
|
||||
body: String::new(),
|
||||
url: String::new(),
|
||||
author: luxe_core::github::Author { login: "me".into(), bot: false },
|
||||
draft: false,
|
||||
state: luxe_core::github::PullRequestState::Open,
|
||||
base_ref: "main".into(),
|
||||
base_oid: "b".into(),
|
||||
head_ref: "topic".into(),
|
||||
head_oid: "7777777aaaa".into(),
|
||||
cross_repository: false,
|
||||
review_decision: None,
|
||||
checks: luxe_core::github::CheckRollup { pending: 1, ..Default::default() },
|
||||
closing_issues: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn issue(
|
||||
&self,
|
||||
_: &luxe_core::github::Repository,
|
||||
_: u64,
|
||||
) -> Result<luxe_core::github::Issue, GitHubError> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn conversation(
|
||||
&self,
|
||||
|
||||
_repository: &luxe_core::github::Repository,
|
||||
|
||||
_number: u64,
|
||||
|
||||
_pull_request: bool,
|
||||
) -> Result<Vec<luxe_core::github::overview::ConversationEntry>, GitHubError> {
|
||||
unreachable!("this double does not read conversations")
|
||||
}
|
||||
|
||||
async fn issue_overview(
|
||||
&self,
|
||||
_repository: &luxe_core::github::Repository,
|
||||
_number: u64,
|
||||
) -> Result<luxe_core::github::overview::IssueOverview, GitHubError> {
|
||||
unreachable!("this double does not read overviews")
|
||||
}
|
||||
|
||||
async fn pull_request_overview(
|
||||
&self,
|
||||
_repository: &luxe_core::github::Repository,
|
||||
_number: u64,
|
||||
) -> Result<luxe_core::github::overview::PullRequestOverview, GitHubError> {
|
||||
unreachable!("this double does not read overviews")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl luxe_core::github::Branches for Scripted {
|
||||
async fn branch_status(
|
||||
&self,
|
||||
_: &luxe_core::github::Repository,
|
||||
head: &luxe_core::github::BranchHead,
|
||||
) -> Result<luxe_core::github::BranchStatus, GitHubError> {
|
||||
assert_eq!(head.name, "topic");
|
||||
if !self.pull_request {
|
||||
return Ok(luxe_core::github::BranchStatus { pull_request: None, rate_limit: None });
|
||||
}
|
||||
let pr = self.pull_request(&self.repository(Path::new("")).await?, 7).await?;
|
||||
Ok(luxe_core::github::BranchStatus {
|
||||
pull_request: Some(luxe_core::github::PullRequestStatus {
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
url: pr.url,
|
||||
state: pr.state,
|
||||
draft: false,
|
||||
review_decision: None,
|
||||
checks: pr.checks,
|
||||
unresolved_threads: 0,
|
||||
head_oid: pr.head_oid,
|
||||
stack: None,
|
||||
}),
|
||||
rate_limit: None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn pull_request_head(
|
||||
&self,
|
||||
_repository: &luxe_core::github::Repository,
|
||||
_number: u64,
|
||||
) -> Result<luxe_core::github::PullRequestHead, GitHubError> {
|
||||
unreachable!("this double reads no pull request heads")
|
||||
}
|
||||
|
||||
async fn merged_below(
|
||||
&self,
|
||||
_repository: &luxe_core::github::Repository,
|
||||
_number: u64,
|
||||
_base: &str,
|
||||
) -> Result<Option<luxe_core::restack::MergedBelow>, GitHubError> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl luxe_core::github::Checks for Scripted {
|
||||
async fn failing_checks(
|
||||
&self,
|
||||
_: &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());
|
||||
}
|
||||
Ok(vec![check("test", CheckLog::NotRead)])
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_named_pull_request_reads_its_head() {
|
||||
let github = Scripted { signed_in: true, pull_request: true };
|
||||
let text = checks(&github, Path::new("."), &["#7".into()]).await.unwrap();
|
||||
assert!(
|
||||
text.starts_with("1 check failing on #7 · Topic (7777777). 1 check is still running."),
|
||||
"{text}"
|
||||
);
|
||||
|
||||
let error = checks(&github, Path::new("."), &["seven".into()]).await.unwrap_err();
|
||||
assert!(error.contains("`seven` is not a pull request number"), "{error}");
|
||||
let error = checks(&github, Path::new("."), &["8".into()]).await.unwrap_err();
|
||||
assert!(error.contains("never pushed has no checks"), "{error}");
|
||||
let error = checks(&Scripted { signed_in: false, pull_request: true }, Path::new("."), &[])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.contains("gh auth login"), "{error}");
|
||||
}
|
||||
|
||||
/// With nothing named, the branch's own pull request is the one read.
|
||||
#[tokio::test]
|
||||
async fn the_branchs_pull_request_is_the_default() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let output = std::process::Command::new("git")
|
||||
.args(["init", "-q", "-b", "topic"])
|
||||
.current_dir(dir.path())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
let text =
|
||||
checks(&Scripted { signed_in: true, pull_request: true }, dir.path(), &[]).await.unwrap();
|
||||
assert!(text.starts_with("1 check failing on #7 · Topic"), "{text}");
|
||||
}
|
||||
|
||||
/// A branch with no pull request reads the checks on `HEAD`, and says it did.
|
||||
#[tokio::test]
|
||||
async fn without_a_pull_request_the_checks_on_head_are_read() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let git = |args: &[&str]| {
|
||||
let output =
|
||||
std::process::Command::new("git").args(args).current_dir(dir.path()).output().unwrap();
|
||||
assert!(output.status.success(), "{args:?}: {output:?}");
|
||||
String::from_utf8_lossy(&output.stdout).trim().to_string()
|
||||
};
|
||||
git(&["init", "-q", "-b", "topic"]);
|
||||
let github = Scripted { signed_in: true, pull_request: false };
|
||||
let error = checks(&github, dir.path(), &[]).await.unwrap_err();
|
||||
assert!(error.contains("no commit"), "{error}");
|
||||
|
||||
git(&["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "a"]);
|
||||
let head = git(&["rev-parse", "HEAD"]);
|
||||
let text = checks(&github, dir.path(), &[]).await.unwrap();
|
||||
assert_eq!(
|
||||
text,
|
||||
format!("No checks are failing on {} (this branch has no pull request).", &head[..7])
|
||||
);
|
||||
}
|
||||
|
||||
/// Against the real `gh` and luxe-dev's #119, whose getrandom bump failed three jobs: each
|
||||
/// comes back with the compiler's error at the end of its tail. `cargo test -- --ignored`.
|
||||
#[tokio::test]
|
||||
#[ignore = "needs a signed-in gh and the network"]
|
||||
async fn a_real_failed_run_ends_in_its_error() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let github = luxe_core::github::GhCli::new();
|
||||
let text = checks(&github, &root, &["119".into()]).await.unwrap();
|
||||
assert!(text.starts_with("1 check failing on #119"), "{text}");
|
||||
assert!(text.contains("##[error]Process completed with exit code"), "{text}");
|
||||
}
|
||||
103
crates/luxe-tools/src/git/failure.rs
Normal file
103
crates/luxe-tools/src/git/failure.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
//! Failures — what git's and `gh`'s own complaints say once a model has to act on them.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// Turn git's plumbing failure into something a model can act on.
|
||||
///
|
||||
/// Outside a repository, `git status` answers with "fatal: not a git repository … Stopping at
|
||||
/// filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)" and `git diff` prints its entire
|
||||
/// usage screen — twenty lines of flags in place of a fact. Neither tells a reader the one thing
|
||||
/// that matters: this directory has no version control, so stop asking it about history.
|
||||
///
|
||||
/// **Both streams, always.** Git puts a *fatal* on stderr and a *refusal* on stdout: a commit with
|
||||
/// nothing staged exits 1 having said "no changes added to commit" on stdout and nothing at all on
|
||||
/// stderr. Reading stderr alone turned the most common commit failure there is into "Git command
|
||||
/// failed (no output).", which names no cause and suggests no fix — so the model abandoned the
|
||||
/// tool and ran the same commit through `bash`, where git's own words were waiting.
|
||||
pub(super) fn explain_failure(stderr: &str, stdout: &str, cwd: &Path) -> String {
|
||||
let lowered = format!("{stderr}\n{stdout}").to_ascii_lowercase();
|
||||
if lowered.contains("not a git repository") {
|
||||
return format!(
|
||||
"Not a git repository: `{}` is not version controlled, so there is no status, diff, \
|
||||
history, or branch to read. Use `read`/`grep` for the files themselves.",
|
||||
luxe_core::paths::display(cwd)
|
||||
);
|
||||
}
|
||||
// Reached because run_git closes the editor off deliberately. Git's own reply names `-m` and
|
||||
// `-F`, which are not the arguments this tool takes.
|
||||
if lowered.contains("problem with the editor") {
|
||||
return "Git wanted an editor to write this commit message and there is nobody to type \
|
||||
into one. Pass `message`, or add `--no-edit` to reuse the existing message."
|
||||
.to_string();
|
||||
}
|
||||
// Git's own advice here names `git add` and `git commit -a`, which are command lines rather
|
||||
// than this tool's arguments. The three refusals are distinct: what to do about each depends
|
||||
// on whether anything changed at all, and whether git can see it.
|
||||
if lowered.contains("no changes added to commit") {
|
||||
return "Nothing is staged, so there is nothing to commit — the changes are in the working \
|
||||
tree only. Stage them first with `{\"action\": \"add\", \"args\": [\".\"]}`, or \
|
||||
commit every tracked change at once by adding `-a` to `args`."
|
||||
.to_string();
|
||||
}
|
||||
if lowered.contains("nothing added to commit but untracked files present") {
|
||||
return "Every change here is in a file git has never tracked, so a commit would be empty. \
|
||||
Add the new paths first with `{\"action\": \"add\", \"args\": [\".\"]}` — `-a` does \
|
||||
not pick up untracked files."
|
||||
.to_string();
|
||||
}
|
||||
if lowered.contains("nothing to commit") {
|
||||
return "The working tree is clean, so this change is already committed. Check \
|
||||
`{\"action\": \"log\"}` before making another one."
|
||||
.to_string();
|
||||
}
|
||||
let reported = [stderr.trim(), stdout.trim()]
|
||||
.into_iter()
|
||||
.filter(|stream| !stream.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
if reported.is_empty() {
|
||||
return "Git command failed (no output).".to_string();
|
||||
}
|
||||
// Anything else keeps git's own words, bounded — a usage dump is not an explanation.
|
||||
crate::output_limit::cap_lines(
|
||||
&format!("Git command failed: {reported}"),
|
||||
GIT_ERROR_MAX_LINES,
|
||||
"lines",
|
||||
"Run the command through `bash` if you need git's full output.",
|
||||
)
|
||||
}
|
||||
|
||||
/// Max lines of git's own error text passed through.
|
||||
pub(super) const GIT_ERROR_MAX_LINES: usize = 12;
|
||||
|
||||
/// Max lines of `gh`'s error text passed through.
|
||||
pub(super) const GH_ERROR_MAX_LINES: usize = 12;
|
||||
|
||||
/// Rewrite a `gh` failure that has a known cause into the sentence that fixes it.
|
||||
///
|
||||
/// `gh` reports these accurately but in its own vocabulary, and the useful half is often below the
|
||||
/// part a bounded result keeps. Which failure it was is decided by
|
||||
/// [`luxe_core::github::classify_failure`], the one reading of `gh`'s wording in the tree; this only
|
||||
/// picks the words. The rest is passed through untouched — guessing at an error nobody anticipated
|
||||
/// is how a tool starts lying about what went wrong.
|
||||
pub(super) fn explain_gh_failure(reported: &str) -> Option<&'static str> {
|
||||
use luxe_core::github::GitHubError;
|
||||
match luxe_core::github::classify_failure(reported, "") {
|
||||
GitHubError::NotAuthenticated { .. } => return Some(
|
||||
"the GitHub CLI is installed but not signed in — run `gh auth login` in a terminal \
|
||||
(it needs a browser or a device code, so the agent cannot do it for you)",
|
||||
),
|
||||
GitHubError::NotGitHub => {
|
||||
return Some(
|
||||
"this repository has no remote on a GitHub host, so there are no pull requests \
|
||||
for `gh` to work with — `git remote -v` shows where it points",
|
||||
)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let lower = reported.to_lowercase();
|
||||
if lower.contains("no pull requests match") || lower.contains("no open pull requests") {
|
||||
return Some("no pull request matches — nothing to report, rather than a failure");
|
||||
}
|
||||
None
|
||||
}
|
||||
154
crates/luxe-tools/src/git/run.rs
Normal file
154
crates/luxe-tools/src/git/run.rs
Normal file
@@ -0,0 +1,154 @@
|
||||
//! Running git and `gh` — bounded, with the tree reaped on a timeout and a failure explained.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
|
||||
use super::failure::{explain_failure, GH_ERROR_MAX_LINES};
|
||||
use super::GitTool;
|
||||
|
||||
/// How long a `gh` invocation may take before it is reaped.
|
||||
///
|
||||
/// Every `gh` subcommand is a network call, so this is not a guess about speed — it is the bound
|
||||
/// that stops a hung connection from stalling the turn with nothing to cancel.
|
||||
const GH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
|
||||
/// How long a `git` invocation may take before its process tree is reaped.
|
||||
///
|
||||
/// Deliberately under the engine's own deadline so this fires first, because only this one can kill
|
||||
/// the *tree*: the engine bounds a call by dropping the future, which reaps `git` and leaves the
|
||||
/// `gpg` pinentry or pre-commit hook it started running — holding `.git/index.lock` against every
|
||||
/// call that follows. Generous enough for a hook that runs a linter; the engine remains the backstop
|
||||
/// under any configuration that shortens its own bound.
|
||||
const GIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90);
|
||||
|
||||
impl GitTool {
|
||||
/// Run a git command and return its stdout.
|
||||
pub(super) async fn run_git(&self, cwd: &Path, args: &[&str]) -> Result<String> {
|
||||
let mut cmd = luxe_core::program::captured_command("git", args, cwd);
|
||||
// Git opens `$EDITOR` for a commit it has no message for, and that editor would inherit a
|
||||
// terminal the TUI owns while waiting for a human who cannot see it. Failing costs nothing:
|
||||
// every commit reaching here already carries a message or names where git should find one,
|
||||
// and `explain_failure` turns git's reply into the two arguments that would have worked.
|
||||
cmd.env("GIT_EDITOR", "false");
|
||||
|
||||
let output =
|
||||
run_bounded(cmd, "git", GIT_TIMEOUT, "a commit hook or a signing passphrase").await?;
|
||||
|
||||
if output.status.success() {
|
||||
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
||||
} else {
|
||||
Err(anyhow::anyhow!(
|
||||
"{}",
|
||||
explain_failure(
|
||||
&String::from_utf8_lossy(&output.stderr),
|
||||
&String::from_utf8_lossy(&output.stdout),
|
||||
cwd
|
||||
)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the branch a pull request can actually be opened from, or say why it cannot be.
|
||||
///
|
||||
/// `gh pr create` has one precondition it does not fix for you: the branch has to exist on the
|
||||
/// remote. Otherwise the call fails with a message about a head branch, and the model spends
|
||||
/// two round trips on `git push -u` and a retry, for a step that has exactly one correct
|
||||
/// answer.
|
||||
///
|
||||
/// Returns a line to prepend to the result when something was done, so a push is never silent.
|
||||
/// The push is plain — `--set-upstream`, never `--force` — because publishing a branch that
|
||||
/// does not exist yet cannot destroy anything, and rewriting one that does is a different
|
||||
/// operation with a different permission story.
|
||||
pub(super) async fn ready_branch_for_pr(&self, cwd: &Path) -> Result<Option<String>> {
|
||||
let branch = self.run_git(cwd, &["rev-parse", "--abbrev-ref", "HEAD"]).await?;
|
||||
let branch = branch.trim().to_string();
|
||||
if branch.is_empty() || branch == "HEAD" {
|
||||
anyhow::bail!(
|
||||
"HEAD is detached, so there is no branch to open a pull request from — \
|
||||
`git checkout -b <name>` first"
|
||||
);
|
||||
}
|
||||
// A pull request from trunk to trunk is not a thing, and the error `gh` gives for it sends
|
||||
// people looking at their remote rather than at their branch.
|
||||
if matches!(branch.as_str(), "main" | "master") {
|
||||
anyhow::bail!(
|
||||
"you are on `{branch}`, which is what a pull request would target — put the work \
|
||||
on its own branch first (`git checkout -b <name>`)"
|
||||
);
|
||||
}
|
||||
// An upstream already set means the branch is published; `gh` takes it from here.
|
||||
if self.run_git(cwd, &["rev-parse", "--abbrev-ref", "@{u}"]).await.is_ok() {
|
||||
return Ok(None);
|
||||
}
|
||||
self.run_git(cwd, &["push", "--set-upstream", "origin", &branch])
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!("could not publish `{branch}`: {error}"))?;
|
||||
Ok(Some(format!("Pushed `{branch}` to origin (it had no upstream), then:")))
|
||||
}
|
||||
|
||||
/// Run a `gh` command and return its stdout.
|
||||
///
|
||||
/// Resolved rather than assumed: `gh` installed by scoop, winget or Homebrew is frequently
|
||||
/// absent from the `PATH` an app inherits.
|
||||
pub(super) async fn run_gh(&self, cwd: &Path, args: &[&str]) -> Result<String> {
|
||||
let program = luxe_core::program::resolve("gh").ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"the GitHub CLI (`gh`) is not installed \u{2014} see https://cli.github.com, then run \
|
||||
`gh auth login`"
|
||||
)
|
||||
})?;
|
||||
let cmd = luxe_core::program::captured_command(program, args, cwd);
|
||||
let output = run_bounded(cmd, "gh", GH_TIMEOUT, "network access").await?;
|
||||
|
||||
if output.status.success() {
|
||||
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
||||
} else {
|
||||
// Same trap as `git`: a failure whose only words went to stdout would otherwise come
|
||||
// back as a bare "gh command failed:" with the reason cut off.
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let reported = match stderr.trim() {
|
||||
"" => stdout.trim(),
|
||||
text => text,
|
||||
};
|
||||
Err(anyhow::anyhow!(
|
||||
"gh command failed{}",
|
||||
match reported {
|
||||
"" => " (no output).".to_string(),
|
||||
text => format!(
|
||||
": {}",
|
||||
crate::output_limit::cap_lines(
|
||||
text,
|
||||
GH_ERROR_MAX_LINES,
|
||||
"lines of gh output",
|
||||
"Run the command directly to see the rest.",
|
||||
)
|
||||
),
|
||||
}
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `cmd` to completion under `deadline`, killing its whole tree if it expires.
|
||||
///
|
||||
/// `waiting_for` names the usual culprit, so a timeout is a lead rather than a shrug.
|
||||
async fn run_bounded(
|
||||
cmd: tokio::process::Command,
|
||||
program: &str,
|
||||
deadline: std::time::Duration,
|
||||
waiting_for: &str,
|
||||
) -> Result<std::process::Output> {
|
||||
use luxe_core::program::BoundedRunError;
|
||||
luxe_core::program::run_bounded(cmd, deadline).await.map_err(|error| match error {
|
||||
BoundedRunError::Timeout { after } => anyhow::anyhow!(
|
||||
"{program} timed out after {}s \u{2014} {waiting_for} is the usual cause; run the \
|
||||
command yourself to see what it is waiting for",
|
||||
after.as_secs()
|
||||
),
|
||||
BoundedRunError::Spawn(source) | BoundedRunError::Wait(source) => {
|
||||
anyhow::Error::new(source).context(format!("Failed to execute {program} command"))
|
||||
}
|
||||
})
|
||||
}
|
||||
746
crates/luxe-tools/src/git/tests.rs
Normal file
746
crates/luxe-tools/src/git/tests.rs
Normal file
@@ -0,0 +1,746 @@
|
||||
use super::failure::{explain_failure, explain_gh_failure, GIT_ERROR_MAX_LINES};
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn test_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: tmp_dir.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_git_missing_action() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({}), &ctx).await;
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_git_unknown_action() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"action": "invalid"}), &ctx).await;
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
/// The reply to an action nobody knows lists every action the schema offers.
|
||||
///
|
||||
/// The break this catches: the list was typed out by hand and stopped at `pr`, so a model that
|
||||
/// misspelled `checks` was told `show`, `issue` and `checks` did not exist.
|
||||
#[tokio::test]
|
||||
async fn an_unknown_action_names_every_action_the_schema_offers() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"action": "invalid"}), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(said) = &result.content[0] else { panic!("text") };
|
||||
let schema = tool.schema();
|
||||
let offered = schema.parameters["properties"]["action"]["enum"].as_array().unwrap();
|
||||
for action in offered {
|
||||
let name = action.as_str().unwrap();
|
||||
assert!(said.contains(name), "{name} is missing from: {said}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The schema and the dispatcher cannot drift: every action the schema offers is one the tool
|
||||
/// parses, and every action it parses is offered.
|
||||
#[test]
|
||||
fn every_action_in_the_schema_parses_and_every_parsed_action_is_in_the_schema() {
|
||||
let schema = GitTool::new().schema();
|
||||
let offered: Vec<&str> = schema.parameters["properties"]["action"]["enum"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|action| action.as_str().unwrap())
|
||||
.collect();
|
||||
for name in &offered {
|
||||
let parsed = GitAction::parse(name).unwrap_or_else(|| panic!("`{name}` does not parse"));
|
||||
assert_eq!(parsed.name(), *name);
|
||||
}
|
||||
let parsed: Vec<&str> = GitAction::ALL.map(GitAction::name).to_vec();
|
||||
assert_eq!(parsed, offered, "the same actions, in the schema's order");
|
||||
}
|
||||
|
||||
/// What each action runs, bare and with arguments: the defaults a caller relies on, and that the
|
||||
/// arguments it gives are the ones git gets.
|
||||
#[test]
|
||||
fn each_action_plans_the_git_command_it_names() {
|
||||
let planned = |action: GitAction, request: &[&str]| {
|
||||
let request: Vec<String> = request.iter().map(|arg| arg.to_string()).collect();
|
||||
let plan = plan(action, &serde_json::json!({}), &request)
|
||||
.unwrap_or_else(|_| panic!("{action:?} plans"));
|
||||
plan.argv.join(" ")
|
||||
};
|
||||
assert_eq!(planned(GitAction::Status, &[]), "status --short");
|
||||
assert_eq!(planned(GitAction::Diff, &[]), "diff --unified=3");
|
||||
assert_eq!(planned(GitAction::Diff, &["--stat"]), "diff --stat");
|
||||
assert_eq!(planned(GitAction::Show, &["HEAD", "--stat"]), "show HEAD --stat");
|
||||
assert_eq!(planned(GitAction::Log, &[]), "log --oneline -11");
|
||||
assert_eq!(planned(GitAction::Log, &["-n", "3"]), "log -n 3");
|
||||
assert_eq!(planned(GitAction::Add, &["a.rs", "b.rs"]), "add a.rs b.rs");
|
||||
assert_eq!(planned(GitAction::Branch, &[]), "branch -a");
|
||||
assert_eq!(planned(GitAction::Branch, &["-d", "old"]), "branch -d old");
|
||||
assert_eq!(planned(GitAction::Checkout, &["topic"]), "checkout topic");
|
||||
assert_eq!(planned(GitAction::Stash, &[]), "stash push");
|
||||
|
||||
// Naming nothing where something is needed is refused before git is asked
|
||||
for action in [GitAction::Add, GitAction::Checkout] {
|
||||
let Err(refusal) = plan(action, &serde_json::json!({}), &[]) else { panic!("{action:?}") };
|
||||
assert!(refusal.is_error);
|
||||
}
|
||||
// and an action that goes to `gh` is not a git command
|
||||
assert!(plan(GitAction::Pr, &serde_json::json!({}), &[]).is_err());
|
||||
}
|
||||
|
||||
/// How each answer is told: a clean tree, an empty diff and history, and a staged add each say so
|
||||
/// rather than returning nothing.
|
||||
#[test]
|
||||
fn an_empty_answer_says_what_it_means() {
|
||||
assert_eq!(Shape::OrMessage("clean").tell(" \n"), "clean");
|
||||
assert_eq!(Shape::OrMessage("clean").tell(" M a.rs\n"), " M a.rs\n");
|
||||
let diff = Shape::Capped { max: 10, noun: "lines", hint: "", empty: Some("no changes") };
|
||||
assert_eq!(diff.tell(""), "no changes");
|
||||
assert_eq!(Shape::LogDefault.tell(""), "no commits matched");
|
||||
assert_eq!(Shape::Said("Files staged.").tell("anything"), "Files staged.");
|
||||
assert_eq!(Shape::Trimmed.tell(" x\n"), "x");
|
||||
assert_eq!(Shape::Raw.tell(" x\n"), " x\n");
|
||||
}
|
||||
|
||||
/// A repository with one commit on a branch, and a bare "remote" it can really push to.
|
||||
///
|
||||
/// A real remote rather than a mock: the whole point of the preflight is what `git` does about
|
||||
/// an upstream, and an upstream that no command could ever set is not the thing under test.
|
||||
///
|
||||
/// `cfg(unix)` for the same reason its callers are — it silences the global git config with
|
||||
/// `/dev/null`, so a contributor's own `init.defaultBranch` cannot change what is under test.
|
||||
#[cfg(unix)]
|
||||
fn repo_with_remote() -> (TempDir, std::path::PathBuf) {
|
||||
let dir = TempDir::new().expect("tempdir");
|
||||
let remote = dir.path().join("remote.git");
|
||||
let work = dir.path().join("work");
|
||||
let run = |args: &[&str], cwd: &std::path::Path| {
|
||||
let status = std::process::Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.env("GIT_CONFIG_GLOBAL", "/dev/null")
|
||||
.env("GIT_CONFIG_SYSTEM", "/dev/null")
|
||||
.output()
|
||||
.expect("git runs");
|
||||
assert!(status.status.success(), "git {args:?}: {:?}", status);
|
||||
};
|
||||
std::fs::create_dir_all(&work).expect("mkdir");
|
||||
run(&["init", "--bare", "-b", "main", remote.to_str().expect("utf8")], dir.path());
|
||||
run(&["init", "-b", "main"], &work);
|
||||
run(&["config", "user.email", "t@example.com"], &work);
|
||||
run(&["config", "user.name", "Test"], &work);
|
||||
std::fs::write(work.join("a.txt"), "x").expect("write");
|
||||
run(&["add", "."], &work);
|
||||
run(&["commit", "-m", "first"], &work);
|
||||
run(&["remote", "add", "origin", remote.to_str().expect("utf8")], &work);
|
||||
(dir, work)
|
||||
}
|
||||
|
||||
/// A bare `log` shows ten commits and says when there are older ones, rather than letting ten
|
||||
/// read as the whole history; exactly ten says nothing more.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_bare_log_says_when_history_goes_on() {
|
||||
let (_dir, work) = repo_with_remote();
|
||||
let commit = |message: &str| {
|
||||
let output = std::process::Command::new("git")
|
||||
.args(["commit", "--allow-empty", "-q", "-m", message])
|
||||
.current_dir(&work)
|
||||
.env("GIT_CONFIG_GLOBAL", "/dev/null")
|
||||
.output()
|
||||
.expect("git runs");
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
};
|
||||
for n in 2..=10 {
|
||||
commit(&format!("commit {n}"));
|
||||
}
|
||||
let tool = GitTool::new();
|
||||
let cx = test_context(&work);
|
||||
let log = || tool.run(serde_json::json!({"action": "log"}), &cx);
|
||||
let luxe_core::ContentBlock::Text(ten) = &log().await.content[0] else { panic!("text") };
|
||||
assert_eq!(ten.lines().count(), 10, "{ten}");
|
||||
assert!(!ten.contains("older commits"), "{ten}");
|
||||
commit("commit 11");
|
||||
let luxe_core::ContentBlock::Text(eleven) = &log().await.content[0] else { panic!("text") };
|
||||
assert!(eleven.lines().next().unwrap().ends_with("commit 11"), "{eleven}");
|
||||
assert!(!eleven.contains(" first"), "the oldest is the one left out: {eleven}");
|
||||
assert!(eleven.ends_with("or a path for more."), "{eleven}");
|
||||
}
|
||||
|
||||
/// The preflight's whole reason for existing: a branch nobody has pushed gets published, so
|
||||
/// `gh pr create` meets the precondition it will not fix for itself.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_pull_request_publishes_its_branch_first() {
|
||||
let (_dir, work) = repo_with_remote();
|
||||
let run = |args: &[&str]| {
|
||||
std::process::Command::new("git").args(args).current_dir(&work).output().expect("git runs");
|
||||
};
|
||||
run(&["checkout", "-b", "feature"]);
|
||||
|
||||
let tool = GitTool::new();
|
||||
let note = tool.ready_branch_for_pr(&work).await.expect("the branch can be published");
|
||||
assert!(
|
||||
note.as_deref().is_some_and(|line| line.contains("feature")),
|
||||
"a push is never silent: {note:?}"
|
||||
);
|
||||
|
||||
// Really published, and a second call is now a no-op rather than a second push.
|
||||
let upstream = tool
|
||||
.run_git(&work, &["rev-parse", "--abbrev-ref", "@{u}"])
|
||||
.await
|
||||
.expect("an upstream exists now");
|
||||
assert_eq!(upstream.trim(), "origin/feature");
|
||||
assert_eq!(tool.ready_branch_for_pr(&work).await.expect("still fine"), None);
|
||||
}
|
||||
|
||||
/// Opening a pull request from trunk cannot work, and `gh`'s own error for it sends people to
|
||||
/// look at their remote instead of at their branch.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_pull_request_from_trunk_is_refused_with_the_fix() {
|
||||
let (_dir, work) = repo_with_remote();
|
||||
let error =
|
||||
GitTool::new().ready_branch_for_pr(&work).await.expect_err("main cannot target main");
|
||||
let said = error.to_string();
|
||||
assert!(said.contains("main"), "{said}");
|
||||
assert!(said.contains("checkout -b"), "names the fix: {said}");
|
||||
}
|
||||
|
||||
/// A detached HEAD has no branch to publish, and saying "push failed" there would be a
|
||||
/// diagnosis of the wrong problem.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_detached_head_is_named_as_the_problem() {
|
||||
let (_dir, work) = repo_with_remote();
|
||||
std::process::Command::new("git")
|
||||
.args(["checkout", "--detach", "HEAD"])
|
||||
.current_dir(&work)
|
||||
.output()
|
||||
.expect("git runs");
|
||||
let error = GitTool::new().ready_branch_for_pr(&work).await.expect_err("nothing to push");
|
||||
assert!(error.to_string().contains("detached"), "{error}");
|
||||
}
|
||||
|
||||
/// Only `create` has a precondition; a read must not push anything.
|
||||
#[test]
|
||||
fn only_creating_a_pull_request_triggers_the_preflight() {
|
||||
assert!(is_pr_create(&["create".to_string(), "--title".to_string()]));
|
||||
for read_only in [vec![], vec!["list".to_string()], vec!["view".to_string()]] {
|
||||
assert!(!is_pr_create(&read_only), "{read_only:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The one `gh` failure a person can actually act on, in words that say what to do.
|
||||
#[test]
|
||||
fn a_signed_out_gh_is_explained_rather_than_echoed() {
|
||||
for raw in [
|
||||
"gh command failed: To get started with GitHub CLI, please run: gh auth login",
|
||||
"HTTP 401: Requires authentication",
|
||||
] {
|
||||
let explained = explain_gh_failure(raw).expect("a known cause");
|
||||
assert!(explained.contains("gh auth login"), "{explained}");
|
||||
}
|
||||
// Anything unrecognized is passed through rather than guessed at.
|
||||
assert_eq!(explain_gh_failure("something nobody anticipated"), None);
|
||||
}
|
||||
|
||||
/// `gh`'s "no GitHub remote" message ends by suggesting `gh auth login`. Read as a sign-in
|
||||
/// problem, it sent the reader to fix an account that was fine.
|
||||
#[test]
|
||||
fn a_repository_without_a_github_remote_is_not_a_sign_in_problem() {
|
||||
let explained = explain_gh_failure(
|
||||
"gh command failed: none of the git remotes configured for this repository point to a \
|
||||
known GitHub host. To tell gh about a new GitHub host, please use `gh auth login`",
|
||||
)
|
||||
.expect("a known cause");
|
||||
assert!(explained.contains("no remote on a GitHub host"), "{explained}");
|
||||
assert!(!explained.contains("not signed in"), "{explained}");
|
||||
}
|
||||
|
||||
/// The defect this guards was silent by construction: everything after the subaction was
|
||||
/// dropped, so a fully-specified `pr create` arrived at `gh` as a bare one and sat waiting for
|
||||
/// the title it had already been given.
|
||||
#[test]
|
||||
fn every_pr_argument_reaches_gh() {
|
||||
let requested: Vec<String> = ["create", "--title", "Fix the thing", "--body", "why", "--draft"]
|
||||
.iter()
|
||||
.map(|part| (*part).to_string())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
gh_args("pr", &requested),
|
||||
["pr", "create", "--title", "Fix the thing", "--body", "why", "--draft"]
|
||||
);
|
||||
|
||||
assert_eq!(gh_args("pr", &[]), ["pr", "list"], "no subaction is a listing, not an error");
|
||||
assert_eq!(gh_args("pr", &["view".to_string()]), ["pr", "view"]);
|
||||
let issue: Vec<String> = ["view", "12", "--comments"].map(String::from).to_vec();
|
||||
assert_eq!(gh_args("issue", &issue), ["issue", "view", "12", "--comments"]);
|
||||
assert_eq!(gh_args("issue", &[]), ["issue", "list"]);
|
||||
}
|
||||
|
||||
/// The same defect as [`every_pr_argument_reaches_gh`], one arm away and still live: only the
|
||||
/// subaction survived, so the `-m wip` that names a stash entry was dropped on the floor.
|
||||
#[test]
|
||||
fn every_stash_argument_reaches_git() {
|
||||
let requested: Vec<String> =
|
||||
["push", "-m", "wip", "--keep-index"].iter().map(|part| (*part).to_string()).collect();
|
||||
assert_eq!(stash_args(&requested), ["stash", "push", "-m", "wip", "--keep-index"]);
|
||||
|
||||
assert_eq!(stash_args(&[]), ["stash", "push"], "no subaction stashes, as it always did");
|
||||
assert_eq!(stash_args(&["pop".to_string()]), ["stash", "pop"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_git_status_not_repo() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"action": "status"}), &ctx).await;
|
||||
// Should fail because tmp_dir is not a git repo
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_git_commit_missing_message() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"action": "commit"}), &ctx).await;
|
||||
assert!(result.is_error);
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("\"message\""), "a refusal shows the call that works: {text}");
|
||||
}
|
||||
|
||||
/// No refusal may demand an argument the schema never offered.
|
||||
///
|
||||
/// The defect this guards was invisible from either side on its own. `commit` read a top-level
|
||||
/// `message`; `schema()` advertised `action` and `args` and nothing else. Both halves read fine
|
||||
/// in isolation, and together they meant the only call a model could build from the schema was
|
||||
/// the one call the tool rejected — which a real session hit three times before giving up and
|
||||
/// shelling out. So: hand every action everything the schema offers, and nothing may come back
|
||||
/// saying something is missing.
|
||||
#[tokio::test]
|
||||
async fn no_action_demands_an_argument_the_schema_never_offered() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
if !init_repo(tmp_dir.path()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let schema = tool.schema();
|
||||
let properties = schema.parameters["properties"].as_object().expect("an object schema");
|
||||
let actions =
|
||||
properties["action"]["enum"].as_array().expect("the actions are enumerated").clone();
|
||||
|
||||
for action in actions {
|
||||
let mut call = serde_json::Map::new();
|
||||
call.insert("action".to_string(), action.clone());
|
||||
// Everything else the schema offers, filled with the most harmless value that fits, so
|
||||
// any complaint left is about something the schema never mentioned.
|
||||
for (name, spec) in properties.iter().filter(|(name, _)| *name != "action") {
|
||||
let value = match spec["type"].as_str() {
|
||||
Some("array") => serde_json::json!(["."]),
|
||||
_ => serde_json::json!("placeholder"),
|
||||
};
|
||||
call.insert(name.clone(), value);
|
||||
}
|
||||
|
||||
let result = tool.run(serde_json::Value::Object(call), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else {
|
||||
panic!("expected text")
|
||||
};
|
||||
let lowered = text.to_ascii_lowercase();
|
||||
assert!(
|
||||
!lowered.contains("is required") && !lowered.contains("must include"),
|
||||
"`{action}` was handed every declared argument and still reports one missing: \
|
||||
{text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every spelling of a commit message reaches a real repository as a real commit.
|
||||
///
|
||||
/// [`crate::git::args`] proves the argument list; this proves the wiring, against git itself.
|
||||
#[tokio::test]
|
||||
async fn a_commit_message_lands_however_it_was_spelled() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
if !init_repo(tmp_dir.path()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let spellings = [
|
||||
serde_json::json!({"action": "commit", "message": "canonical"}),
|
||||
serde_json::json!({"action": "commit", "args": ["-m", "inside args"]}),
|
||||
serde_json::json!({"action": "commit", "args": ["a bare argument"]}),
|
||||
];
|
||||
for (nth, call) in spellings.iter().enumerate() {
|
||||
std::fs::write(tmp_dir.path().join(format!("{nth}.txt")), "x").unwrap();
|
||||
let staged = tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
assert!(!staged.is_error, "staging failed");
|
||||
|
||||
let result = tool.run(call.clone(), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else {
|
||||
panic!("expected text")
|
||||
};
|
||||
assert!(!result.is_error, "{call} was refused: {text}");
|
||||
}
|
||||
|
||||
let log = tool.run(serde_json::json!({"action": "log", "args": ["--format=%s"]}), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &log.content[0] else { panic!("expected text") };
|
||||
let subjects: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(subjects, ["a bare argument", "inside args", "canonical"], "{text}");
|
||||
}
|
||||
|
||||
/// `show` reads a file as a revision has it, which is how a pull request that is not checked
|
||||
/// out is read without the shell.
|
||||
#[tokio::test]
|
||||
async fn show_reads_a_file_at_a_revision() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
if !init_repo(tmp_dir.path()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let file = tmp_dir.path().join("a.txt");
|
||||
std::fs::write(&file, "as committed\n").unwrap();
|
||||
tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
tool.run(serde_json::json!({"action": "commit", "message": "base"}), &ctx).await;
|
||||
std::fs::write(&file, "since\n").unwrap();
|
||||
|
||||
let shown = tool.run(serde_json::json!({"action": "show", "args": ["HEAD:a.txt"]}), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &shown.content[0] else { panic!("text") };
|
||||
assert!(!shown.is_error, "{text}");
|
||||
assert_eq!(text.trim(), "as committed");
|
||||
}
|
||||
|
||||
/// The defect end to end, against git itself: an unstaged commit must come back saying why.
|
||||
///
|
||||
/// Pinned here as well as at [`explain_failure`] because the bug was neither in the wording
|
||||
/// nor in git — it was the one stream the runner threw away, and only a real invocation has
|
||||
/// two streams to throw away.
|
||||
#[tokio::test]
|
||||
async fn committing_with_nothing_staged_says_what_to_stage() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
if !init_repo(tmp_dir.path()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let file = tmp_dir.path().join("a.txt");
|
||||
|
||||
std::fs::write(&file, "one").unwrap();
|
||||
tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
tool.run(serde_json::json!({"action": "commit", "message": "base"}), &ctx).await;
|
||||
std::fs::write(&file, "two").unwrap();
|
||||
|
||||
let refused =
|
||||
tool.run(serde_json::json!({"action": "commit", "message": "unstaged"}), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &refused.content[0] else { panic!("expected text") };
|
||||
assert!(refused.is_error, "an unstaged commit is a failure: {text}");
|
||||
assert!(!text.contains("no output"), "git said plenty, on stdout: {text}");
|
||||
assert!(text.contains("Nothing is staged"), "{text}");
|
||||
|
||||
// And the fix it names actually works, through this tool.
|
||||
tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
let committed =
|
||||
tool.run(serde_json::json!({"action": "commit", "message": "staged"}), &ctx).await;
|
||||
assert!(!committed.is_error, "{:?}", committed.content);
|
||||
}
|
||||
|
||||
/// A commit that reuses an existing message needs no `message`, and used to be unreachable.
|
||||
#[tokio::test]
|
||||
async fn amending_with_no_edit_keeps_the_message_it_already_had() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
if !init_repo(tmp_dir.path()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
std::fs::write(tmp_dir.path().join("a.txt"), "one").unwrap();
|
||||
tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
tool.run(serde_json::json!({"action": "commit", "message": "the subject"}), &ctx).await;
|
||||
|
||||
std::fs::write(tmp_dir.path().join("a.txt"), "two").unwrap();
|
||||
tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
let amended = tool
|
||||
.run(serde_json::json!({"action": "commit", "args": ["--amend", "--no-edit"]}), &ctx)
|
||||
.await;
|
||||
let luxe_core::ContentBlock::Text(text) = &amended.content[0] else { panic!("expected text") };
|
||||
assert!(!amended.is_error, "{text}");
|
||||
|
||||
let log = tool.run(serde_json::json!({"action": "log", "args": ["--format=%s"]}), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &log.content[0] else { panic!("expected text") };
|
||||
assert_eq!(text.lines().collect::<Vec<_>>(), ["the subject"], "one commit, same subject");
|
||||
}
|
||||
|
||||
/// The `stash` action forwards what it was given, proven against git rather than against
|
||||
/// [`stash_args`] alone — the argument list was already right in isolation, and the arm calling
|
||||
/// it is where the label used to go missing.
|
||||
#[tokio::test]
|
||||
async fn a_named_stash_keeps_its_name() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
if !init_repo(tmp_dir.path()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let file = tmp_dir.path().join("a.txt");
|
||||
|
||||
std::fs::write(&file, "one").unwrap();
|
||||
tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
tool.run(serde_json::json!({"action": "commit", "message": "base"}), &ctx).await;
|
||||
std::fs::write(&file, "two").unwrap();
|
||||
|
||||
let stashed = tool
|
||||
.run(
|
||||
serde_json::json!({"action": "stash", "args": ["push", "-m", "the named entry"]}),
|
||||
&ctx,
|
||||
)
|
||||
.await;
|
||||
let luxe_core::ContentBlock::Text(text) = &stashed.content[0] else { panic!("expected text") };
|
||||
assert!(!stashed.is_error, "{text}");
|
||||
|
||||
let listed = std::process::Command::new("git")
|
||||
.args(["stash", "list"])
|
||||
.current_dir(tmp_dir.path())
|
||||
.output()
|
||||
.expect("git runs");
|
||||
let listed = String::from_utf8_lossy(&listed.stdout);
|
||||
assert!(listed.contains("the named entry"), "the label reached git: {listed:?}");
|
||||
}
|
||||
|
||||
/// Git asking for an editor is a hang everywhere else; here it is closed off, and the reply
|
||||
/// names the two arguments that would have worked instead of git's `-m`/`-F`.
|
||||
#[test]
|
||||
fn an_editor_prompt_is_answered_with_the_arguments_this_tool_takes() {
|
||||
let explained = explain_failure(
|
||||
"error: there was a problem with the editor 'false'\n\
|
||||
Please supply the message using either -m or -F option.",
|
||||
"",
|
||||
std::path::Path::new("/tmp/work"),
|
||||
);
|
||||
assert!(explained.contains("`message`"), "{explained}");
|
||||
assert!(explained.contains("--no-edit"), "{explained}");
|
||||
}
|
||||
|
||||
/// A repository that can commit: `init` plus the identity git refuses to invent.
|
||||
fn init_repo(path: &std::path::Path) -> bool {
|
||||
let run = |args: &[&str]| {
|
||||
std::process::Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(path)
|
||||
.output()
|
||||
.is_ok_and(|output| output.status.success())
|
||||
};
|
||||
run(&["init", "--quiet"])
|
||||
&& run(&["config", "user.email", "test@luxe.invalid"])
|
||||
&& run(&["config", "user.name", "Luxe Test"])
|
||||
// A signing key the machine may not have would fail every commit here.
|
||||
&& run(&["config", "commit.gpgsign", "false"])
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_clean_tree_says_so_instead_of_returning_nothing() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
// A real (empty) repo: `git status --short` prints nothing at all.
|
||||
let init = tokio::process::Command::new("git")
|
||||
.args(["init", "--quiet"])
|
||||
.current_dir(tmp_dir.path())
|
||||
.status()
|
||||
.await;
|
||||
if !matches!(init, Ok(status) if status.success()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"action": "status"}), &ctx).await;
|
||||
assert!(!result.is_error);
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else {
|
||||
panic!("expected text");
|
||||
};
|
||||
assert!(text.contains("clean"), "an empty status explains itself: {text:?}");
|
||||
|
||||
let diff = tool.run(serde_json::json!({"action": "diff"}), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &diff.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("no changes"), "an empty diff explains itself: {text:?}");
|
||||
}
|
||||
|
||||
/// A failing `gh` hands its own stderr back, rather than an empty complaint.
|
||||
///
|
||||
/// The break this catches, measured against the installed binary: `spawn` leaves stdout and
|
||||
/// stderr **inherited** — only `Command::output` pipes them — so this call reported
|
||||
/// "gh command failed:" with nothing after the colon while `gh`'s actual message ("no git
|
||||
/// remotes found") went to the terminal, on top of the TUI. Runs only where `gh` is installed,
|
||||
/// in a directory with no remote, which is a reliable way to make it fail without a network.
|
||||
#[tokio::test]
|
||||
async fn a_failing_gh_reports_what_gh_said() {
|
||||
if !luxe_core::program::is_available("gh") {
|
||||
return;
|
||||
}
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
// A repository with no remote: `gh pr list` refuses immediately and says why.
|
||||
std::process::Command::new("git")
|
||||
.args(["init", "-q"])
|
||||
.current_dir(tmp_dir.path())
|
||||
.output()
|
||||
.expect("git runs");
|
||||
|
||||
let tool = GitTool::new();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let result = tool.run(serde_json::json!({"action": "pr"}), &ctx).await;
|
||||
|
||||
assert!(result.is_error, "a repository with no remote has no pull requests");
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else {
|
||||
panic!("Expected Text content block")
|
||||
};
|
||||
|
||||
// The property, not the particular complaint. `gh` fails here for whatever reason the
|
||||
// machine supplies — "no git remotes found" on a developer's box, "set the GH_TOKEN
|
||||
// environment variable" on a CI runner — and asserting either one pins the test to one
|
||||
// environment, which is how the first version of it passed locally and failed in CI. What
|
||||
// has to hold everywhere is that a reason comes back: gh's own words, or the sentence a
|
||||
// recognized cause is rewritten into. The bug was an empty tail.
|
||||
let reason = text
|
||||
.strip_prefix("gh pr failed:")
|
||||
.map(|tail| tail.trim().trim_start_matches("gh command failed:").trim())
|
||||
.unwrap_or_default();
|
||||
assert!(!reason.is_empty(), "a reason must come back, got {text:?}");
|
||||
assert!(!reason.contains("(no output)"), "a reason must come back, got {text:?}");
|
||||
}
|
||||
|
||||
/// Without `gh` on PATH, `pr` says so and says what to do about it.
|
||||
///
|
||||
/// The break this catches: the old answer was "GitHub CLI integration is not enabled", gated on
|
||||
/// a `GitConfig` flag that nothing could set — `GitConfig::default()` is what registers the tool
|
||||
/// — so the action was unreachable and its error named an internal switch instead of the program
|
||||
/// the user has to install. Skipped where `gh` really is installed, since then there is nothing
|
||||
/// to report.
|
||||
#[tokio::test]
|
||||
async fn pr_without_the_github_cli_names_the_missing_program() {
|
||||
if luxe_core::program::is_available("gh") {
|
||||
return;
|
||||
}
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"action": "pr"}), &ctx).await;
|
||||
assert!(result.is_error);
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else {
|
||||
panic!("Expected Text content block")
|
||||
};
|
||||
assert!(text.contains("`gh`"), "name the program: {text}");
|
||||
assert!(text.contains("auth login"), "and what it needs after installing: {text}");
|
||||
}
|
||||
|
||||
/// Outside a repo, git answers `status` with a filesystem-boundary note and `diff` with its
|
||||
/// entire usage screen. Neither states the fact that matters.
|
||||
#[test]
|
||||
fn outside_a_repository_the_error_says_so_in_one_line() {
|
||||
let stderr = "fatal: not a git repository (or any parent up to mount point /)\n\
|
||||
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).";
|
||||
let explained = explain_failure(stderr, "", std::path::Path::new("/tmp/work"));
|
||||
|
||||
assert!(explained.starts_with("Not a git repository"), "{explained}");
|
||||
assert!(explained.contains("/tmp/work"), "names the directory: {explained}");
|
||||
assert!(explained.contains("read"), "and says what to do instead: {explained}");
|
||||
assert!(!explained.contains("GIT_DISCOVERY"), "plumbing noise is dropped: {explained}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_usage_dump_is_bounded_rather_than_pasted_whole() {
|
||||
let usage = vec![" -p, --patch generate patch"; 40].join("\n");
|
||||
let explained = explain_failure(&usage, "", std::path::Path::new("/tmp/work"));
|
||||
assert!(explained.lines().count() <= GIT_ERROR_MAX_LINES + 3, "{explained}");
|
||||
assert!(explained.contains("more lines not shown"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_git_error_keeps_gits_own_words() {
|
||||
let explained =
|
||||
explain_failure("error: pathspec 'nope' did not match", "", std::path::Path::new("."));
|
||||
assert!(explained.contains("pathspec 'nope' did not match"), "{explained}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_stderr_still_says_something() {
|
||||
assert!(explain_failure(" ", "", std::path::Path::new(".")).contains("no output"));
|
||||
}
|
||||
|
||||
/// Git says why a commit was refused on **stdout**, and exits 1 with an empty stderr. Reading
|
||||
/// one stream reported "no output" for the single most common commit failure there is.
|
||||
#[test]
|
||||
fn a_refusal_git_wrote_to_stdout_is_not_reported_as_no_output() {
|
||||
let refused = "On branch master\nChanges not staged for commit:\n\tmodified: f.txt\n\n\
|
||||
no changes added to commit (use \"git add\" and/or \"git commit -a\")";
|
||||
let explained = explain_failure("", refused, std::path::Path::new("."));
|
||||
|
||||
assert!(!explained.contains("no output"), "{explained}");
|
||||
assert!(explained.contains("Nothing is staged"), "names the cause: {explained}");
|
||||
assert!(explained.contains("\"action\": \"add\""), "and this tool's fix: {explained}");
|
||||
assert!(explained.contains("-a"), "and the one-call alternative: {explained}");
|
||||
}
|
||||
|
||||
/// The three refusals are corrected differently, so each gets its own answer: `-a` picks up a
|
||||
/// tracked modification and will never pick up an untracked file.
|
||||
#[test]
|
||||
fn each_reason_a_commit_is_refused_gets_its_own_answer() {
|
||||
let untracked = explain_failure(
|
||||
"",
|
||||
"nothing added to commit but untracked files present (use \"git add\" to track)",
|
||||
std::path::Path::new("."),
|
||||
);
|
||||
assert!(untracked.contains("never tracked"), "{untracked}");
|
||||
assert!(untracked.contains("`-a` does not"), "and why -a will not do: {untracked}");
|
||||
|
||||
let clean =
|
||||
explain_failure("", "nothing to commit, working tree clean", std::path::Path::new("."));
|
||||
assert!(clean.contains("already committed"), "{clean}");
|
||||
assert!(!clean.contains("Nothing to commit:"), "not two colons in one line: {clean}");
|
||||
assert!(!clean.contains("Stage them"), "there is nothing to stage: {clean}");
|
||||
}
|
||||
|
||||
/// When git splits its report across both streams, neither half is dropped.
|
||||
#[test]
|
||||
fn both_streams_reach_the_caller() {
|
||||
let explained = explain_failure(
|
||||
"Recorded preimage for 'f.txt'",
|
||||
"CONFLICT (content): Merge conflict in f.txt",
|
||||
std::path::Path::new("."),
|
||||
);
|
||||
assert!(explained.contains("CONFLICT (content)"), "{explained}");
|
||||
assert!(explained.contains("Recorded preimage"), "{explained}");
|
||||
}
|
||||
Reference in New Issue
Block a user