diff --git a/Cargo.lock b/Cargo.lock index ee465ca..695ff68 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1116,6 +1116,7 @@ dependencies = [ "gix-odb", "gix-pack", "globset", + "serde_json", "sha1", "tempfile", "thiserror", diff --git a/Cargo.toml b/Cargo.toml index d76284f..e211571 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ gix-pack = "0.60.0" globset = "=0.4.20" sha1 = "0.10" thiserror = "2" +serde_json = "1" # Smart-HTTP transport (Phase 3 C). axum/tokio power the async listener; the # pkt-line/pack/negotiation logic stays in the synchronous core and is called diff --git a/src/forge_cli.rs b/src/forge_cli.rs new file mode 100644 index 0000000..8ec832c --- /dev/null +++ b/src/forge_cli.rs @@ -0,0 +1,518 @@ +//! `rit issue ...` and `rit pr ...`: work with rithub issues and pull requests +//! from the command line through the forge JSON API. +//! +//! The target repository is derived from a configured remote (default +//! `origin`): `https://host//.git` talks to `https://host/api/...`; +//! ssh remotes default to `https://` (override with `RIT_API_URL`). +//! Authentication uses `RIT_USERNAME` + `RIT_TOKEN` (a rithub personal access +//! token), or credentials embedded in an http(s) remote URL. + +use std::io::Read; +use std::path::Path; + +use anyhow::{bail, Context, Result}; +use clap::{Args, Subcommand, ValueEnum}; +use rit::remote::{forge_repo, get_remote, ForgeRepo}; +use rit::Repository; +use serde_json::{json, Value}; + +/// Which remote identifies the forge repository. +#[derive(Args, Clone)] +pub struct ForgeTarget { + /// Remote whose URL names the rithub repository. + #[arg(long = "remote", default_value = "origin", global = true)] + remote: String, +} + +/// State filter for list commands. +#[derive(Clone, Copy, ValueEnum)] +pub enum StateFilter { + Open, + Closed, + Merged, + All, +} + +#[derive(Args)] +pub struct IssueArgs { + #[command(flatten)] + target: ForgeTarget, + #[command(subcommand)] + action: IssueAction, +} + +#[derive(Subcommand)] +enum IssueAction { + /// List issues (open by default). + List { + #[arg(long = "state", value_enum, default_value = "open")] + state: StateFilter, + }, + /// Show one issue, optionally with its comments. + View { + number: i32, + #[arg(long = "comments")] + comments: bool, + }, + /// Open a new issue. + Create { + /// Title (required). + #[arg(short = 't', long = "title")] + title: String, + #[command(flatten)] + body: BodyArgs, + }, + /// Close an issue. + Close { number: i32 }, + /// Reopen a closed issue. + Reopen { number: i32 }, + /// Comment on an issue. + Comment { + number: i32, + #[command(flatten)] + body: BodyArgs, + }, +} + +#[derive(Args)] +pub struct PrArgs { + #[command(flatten)] + target: ForgeTarget, + #[command(subcommand)] + action: PrAction, +} + +#[derive(Subcommand)] +enum PrAction { + /// List pull requests (open by default). + List { + #[arg(long = "state", value_enum, default_value = "open")] + state: StateFilter, + }, + /// Show one pull request with mergeability and approvals. + View { + number: i32, + #[arg(long = "comments")] + comments: bool, + }, + /// Open a pull request from `--head` (default: current branch) into + /// `--base` (default: the repository's default branch). + Create { + /// Title (required). + #[arg(short = 't', long = "title")] + title: String, + /// Source branch (default: the current branch). + #[arg(long = "head")] + head: Option, + /// Target branch (default: the repository's default branch). + #[arg(long = "base")] + base: Option, + /// Source `org/repo` for a pull request from a fork. + #[arg(long = "head-repo")] + head_repo: Option, + #[command(flatten)] + body: BodyArgs, + }, + /// Merge a pull request (subject to branch protection). + Merge { + number: i32, + /// How to merge. + #[arg(long = "strategy", value_enum, default_value = "merge")] + strategy: MergeStrategy, + /// Merge commit message. + #[arg(short = 'm', long = "message")] + message: Option, + }, + /// Close a pull request without merging. + Close { number: i32 }, + /// Reopen a closed pull request. + Reopen { number: i32 }, + /// Comment on a pull request. + Comment { + number: i32, + #[command(flatten)] + body: BodyArgs, + }, + /// Print the pull request's diff. + Diff { + number: i32, + /// Only list changed files with their line counts. + #[arg(long = "stat")] + stat: bool, + }, + /// Show the check runs for the pull request's head commit. + Checks { number: i32 }, +} + +#[derive(Clone, Copy, ValueEnum)] +enum MergeStrategy { + Merge, + Squash, + Rebase, +} + +impl MergeStrategy { + fn as_str(self) -> &'static str { + match self { + MergeStrategy::Merge => "merge", + MergeStrategy::Squash => "squash", + MergeStrategy::Rebase => "rebase", + } + } +} + +/// A text body given inline or from a file (`-` = stdin). +#[derive(Args)] +struct BodyArgs { + /// Body text (Markdown). + #[arg(short = 'b', long = "body", conflicts_with = "body_file")] + body: Option, + /// Read the body from a file, or `-` for stdin. + #[arg(short = 'F', long = "body-file")] + body_file: Option, +} + +impl BodyArgs { + fn read(&self) -> Result> { + if let Some(body) = &self.body { + return Ok(Some(body.clone())); + } + match self.body_file.as_deref() { + None => Ok(None), + Some("-") => { + let mut text = String::new(); + std::io::stdin().read_to_string(&mut text).context("reading body from stdin")?; + Ok(Some(text)) + } + Some(path) => Ok(Some( + std::fs::read_to_string(path).with_context(|| format!("reading {path}"))?, + )), + } + } + + fn require(&self) -> Result { + match self.read()? { + Some(text) if !text.trim().is_empty() => Ok(text), + _ => bail!("a body is required (--body or --body-file )"), + } + } +} + +fn open_forge(repo_path: &Path, target: &ForgeTarget) -> Result<(Repository, ForgeRepo)> { + let repo = Repository::discover(repo_path) + .with_context(|| format!("opening repo at {}", repo_path.display()))?; + let remote = get_remote(&repo, &target.remote)?; + let forge = forge_repo(&remote.url)?; + Ok((repo, forge)) +} + +fn state_query(state: StateFilter) -> &'static str { + match state { + StateFilter::Open => "?state=open", + StateFilter::Closed => "?state=closed", + StateFilter::Merged => "?state=merged", + StateFilter::All => "", + } +} + +fn s<'a>(v: &'a Value, key: &str) -> &'a str { + v.get(key).and_then(Value::as_str).unwrap_or("") +} + +fn n(v: &Value, key: &str) -> i64 { + v.get(key).and_then(Value::as_i64).unwrap_or(0) +} + +/// `2026-09-24T10:11:12Z` -> `2026-09-24`. +fn day(ts: &str) -> &str { + ts.get(..10).unwrap_or(ts) +} + +fn print_body(body: &str) { + if body.trim().is_empty() { + println!(" (no description)"); + } else { + for line in body.lines() { + println!(" {line}"); + } + } +} + +fn print_comments(forge: &ForgeRepo, sub: &str) -> Result<()> { + let comments = forge.api("GET", sub, None)?; + let list = comments.as_array().cloned().unwrap_or_default(); + println!(); + if list.is_empty() { + println!("No comments."); + return Ok(()); + } + println!("{} comment(s):", list.len()); + for c in &list { + println!(); + println!(" -- {} --", day(s(c, "created_at"))); + for line in s(c, "body").lines() { + println!(" {line}"); + } + } + Ok(()) +} + +pub fn cmd_issue(repo_path: &Path, args: &IssueArgs) -> Result<()> { + let (_, forge) = open_forge(repo_path, &args.target)?; + match &args.action { + IssueAction::List { state } => { + let issues = forge.api("GET", &format!("/issues{}", state_query(*state)), None)?; + let list = issues.as_array().cloned().unwrap_or_default(); + if list.is_empty() { + println!("No issues in {}.", forge.slug()); + } + for issue in &list { + println!( + "#{:<5} {:<7} {} {}", + n(issue, "number"), + s(issue, "state"), + day(s(issue, "created_at")), + s(issue, "title") + ); + } + } + IssueAction::View { number, comments } => { + let issue = forge.api("GET", &format!("/issues/{number}"), None)?; + println!("#{} {}", n(&issue, "number"), s(&issue, "title")); + println!( + "state: {} opened: {} comments: {}", + s(&issue, "state"), + day(s(&issue, "created_at")), + n(&issue, "comment_count") + ); + let join = |key: &str| { + issue + .get(key) + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).collect::>().join(", ")) + .unwrap_or_default() + }; + let labels = join("labels"); + let assignees = join("assignees"); + if !labels.is_empty() { + println!("labels: {labels}"); + } + if !assignees.is_empty() { + println!("assignees: {assignees}"); + } + println!("{}", forge.web_url(&format!("issues/{number}"))); + println!(); + print_body(s(&issue, "body")); + if *comments { + print_comments(&forge, &format!("/issues/{number}/comments"))?; + } + } + IssueAction::Create { title, body } => { + let issue = forge.api( + "POST", + "/issues", + Some(&json!({ "title": title, "body": body.read()? })), + )?; + let number = n(&issue, "number"); + println!("Opened issue #{number}: {}", s(&issue, "title")); + println!("{}", forge.web_url(&format!("issues/{number}"))); + } + IssueAction::Close { number } => { + forge.api("POST", &format!("/issues/{number}/close"), None)?; + println!("Closed issue #{number} in {}", forge.slug()); + } + IssueAction::Reopen { number } => { + forge.api("POST", &format!("/issues/{number}/reopen"), None)?; + println!("Reopened issue #{number} in {}", forge.slug()); + } + IssueAction::Comment { number, body } => { + forge.api( + "POST", + &format!("/issues/{number}/comments"), + Some(&json!({ "body": body.require()? })), + )?; + println!("Commented on issue #{number}"); + println!("{}", forge.web_url(&format!("issues/{number}"))); + } + } + Ok(()) +} + +fn current_branch(repo: &Repository) -> Result { + let head = std::fs::read_to_string(repo.git_dir().join("HEAD")).context("reading HEAD")?; + head.trim() + .strip_prefix("ref: refs/heads/") + .map(str::to_string) + .context("HEAD is detached; pass --head ") +} + +pub fn cmd_pr(repo_path: &Path, args: &PrArgs) -> Result<()> { + let (repo, forge) = open_forge(repo_path, &args.target)?; + match &args.action { + PrAction::List { state } => { + let prs = forge.api("GET", &format!("/pulls{}", state_query(*state)), None)?; + let list = prs.as_array().cloned().unwrap_or_default(); + if list.is_empty() { + println!("No pull requests in {}.", forge.slug()); + } + for pr in &list { + println!( + "#{:<5} {:<7} {} -> {} {}", + n(pr, "number"), + s(pr, "state"), + s(pr, "head_branch"), + s(pr, "base_branch"), + s(pr, "title") + ); + } + } + PrAction::View { number, comments } => { + let pr = forge.api("GET", &format!("/pulls/{number}"), None)?; + println!("#{} {}", n(&pr, "number"), s(&pr, "title")); + println!( + "state: {} {} -> {} opened: {}", + s(&pr, "state"), + s(&pr, "head_branch"), + s(&pr, "base_branch"), + day(s(&pr, "created_at")) + ); + let mergeable = match pr.get("mergeable").and_then(Value::as_bool) { + Some(true) => "yes", + Some(false) => "no", + None => "unknown", + }; + println!( + "mergeable: {mergeable} ({}) approvals: {}", + pr.get("merge_status").and_then(Value::as_str).unwrap_or("n/a"), + n(&pr, "approvals") + ); + if let Some(sha) = pr.get("merge_commit_sha").and_then(Value::as_str) { + println!("merge commit: {sha}"); + } + println!("{}", forge.web_url(&format!("pulls/{number}"))); + println!(); + print_body(s(&pr, "body")); + if *comments { + print_comments(&forge, &format!("/pulls/{number}/comments"))?; + } + } + PrAction::Create { title, head, base, head_repo, body } => { + let head = match head { + Some(h) => h.clone(), + None => current_branch(&repo)?, + }; + let base = match base { + Some(b) => b.clone(), + None => { + let meta = forge.api("GET", "", None)?; + let b = s(&meta, "default_branch"); + if b.is_empty() { "main".to_string() } else { b.to_string() } + } + }; + let pr = forge.api( + "POST", + "/pulls", + Some(&json!({ + "title": title, + "body": body.read()?, + "head": head, + "base": base, + "head_repo": head_repo, + })), + )?; + let number = n(&pr, "number"); + println!("Opened pull request #{number}: {} ({head} -> {base})", s(&pr, "title")); + println!("{}", forge.web_url(&format!("pulls/{number}"))); + } + PrAction::Merge { number, strategy, message } => { + let out = forge.api( + "POST", + &format!("/pulls/{number}/merge"), + Some(&json!({ "strategy": strategy.as_str(), "message": message })), + )?; + let sha = s(&out, "merge_commit_sha"); + println!( + "Merged pull request #{number} ({}){}", + if s(&out, "kind").is_empty() { strategy.as_str() } else { s(&out, "kind") }, + if sha.is_empty() { String::new() } else { format!(" as {}", &sha[..sha.len().min(12)]) } + ); + } + PrAction::Close { number } => { + forge.api("POST", &format!("/pulls/{number}/close"), None)?; + println!("Closed pull request #{number} in {}", forge.slug()); + } + PrAction::Reopen { number } => { + forge.api("POST", &format!("/pulls/{number}/reopen"), None)?; + println!("Reopened pull request #{number} in {}", forge.slug()); + } + PrAction::Comment { number, body } => { + forge.api( + "POST", + &format!("/pulls/{number}/comments"), + Some(&json!({ "body": body.require()? })), + )?; + println!("Commented on pull request #{number}"); + println!("{}", forge.web_url(&format!("pulls/{number}"))); + } + PrAction::Diff { number, stat } => { + let diff = forge.api("GET", &format!("/pulls/{number}/diff"), None)?; + let files = diff.get("files").and_then(Value::as_array).cloned().unwrap_or_default(); + if files.is_empty() { + println!("No changes."); + return Ok(()); + } + for f in &files { + if *stat { + println!( + " {:<9} +{:<5} -{:<5} {}", + s(f, "status"), + n(f, "additions"), + n(f, "deletions"), + s(f, "path") + ); + continue; + } + let path = s(f, "path"); + println!("diff --rit a/{path} b/{path}"); + if f.get("binary").and_then(Value::as_bool).unwrap_or(false) { + println!("Binary file {path} ({})", s(f, "status")); + continue; + } + let patch = s(f, "patch"); + print!("{patch}"); + if !patch.ends_with('\n') && !patch.is_empty() { + println!(); + } + } + if *stat { + println!( + " {} file(s) changed, {} insertion(s), {} deletion(s)", + files.len(), + n(&diff, "additions"), + n(&diff, "deletions") + ); + } + } + PrAction::Checks { number } => { + let checks = forge.api("GET", &format!("/pulls/{number}/check-runs"), None)?; + let sha = s(&checks, "sha"); + println!( + "checks for {}: {}", + &sha[..sha.len().min(12)], + s(&checks, "state") + ); + let runs = checks.get("check_runs").and_then(Value::as_array).cloned().unwrap_or_default(); + if runs.is_empty() { + println!("No check runs reported yet."); + } + for run in &runs { + let conclusion = run.get("conclusion").and_then(Value::as_str).unwrap_or("-"); + println!(" {:<24} {:<12} {}", s(run, "name"), s(run, "status"), conclusion); + if let Some(url) = run.get("details_url").and_then(Value::as_str) { + println!(" {:<24} {url}", ""); + } + } + } + } + Ok(()) +} diff --git a/src/main.rs b/src/main.rs index 53e3582..e523571 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,8 @@ use std::io::{Read, Write}; use std::path::PathBuf; +mod forge_cli; + use anyhow::{bail, Context, Result}; use clap::{Args, Parser, Subcommand}; use rit::object::Object; @@ -96,6 +98,11 @@ enum Command { Stash(StashArgs), /// Serve one repository over the Git smart-HTTP protocol. ServeHttp(ServeHttpArgs), + /// Work with rithub issues: list, view, create, close, reopen, comment. + Issue(forge_cli::IssueArgs), + /// Work with rithub pull requests: list, view, create, merge, close, + /// reopen, comment, diff, checks. + Pr(forge_cli::PrArgs), } #[derive(Args)] @@ -419,6 +426,8 @@ fn run() -> Result<()> { Command::CherryPick(args) => cmd_cherry_pick_cli(&cli, args), Command::Stash(args) => cmd_stash_cli(&cli, args), Command::ServeHttp(args) => cmd_serve_http(args), + Command::Issue(args) => forge_cli::cmd_issue(&cli.repo, args), + Command::Pr(args) => forge_cli::cmd_pr(&cli.repo, args), } } diff --git a/src/remote.rs b/src/remote.rs index 4ffed63..cf8815f 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -23,6 +23,12 @@ //! URL userinfo for a single command, or `RIT_USERNAME` + `RIT_TOKEN` (a rithub //! personal access token). Local paths (`/srv/repo.git`, `file:///srv/repo.git`) //! are served in-process with no network at all. +//! +//! SSH remotes (`ssh://[user@]host[:port]/org/repo.git` or scp-style +//! `git@host:org/repo.git`) run the system `ssh` client with +//! `git-upload-pack ''` / `git-receive-pack ''`, exactly what the +//! rithub SSH transport serves; keys come from the user's ssh agent/config. +//! Set `RIT_SSH` to use a different ssh program. use std::collections::BTreeMap; use std::io::Write; @@ -156,6 +162,150 @@ pub fn remove_remote(repo: &Repository, name: &str) -> Result<()> { enum Endpoint { Local(PathBuf), Http { base: String, auth: Option<(String, String)> }, + /// `dest` is `[user@]host`; `path` is the repository path on the server. + Ssh { dest: String, port: Option, path: String }, +} + +/// Parse an SSH remote: `ssh://[user@]host[:port]/path` or scp-style +/// `[user@]host:path`. Returns `None` when `url` is not an SSH remote. +fn parse_ssh(url: &str) -> Result> { + let url = url.trim(); + if let Some(rest) = url.strip_prefix("ssh://").or_else(|| url.strip_prefix("git+ssh://")) { + let (authority, path) = rest + .split_once('/') + .ok_or_else(|| anyhow!("ssh remote URL has no repository path"))?; + let (dest, port) = match authority.rsplit_once(':') { + Some((d, p)) if !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()) => { + (d.to_string(), Some(p.parse::().context("invalid ssh port")?)) + } + _ => (authority.to_string(), None), + }; + if dest.is_empty() || dest.starts_with('-') { + bail!("invalid ssh host in remote URL"); + } + return Ok(Some(Endpoint::Ssh { dest, port, path: normalize_repo_path(path)? })); + } + if url.contains("://") { + return Ok(None); + } + // scp-style: `host:path` where the host part has no '/' and is not a + // local path that happens to contain a colon. + if let Some((host, path)) = url.split_once(':') { + if !host.is_empty() && !host.contains('/') && !path.is_empty() && !Path::new(url).exists() { + if host.starts_with('-') { + bail!("invalid ssh host in remote URL"); + } + return Ok(Some(Endpoint::Ssh { + dest: host.to_string(), + port: None, + path: normalize_repo_path(path)?, + })); + } + } + Ok(None) +} + +/// Normalize a server-side repository path to `org/repo.git`, rejecting +/// anything that could escape into shell syntax on the remote. +fn normalize_repo_path(path: &str) -> Result { + let path = path.trim_start_matches('/').trim_end_matches('/'); + if path.is_empty() + || path.contains("..") + || !path + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '/')) + { + bail!("invalid repository path in ssh remote URL"); + } + Ok(if path.ends_with(".git") { path.to_string() } else { format!("{path}.git") }) +} + +/// Read one pkt-line (raw, including its length header) from `reader`. +/// Returns `None` at EOF. A flush packet is returned as `b"0000"`. +fn read_pkt_raw(reader: &mut impl std::io::Read) -> Result>> { + let mut header = [0u8; 4]; + match reader.read_exact(&mut header) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None), + Err(e) => return Err(e.into()), + } + let len = std::str::from_utf8(&header) + .ok() + .and_then(|h| usize::from_str_radix(h, 16).ok()) + .ok_or_else(|| anyhow!("malformed pkt-line from ssh remote"))?; + let mut out = header.to_vec(); + if len >= 4 { + let mut payload = vec![0u8; len - 4]; + reader.read_exact(&mut payload)?; + out.extend(payload); + } + Ok(Some(out)) +} + +/// Run one stateful git service session over ssh: read the ref advertisement +/// (up to the first flush), then optionally send `request` and read the full +/// response until the server closes the stream. Returns `(advertisement, +/// response)`. +fn ssh_session( + dest: &str, + port: Option, + path: &str, + service: &str, + request: Option<&[u8]>, +) -> Result<(Vec, Vec)> { + use std::io::Read; + + let program = std::env::var("RIT_SSH").unwrap_or_else(|_| "ssh".to_string()); + let mut cmd = Command::new(&program); + cmd.arg("-T"); + if let Some(port) = port { + cmd.arg("-p").arg(port.to_string()); + } + cmd.arg("--") + .arg(dest) + .arg(format!("{service} '{path}'")) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()); + let mut child = cmd + .spawn() + .with_context(|| format!("running {program} (install OpenSSH to use ssh remotes)"))?; + let mut stdout = child.stdout.take().ok_or_else(|| anyhow!("ssh stdout unavailable"))?; + let mut stdin = child.stdin.take().ok_or_else(|| anyhow!("ssh stdin unavailable"))?; + + let mut advertisement = Vec::new(); + loop { + match read_pkt_raw(&mut stdout)? { + None => break, + Some(pkt) => { + let flush = pkt == b"0000"; + advertisement.extend(pkt); + if flush { + break; + } + } + } + } + + let mut response = Vec::new(); + match request { + Some(body) => { + stdin.write_all(body).context("sending request over ssh")?; + drop(stdin); + stdout.read_to_end(&mut response).context("reading ssh response")?; + } + None => { + // Nothing wanted: end the session politely with a flush. + let _ = stdin.write_all(b"0000"); + drop(stdin); + let _ = stdout.read_to_end(&mut response); + } + } + let status = child.wait().context("waiting for ssh")?; + if advertisement.is_empty() && !status.success() { + bail!("ssh remote {dest}:{path} failed ({status}); check your ssh key and repository access"); + } + Ok((advertisement, response)) } fn strip_password(url: &str) -> String { @@ -178,11 +328,14 @@ fn resolve_endpoint(url: &str) -> Result { if let Some(rest) = url.strip_prefix("file://") { return Ok(Endpoint::Local(PathBuf::from(rest))); } + if let Some(ssh) = parse_ssh(url)? { + return Ok(ssh); + } let Some((scheme, rest)) = url.split_once("://") else { return Ok(Endpoint::Local(PathBuf::from(url))); }; if scheme != "http" && scheme != "https" { - bail!("unsupported remote URL scheme '{scheme}' (use http, https, or a local path)"); + bail!("unsupported remote URL scheme '{scheme}' (use http, https, ssh, or a local path)"); } let (authority, path) = rest.split_once('/').map_or((rest, ""), |(a, p)| (a, p)); let (userinfo, host) = match authority.rsplit_once('@') { @@ -370,6 +523,10 @@ fn discover(endpoint: &Endpoint, service: &str) -> Result { check_status(status, &body, "listing remote refs")?; parse_advertisement(&body) } + Endpoint::Ssh { dest, port, path } => { + let (adv, _) = ssh_session(dest, *port, path, service, None)?; + parse_advertisement(&adv) + } } } @@ -451,6 +608,9 @@ fn fetch_into( check_status(status, &resp, "fetching objects")?; resp } + Endpoint::Ssh { dest, port, path } => { + ssh_session(dest, *port, path, "git-upload-pack", Some(&body))?.1 + } }; let pack = strip_nak(&response)?; report.objects = tx.stage_pack(pack)?; @@ -661,6 +821,9 @@ pub fn push(repo: &Repository, remote: &str, refspec: &str, force: bool) -> Resu check_status(status, &resp, "pushing")?; resp } + Endpoint::Ssh { dest, port, path } => { + ssh_session(dest, *port, path, "git-receive-pack", Some(&body))?.1 + } }; check_report_status(&response, &dst)?; // Keep the remote-tracking ref in sync with what we just pushed. @@ -709,3 +872,163 @@ fn check_report_status(response: &[u8], dst: &str) -> Result<()> { } Ok(()) } + +// --------------------------------------------------------------------------- +// Forge (rithub) JSON API client — used by `rit issue` / `rit pr` +// --------------------------------------------------------------------------- + +/// A rithub repository addressed through its JSON API, derived from a remote. +#[derive(Debug, Clone)] +pub struct ForgeRepo { + /// API origin, e.g. `https://rithub.example.com` (no trailing slash). + pub api_base: String, + pub org: String, + pub repo: String, + auth: Option<(String, String)>, +} + +/// Split `.../org/repo(.git)` into `(prefix, org, repo)`. +fn split_org_repo(path: &str) -> Result<(String, String, String)> { + let path = path.trim_matches('/'); + let path = path.strip_suffix(".git").unwrap_or(path); + let mut parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect(); + if parts.len() < 2 { + bail!("remote URL does not name an org/repo (expected ...//.git)"); + } + let repo = parts.pop().unwrap_or_default().to_string(); + let org = parts.pop().unwrap_or_default().to_string(); + Ok((parts.join("/"), org, repo)) +} + +/// Resolve the forge API target for a remote URL. HTTP(S) remotes use the same +/// origin; SSH remotes default to `https://`. `RIT_API_URL` overrides the +/// API origin in both cases. Credentials: URL userinfo, else `RIT_USERNAME` + +/// `RIT_TOKEN`. +pub fn forge_repo(url: &str) -> Result { + let override_base = std::env::var("RIT_API_URL") + .ok() + .map(|u| u.trim().trim_end_matches('/').to_string()) + .filter(|u| !u.is_empty()); + match resolve_endpoint(url)? { + Endpoint::Local(_) => bail!( + "remote '{url}' is a local path; issue and pr commands need a rithub http(s) or ssh remote" + ), + Endpoint::Http { base, auth } => { + let (scheme, rest) = base.split_once("://").unwrap_or(("https", base.as_str())); + let (host, path) = rest.split_once('/').unwrap_or((rest, "")); + let (prefix, org, repo) = split_org_repo(path)?; + let origin = if prefix.is_empty() { + format!("{scheme}://{host}") + } else { + format!("{scheme}://{host}/{prefix}") + }; + Ok(ForgeRepo { api_base: override_base.unwrap_or(origin), org, repo, auth }) + } + Endpoint::Ssh { dest, path, .. } => { + let host = dest.rsplit_once('@').map_or(dest.as_str(), |(_, h)| h).to_string(); + let (_, org, repo) = split_org_repo(&path)?; + let auth = std::env::var("RIT_TOKEN").ok().map(|token| { + (std::env::var("RIT_USERNAME").unwrap_or_else(|_| "token".to_string()), token) + }); + Ok(ForgeRepo { + api_base: override_base.unwrap_or_else(|| format!("https://{host}")), + org, + repo, + auth, + }) + } + } +} + +impl ForgeRepo { + /// `org/repo`. + pub fn slug(&self) -> String { + format!("{}/{}", self.org, self.repo) + } + + /// Browser URL for a path under this repository (e.g. `issues/3`). + pub fn web_url(&self, sub: &str) -> String { + format!("{}/{}/{}/{sub}", self.api_base, self.org, self.repo) + } + + /// Call `METHOD /api/orgs/{org}/repos/{repo}{sub}` with an optional JSON + /// body; returns the parsed JSON response (`null` for an empty body). + pub fn api( + &self, + method: &str, + sub: &str, + body: Option<&serde_json::Value>, + ) -> Result { + let url = format!("{}/api/orgs/{}/repos/{}{sub}", self.api_base, self.org, self.repo); + let payload = body.map(serde_json::to_vec).transpose()?; + let (status, response) = api_request(method, &url, self.auth.as_ref(), payload.as_deref())?; + let parsed: serde_json::Value = if response.iter().all(|b| b.is_ascii_whitespace()) { + serde_json::Value::Null + } else { + serde_json::from_slice(&response).unwrap_or_else(|_| { + serde_json::Value::String(String::from_utf8_lossy(&response).into_owned()) + }) + }; + if (200..300).contains(&status) { + return Ok(parsed); + } + let message = parsed + .get("error") + .and_then(|e| e.as_str()) + .map(str::to_string) + .unwrap_or_else(|| format!("HTTP {status}")); + match status { + 401 => bail!("{message} (set RIT_USERNAME and RIT_TOKEN to a rithub access token)"), + _ => bail!("{} {}: {message}", method, self.slug()), + } + } +} + +/// One JSON API request through the system `curl`; returns (status, body). +fn api_request( + method: &str, + url: &str, + auth: Option<&(String, String)>, + body: Option<&[u8]>, +) -> Result<(u16, Vec)> { + let out_path = temp_path("api-out"); + let in_path = temp_path("api-in"); + let mut config = format!("url = {}\n", curl_quote(url)); + if let Some((user, pass)) = auth { + config.push_str(&format!("user = {}\n", curl_quote(&format!("{user}:{pass}")))); + } + let mut cmd = Command::new("curl"); + cmd.args(["--silent", "--show-error", "--proto", "=http,https", "--max-redirs", "0"]) + .args(["-X", method]) + .args(["-H", "Accept: application/json"]) + .args(["-A", "rit/0.1"]) + .arg("-o") + .arg(&out_path) + .args(["-w", "%{http_code}", "-K", "-"]); + if let Some(data) = body { + std::fs::write(&in_path, data).context("staging request body")?; + cmd.args(["-H", "Content-Type: application/json"]) + .arg("--data-binary") + .arg(format!("@{}", in_path.display())); + } + let mut child = cmd + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .context("running curl (install curl to use rithub issue/pr commands)")?; + child + .stdin + .take() + .ok_or_else(|| anyhow!("curl stdin unavailable"))? + .write_all(config.as_bytes())?; + let output = child.wait_with_output().context("waiting for curl")?; + let _ = std::fs::remove_file(&in_path); + let response = std::fs::read(&out_path).unwrap_or_default(); + let _ = std::fs::remove_file(&out_path); + if !output.status.success() { + bail!("request to {url} failed: {}", String::from_utf8_lossy(&output.stderr).trim()); + } + let status: u16 = String::from_utf8_lossy(&output.stdout).trim().parse().unwrap_or(0); + Ok((status, response)) +}