Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
269 changes: 215 additions & 54 deletions src/commands/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@

use crate::context::GlobalContext;
use crate::errors::{CliError, CliResult};
use clap::{Arg, ArgMatches, Command};
use crate::utils::browser;
use clap::{Arg, ArgAction, ArgMatches, Command};
use serde::Deserialize;

pub fn command() -> Command {
Command::new("git")
.about("Git-related helpers")
.subcommand_required(true)
.arg_required_else_help(true)
.subcommand(
Command::new("coauthor")
.about("Generate GitHub no-reply co-author lines")
Expand All @@ -33,68 +36,226 @@ pub fn command() -> Command {
.default_value("origin"),
),
)
.subcommand(
Command::new("open")
.about("Open this GitHub repo, issue, pull request, or commit in a browser")
.arg(
Arg::new("pr")
.help("Open the pull request for the current branch, number, or commit")
.long("pr")
.short('p')
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("targets")
.help("Optional `pr`, issue/PR number, or commit hash")
.num_args(0..=2)
.value_name("TARGET"),
)
.arg(
Arg::new("remote")
.short('r')
.long("remote")
.help("Git remote to use")
.default_value("origin"),
),
)
}

pub fn exec(gctx: &mut GlobalContext, args: &ArgMatches) -> CliResult {
if let Some(sub) = args.subcommand_matches("coauthor") {
for user in sub.get_many::<String>("usernames").unwrap() {
match fetch_github_user(user) {
Ok(line) => gctx.shell().note(line),
Err(e) => gctx.shell().error(format!("{user}: {e}")),
}
}
} else if let Some(sub) = args.subcommand_matches("prs") {
let remote = sub.get_one::<String>("remote").unwrap();
let (owner, repo) = match parse_owner_repo(remote) {
Ok(pair) => pair,
Err(e) => return Err(CliError::from(e)),
};

let client = reqwest::blocking::Client::new();
let prs = match fetch_open_prs(&client, &owner, &repo) {
Ok(v) => v,
Err(e) => return Err(CliError::from(e)),
};

if prs.is_empty() {
gctx.shell().note("No open pull requests found.");
return Ok(());
match args.subcommand() {
Some(("coauthor", sub)) => coauthor(gctx, sub),
Some(("prs", sub)) => prs(gctx, sub),
Some(("open", sub)) => open(gctx, sub),
_ => Err(CliError::from("no `git` subcommand provided")),
}
}

fn coauthor(gctx: &mut GlobalContext, args: &ArgMatches) -> CliResult {
for user in args.get_many::<String>("usernames").unwrap() {
match fetch_github_user(user) {
Ok(line) => gctx.shell().note(line),
Err(e) => gctx.shell().error(format!("{user}: {e}")),
}
}

Ok(())
}

fn prs(gctx: &mut GlobalContext, args: &ArgMatches) -> CliResult {
let remote = args.get_one::<String>("remote").unwrap();
let (owner, repo) = parse_owner_repo(remote).map_err(CliError::from)?;

let client = reqwest::blocking::Client::new();
let prs = fetch_open_prs(&client, &owner, &repo).map_err(CliError::from)?;

if prs.is_empty() {
gctx.shell().note("No open pull requests found.");
return Ok(());
}

for pr in prs {
let changes = fetch_changes_count(&client, &owner, &repo, pr.number).unwrap_or(0);

gctx.shell().note(format!(
"PR #{} {}{}",
pr.number,
if pr.draft { "[DRAFT] " } else { "" },
pr.title
));
gctx.shell().note(format!(
" Assignees : {}",
pr.assignees
.iter()
.map(|u| u.login.as_str())
.collect::<Vec<_>>()
.join(", ")
));
gctx.shell().note(format!(
" Reviewers : {}",
pr.requested_reviewers
.iter()
.map(|u| u.login.as_str())
.collect::<Vec<_>>()
.join(", ")
));
gctx.shell()
.note(format!(" Change requests pending: {changes}"));
gctx.shell().note("------------------------------");
}

Ok(())
}

for pr in prs {
let changes = fetch_changes_count(&client, &owner, &repo, pr.number).unwrap_or(0);

gctx.shell().note(format!(
"PR #{} {}{}",
pr.number,
if pr.draft { "[DRAFT] " } else { "" },
pr.title
));
gctx.shell().note(format!(
" Assignees : {}",
pr.assignees
.iter()
.map(|u| u.login.as_str())
.collect::<Vec<_>>()
.join(", ")
));
gctx.shell().note(format!(
" Reviewers : {}",
pr.requested_reviewers
.iter()
.map(|u| u.login.as_str())
.collect::<Vec<_>>()
.join(", ")
));
gctx.shell()
.note(format!(" Change requests pending: {changes}"));
gctx.shell().note("------------------------------");
fn open(gctx: &mut GlobalContext, args: &ArgMatches) -> CliResult {
let remote = args.get_one::<String>("remote").unwrap();
let (owner, repo) = parse_owner_repo(remote).map_err(CliError::from)?;
let base_url = format!("https://github.com/{owner}/{repo}");
let (pr_mode, target) = open_args(args)?;
let url = if pr_mode {
pull_request_url(gctx.cwd(), &owner, &repo, &base_url, target)?
} else {
target_url(&base_url, target)?
};

browser::open_url(&url)?;
gctx.shell().note(format!("Opened {url}"));
Ok(())
}

fn open_args(args: &ArgMatches) -> Result<(bool, Option<&str>), CliError> {
let pr_flag = args.get_flag("pr");
let targets = args
.get_many::<String>("targets")
.map(|values| values.map(String::as_str).collect::<Vec<_>>())
.unwrap_or_default();

match targets.as_slice() {
["pr"] => Ok((true, None)),
["pr", target] => Ok((true, Some(*target))),
[] => Ok((pr_flag, None)),
[target] => Ok((pr_flag, Some(*target))),
_ => Err(CliError::from(
"expected `bp git open [pr] [issue|pull-request|commit]`",
)),
}
}

fn target_url(base_url: &str, target: Option<&str>) -> Result<String, CliError> {
match target {
None => Ok(base_url.to_string()),
Some(target) if is_issue_number(target) => Ok(format!("{base_url}/issues/{target}")),
Some(target) if is_commit_hash(target) => Ok(format!("{base_url}/commit/{target}")),
Some(target) => Err(CliError::from(format!(
"`{target}` is not a pull request/issue number or commit hash"
))),
}
}

fn pull_request_url(
cwd: &std::path::Path,
owner: &str,
repo: &str,
base_url: &str,
target: Option<&str>,
) -> Result<String, CliError> {
let number = match target {
Some(target) if is_issue_number(target) => target.to_string(),
Some(target) if is_commit_hash(target) => {
pull_request_for_commit(cwd, owner, repo, target)?
}
Some(target) => {
return Err(CliError::from(format!(
"`{target}` is not a pull request number or commit hash"
)))
}
None => pull_request_for_current_branch(cwd)?,
};

Ok(format!("{base_url}/pull/{number}"))
}

fn pull_request_for_current_branch(cwd: &std::path::Path) -> Result<String, CliError> {
let output = crate::utils::command::output(
"gh",
&["pr", "view", "--json", "number", "--jq", ".number"],
Some(cwd),
)
.map_err(|e| {
CliError::from(format!(
"failed to find a pull request for the current branch: {}",
e.message
))
})?;
non_empty_output(output, "no pull request found for the current branch")
}

fn pull_request_for_commit(
cwd: &std::path::Path,
owner: &str,
repo: &str,
commit: &str,
) -> Result<String, CliError> {
let api_path = format!("repos/{owner}/{repo}/commits/{commit}/pulls");
let output = crate::utils::command::output(
"gh",
&[
"api",
&api_path,
"-H",
"Accept: application/vnd.github+json",
"--jq",
".[0].number",
],
Some(cwd),
)
.map_err(|e| {
CliError::from(format!(
"failed to find a pull request containing `{commit}`: {}",
e.message
))
})?;
non_empty_output(
output,
format!("no pull request found containing `{commit}`"),
)
}

fn non_empty_output(output: String, message: impl Into<String>) -> Result<String, CliError> {
let output = output.trim();
if output.is_empty() || output == "null" {
Err(CliError::from(message.into()))
} else {
return Err(CliError::from("no `git` subcommand provided"));
Ok(output.to_string())
}
}

Ok(())
fn is_issue_number(value: &str) -> bool {
!value.is_empty() && value.chars().all(|c| c.is_ascii_digit())
}

fn is_commit_hash(value: &str) -> bool {
(7..=40).contains(&value.len()) && value.chars().all(|c| c.is_ascii_hexdigit())
}

fn fetch_github_user(username: &str) -> Result<String, String> {
Expand Down
33 changes: 33 additions & 0 deletions src/utils/browser.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use std::process::Command as ProcessCommand;

use crate::errors::{CliError, CliResult};

pub fn open_url(url: &str) -> CliResult {
#[cfg(target_os = "macos")]
let mut command = {
let mut command = ProcessCommand::new("open");
command.arg(url);
command
};

#[cfg(target_os = "windows")]
let mut command = {
let mut command = ProcessCommand::new("cmd");
command.args(["/C", "start", "", url]);
command
};

#[cfg(all(unix, not(target_os = "macos")))]
let mut command = {
let mut command = ProcessCommand::new("xdg-open");
command.arg(url);
command
};

let status = command.status()?;
if status.success() {
Ok(())
} else {
Err(CliError::from(format!("failed to open {url}")))
}
}
1 change: 1 addition & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod browser;
pub mod command;
pub mod gh;
pub mod table;
Expand Down
Loading