Skip to content
Open
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
3 changes: 0 additions & 3 deletions src/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1319,9 +1319,6 @@ impl IssuesEvent {
}
}

#[derive(Debug, serde::Deserialize)]
struct PullRequestEventFields {}

#[derive(Debug, serde::Deserialize)]
pub struct WorkflowRunJob {
pub name: String,
Expand Down
5 changes: 1 addition & 4 deletions src/handlers/backport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::sync::LazyLock;
use crate::config::BackportConfig;
use crate::github::{IssuesAction, IssuesEvent, Label};
use crate::handlers::Context;
use crate::utils::contains_any;
use anyhow::Context as AnyhowContext;
use futures::future::join_all;
use regex::Regex;
Expand Down Expand Up @@ -204,10 +205,6 @@ pub(super) async fn handle_input(
Ok(())
}

fn contains_any(haystack: &[&str], needles: &[&str]) -> bool {
needles.iter().any(|needle| haystack.contains(needle))
}

#[cfg(test)]
mod tests {
use crate::handlers::backport::CLOSES_ISSUE_REGEXP;
Expand Down
4 changes: 4 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,7 @@ pub(crate) async fn is_repo_autorized(

Ok(true)
}

pub fn contains_any(haystack: &[&str], needles: &[&str]) -> bool {
needles.iter().any(|needle| haystack.contains(needle))
}
87 changes: 85 additions & 2 deletions src/zulip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::handlers::docs_update::docs_update;
use crate::handlers::pr_tracking::get_assigned_prs;
use crate::handlers::project_goals::{self, ping_project_goals_owners};
use crate::interactions::ErrorComment;
use crate::utils::pluralize;
use crate::utils::{contains_any, pluralize};
use crate::zulip::api::{MessageApiResponse, Recipient};
use crate::zulip::client::ZulipClient;
use crate::zulip::commands::{
Expand All @@ -24,12 +24,34 @@ use axum::Json;
use axum::extract::State;
use axum::extract::rejection::JsonRejection;
use axum::response::IntoResponse;
use commands::BackportArgs;
use octocrab::Octocrab;
use rust_team_data::v1::{TeamKind, TeamMember};
use std::cmp::Reverse;
use std::fmt::Write as _;
use std::sync::Arc;
use subtle::ConstantTimeEq;
use tracing as log;
use tracing::log;

fn get_text_backport_approved(channel: &str, verb: &str, zulip_link: &str) -> String {
format!("
{channel} backport {verb} as per compiler team [on Zulip]({zulip_link}). A backport PR will be authored by the release team at the end of the current development cycle. Backport labels handled by them.

@rustbot label +{channel}-accepted")
}

fn get_text_backport_declined(channel: &str, verb: &str, zulip_link: &str) -> String {
format!(
"
{channel} backport {verb} as per compiler team [on Zulip]({zulip_link}).

@rustbot label -{channel}-nominated"
)
}

const BACKPORT_CHANNELS: [&str; 2] = ["beta", "stable"];
const BACKPORT_VERBS_APPROVE: [&str; 4] = ["accept", "accepted", "approve", "approved"];
const BACKPORT_VERBS_DECLINE: [&str; 2] = ["decline", "declined"];

#[derive(Debug, serde::Deserialize)]
pub struct Request {
Expand Down Expand Up @@ -302,10 +324,71 @@ async fn handle_command<'a>(
.map_err(|e| format_err!("Failed to await at this time: {e:?}")),
StreamCommand::PingGoals(args) => ping_goals_cmd(ctx, gh_id, message_data, &args).await,
StreamCommand::DocsUpdate => trigger_docs_update(message_data, &ctx.zulip),
StreamCommand::Backport(args) => {
accept_decline_backport(message_data, &ctx.octocrab, &ctx.zulip, &args).await
}
}
}
}

// TODO: shorter variant of this command (f.e. `backport accept` or even `accept`) that infers everything from the Message payload
async fn accept_decline_backport(
message_data: &Message,
octo_client: &Octocrab,
zulip_client: &ZulipClient,
args_data: &BackportArgs,
) -> anyhow::Result<Option<String>> {
let message = message_data.clone();
let args = args_data.clone();
let stream_id = message.stream_id.unwrap();
let subject = message.subject.unwrap();
let verb = args.verb.to_lowercase();
let octo_client = octo_client.clone();

// Repository owner and name are hardcoded
// This command is only used in this repository
let repo_owner = "rust-lang";
let repo_name = "rust";

// validate command parameters
if !contains_any(&[args.channel.to_lowercase().as_str()], &BACKPORT_CHANNELS) {
return Err(anyhow::anyhow!(
"Parser error: unknown channel (allowed: {BACKPORT_CHANNELS:?})."
));
}

// TODO: factor out the Zulip "URL encoder" to make it practical to use
let zulip_send_req = crate::zulip::MessageApiRequest {
recipient: Recipient::Stream {
id: stream_id,
topic: &subject,
},
content: "",
};
let zulip_link = zulip_send_req.url(zulip_client);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: for how the Message API works today, we can't pin exactly a single message so the link in the GitHub comment will be to the whole topic, which is a bit inconvenient but hopefully will be solved by Zulip. I'd rather wait on them for a correct fix rather us add hacks to make it work.


let message_body = if contains_any(&[verb.as_str()], &BACKPORT_VERBS_APPROVE) {
get_text_backport_approved(&args.channel, &verb, &zulip_link)
} else if contains_any(&[verb.as_str()], &BACKPORT_VERBS_DECLINE) {
get_text_backport_declined(&args.channel, &verb, &zulip_link)
} else {
return Err(anyhow::anyhow!(
"Parser error: unknown verb (allowed: {BACKPORT_VERBS_APPROVE:?} or {BACKPORT_VERBS_DECLINE:?})"
));
};

let res = octo_client
.issues(repo_owner, repo_name)
.create_comment(args.pr_num, &message_body)
.await
.with_context(|| anyhow::anyhow!("unable to post comment on #{}", args.pr_num));
if res.is_err() {
tracing::error!("failed to post comment: {0:?}", res.err());
}

Ok(Some("".to_string()))
}

async fn ping_goals_cmd(
ctx: Arc<Context>,
gh_id: u64,
Expand Down
35 changes: 34 additions & 1 deletion src/zulip/commands.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::db::notifications::Identifier;
use crate::db::review_prefs::RotationMode;
use crate::github::PullRequestNumber;
use clap::{ColorChoice, Parser};
use std::num::NonZeroU32;
use std::str::FromStr;
Expand Down Expand Up @@ -161,8 +162,10 @@ pub enum StreamCommand {
Read,
/// Ping project goal owners.
PingGoals(PingGoalsArgs),
/// Update docs
/// Update docs.
DocsUpdate,
/// Accept or decline a backport.
Backport(BackportArgs),
}

#[derive(clap::Parser, Debug, PartialEq, Clone)]
Expand All @@ -173,6 +176,16 @@ pub struct PingGoalsArgs {
pub next_update: String,
}

#[derive(clap::Parser, Debug, PartialEq, Clone)]
pub struct BackportArgs {
/// Release channel this backport is pointing to. Allowed: "beta" or "stable".
pub channel: String,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please use an enum here for the channel and the verb, and either generate the parser with #[derive(clap::ValueEnum)], or write it manually with FromStr? That way we won't have to check for invalid data in the backport handler, and we'll get a nice error message and a hint (in case of misspelling) for free.

/// Accept or decline this backport? Allowed: "accept", "accepted", "approve", "approved", "decline", "declined".
pub verb: String,
/// PR to be backported
pub pr_num: PullRequestNumber,
}

/// Helper function to parse CLI arguments without any colored help or error output.
pub fn parse_cli<'a, T: Parser, I: Iterator<Item = &'a str>>(input: I) -> anyhow::Result<T> {
fn allow_title_case(sub: clap::Command) -> clap::Command {
Expand Down Expand Up @@ -292,6 +305,26 @@ mod tests {
assert_eq!(parse_stream(&["await"]), StreamCommand::EndTopic);
}

#[test]
fn backports_command() {
assert_eq!(
parse_stream(&["backport", "beta", "accept", "123456"]),
StreamCommand::Backport(BackportArgs {
channel: "beta".to_string(),
verb: "accept".to_string(),
pr_num: 123456
})
);
assert_eq!(
parse_stream(&["backport", "stable", "decline", "123456"]),
StreamCommand::Backport(BackportArgs {
channel: "stable".to_string(),
verb: "decline".to_string(),
pr_num: 123456
})
);
}

fn parse_chat(input: &[&str]) -> ChatCommand {
parse_cli::<ChatCommand, _>(input.into_iter().copied()).unwrap()
}
Expand Down