|  | 
|  | 1 | +use std::collections::HashMap; | 
|  | 2 | +use std::sync::LazyLock; | 
|  | 3 | + | 
|  | 4 | +use crate::config::BackportConfig; | 
|  | 5 | +use crate::github::{IssuesAction, IssuesEvent, Label}; | 
|  | 6 | +use crate::handlers::Context; | 
|  | 7 | +use anyhow::Context as AnyhowContext; | 
|  | 8 | +use futures::future::join_all; | 
|  | 9 | +use regex::Regex; | 
|  | 10 | +use tracing as log; | 
|  | 11 | + | 
|  | 12 | +// See https://docs.github.com/en/issues/tracking-your-work-with-issues/creating-issues/linking-a-pull-request-to-an-issue | 
|  | 13 | +// See tests to see what matches | 
|  | 14 | +static CLOSES_ISSUE_REGEXP: LazyLock<Regex> = LazyLock::new(|| { | 
|  | 15 | +    Regex::new("(?i)(?P<action>close[sd]*|fix([e]*[sd]*)?|resolve[sd]*)(?P<spaces>:? +)(?P<org_repo>[a-zA-Z0-9_-]*/[a-zA-Z0-9_-]*)?#(?P<issue_num>[0-9]+)").unwrap() | 
|  | 16 | +}); | 
|  | 17 | + | 
|  | 18 | +const BACKPORT_LABELS: [&str; 4] = [ | 
|  | 19 | +    "beta-nominated", | 
|  | 20 | +    "beta-accepted", | 
|  | 21 | +    "stable-nominated", | 
|  | 22 | +    "stable-accepted", | 
|  | 23 | +]; | 
|  | 24 | + | 
|  | 25 | +const REGRESSION_LABELS: [&str; 3] = [ | 
|  | 26 | +    "regression-from-stable-to-nightly", | 
|  | 27 | +    "regression-from-stable-to-beta", | 
|  | 28 | +    "regression-from-stable-to-stable", | 
|  | 29 | +]; | 
|  | 30 | + | 
|  | 31 | +// auto-nominate for backport only patches fixing high/critical regressions | 
|  | 32 | +// For `P-{medium,low}` regressions, let the author decide | 
|  | 33 | +const PRIORITY_LABELS: [&str; 2] = ["P-high", "P-critical"]; | 
|  | 34 | + | 
|  | 35 | +#[derive(Default)] | 
|  | 36 | +pub(crate) struct BackportInput { | 
|  | 37 | +    // Issue(s) fixed by this PR | 
|  | 38 | +    ids: Vec<u64>, | 
|  | 39 | +    // Handler configuration, it's a compound value of (required_issue_label -> add_labels) | 
|  | 40 | +    labels: HashMap<String, Vec<String>>, | 
|  | 41 | +} | 
|  | 42 | + | 
|  | 43 | +pub(super) async fn parse_input( | 
|  | 44 | +    _ctx: &Context, | 
|  | 45 | +    event: &IssuesEvent, | 
|  | 46 | +    config: Option<&BackportConfig>, | 
|  | 47 | +) -> Result<Option<BackportInput>, String> { | 
|  | 48 | +    let config = match config { | 
|  | 49 | +        Some(config) => config, | 
|  | 50 | +        None => return Ok(None), | 
|  | 51 | +    }; | 
|  | 52 | + | 
|  | 53 | +    // Only handle events when the PR is opened or the first comment is edited | 
|  | 54 | +    let should_check = matches!(event.action, IssuesAction::Opened | IssuesAction::Edited); | 
|  | 55 | +    if !should_check || !event.issue.is_pr() { | 
|  | 56 | +        log::debug!( | 
|  | 57 | +            "Skipping backport event because: IssuesAction = {:?} issue.is_pr() {}", | 
|  | 58 | +            event.action, | 
|  | 59 | +            event.issue.is_pr() | 
|  | 60 | +        ); | 
|  | 61 | +        return Ok(None); | 
|  | 62 | +    } | 
|  | 63 | +    let pr = &event.issue; | 
|  | 64 | + | 
|  | 65 | +    let pr_labels: Vec<&str> = pr.labels.iter().map(|l| l.name.as_str()).collect(); | 
|  | 66 | +    if contains_any(&pr_labels, &BACKPORT_LABELS) { | 
|  | 67 | +        log::debug!("PR #{} already has a backport label", pr.number); | 
|  | 68 | +        return Ok(None); | 
|  | 69 | +    } | 
|  | 70 | + | 
|  | 71 | +    // Retrieve backport config for this PR, based on its team label(s) | 
|  | 72 | +    // If the PR has no team label matching any [backport.*.required-pr-labels] config, the backport labelling will be skipped | 
|  | 73 | +    let mut input = BackportInput::default(); | 
|  | 74 | +    let valid_configs: Vec<_> = config | 
|  | 75 | +        .configs | 
|  | 76 | +        .iter() | 
|  | 77 | +        .clone() | 
|  | 78 | +        .filter(|(_cfg_name, cfg)| { | 
|  | 79 | +            let required_pr_labels: Vec<&str> = | 
|  | 80 | +                cfg.required_pr_labels.iter().map(|l| l.as_str()).collect(); | 
|  | 81 | +            if !contains_any(&pr_labels, &required_pr_labels) { | 
|  | 82 | +                log::warn!( | 
|  | 83 | +                    "Skipping backport nomination: PR is missing one required label: {:?}", | 
|  | 84 | +                    pr_labels | 
|  | 85 | +                ); | 
|  | 86 | +                return false; | 
|  | 87 | +            } | 
|  | 88 | +            input | 
|  | 89 | +                .labels | 
|  | 90 | +                .insert(cfg.required_issue_label.clone(), cfg.add_labels.clone()); | 
|  | 91 | +            true | 
|  | 92 | +        }) | 
|  | 93 | +        .collect(); | 
|  | 94 | +    if valid_configs.is_empty() { | 
|  | 95 | +        log::warn!( | 
|  | 96 | +            "Skipping backport nomination: could not find a suitable backport config. Please ensure the triagebot.toml has a `[backport.*.required-pr-labels]` section matching the team label(s) for PR #{}.", | 
|  | 97 | +            pr.number | 
|  | 98 | +        ); | 
|  | 99 | +        return Ok(None); | 
|  | 100 | +    } | 
|  | 101 | + | 
|  | 102 | +    // Check marker text in the opening comment of the PR to retrieve the issue(s) being fixed | 
|  | 103 | +    for caps in CLOSES_ISSUE_REGEXP.captures_iter(&event.issue.body) { | 
|  | 104 | +        let id = caps | 
|  | 105 | +            .name("issue_num") | 
|  | 106 | +            .ok_or_else(|| format!("failed to get issue_num from {caps:?}"))? | 
|  | 107 | +            .as_str(); | 
|  | 108 | + | 
|  | 109 | +        let id = match id.parse::<u64>() { | 
|  | 110 | +            Ok(id) => id, | 
|  | 111 | +            Err(err) => { | 
|  | 112 | +                return Err(format!("Failed to parse issue id `{id}`, error: {err}")); | 
|  | 113 | +            } | 
|  | 114 | +        }; | 
|  | 115 | +        if let Some(org_repo) = caps.name("org_repo") | 
|  | 116 | +            && org_repo.as_str() != event.repository.full_name | 
|  | 117 | +        { | 
|  | 118 | +            log::info!( | 
|  | 119 | +                "Skipping backport nomination: Ignoring issue#{id} pointing to a different git repository: Expected {0}, found {org_repo:?}", | 
|  | 120 | +                event.repository.full_name | 
|  | 121 | +            ); | 
|  | 122 | +            continue; | 
|  | 123 | +        } | 
|  | 124 | +        input.ids.push(id); | 
|  | 125 | +    } | 
|  | 126 | + | 
|  | 127 | +    if input.ids.is_empty() || input.labels.is_empty() { | 
|  | 128 | +        return Ok(None); | 
|  | 129 | +    } | 
|  | 130 | + | 
|  | 131 | +    log::debug!( | 
|  | 132 | +        "Will handle event action {:?} in backport. Regression IDs found {:?}", | 
|  | 133 | +        event.action, | 
|  | 134 | +        input.ids | 
|  | 135 | +    ); | 
|  | 136 | + | 
|  | 137 | +    Ok(Some(input)) | 
|  | 138 | +} | 
|  | 139 | + | 
|  | 140 | +pub(super) async fn handle_input( | 
|  | 141 | +    ctx: &Context, | 
|  | 142 | +    _config: &BackportConfig, | 
|  | 143 | +    event: &IssuesEvent, | 
|  | 144 | +    input: BackportInput, | 
|  | 145 | +) -> anyhow::Result<()> { | 
|  | 146 | +    let pr = &event.issue; | 
|  | 147 | + | 
|  | 148 | +    // Retrieve the issue(s) this pull request closes | 
|  | 149 | +    let issues = input | 
|  | 150 | +        .ids | 
|  | 151 | +        .iter() | 
|  | 152 | +        .copied() | 
|  | 153 | +        .map(|id| async move { event.repository.get_issue(&ctx.github, id).await }); | 
|  | 154 | +    let issues = join_all(issues).await; | 
|  | 155 | + | 
|  | 156 | +    // Add backport nomination label to the pull request | 
|  | 157 | +    for issue in issues { | 
|  | 158 | +        if let Err(ref err) = issue { | 
|  | 159 | +            log::warn!("Failed to get issue: {:?}", err); | 
|  | 160 | +            continue; | 
|  | 161 | +        } | 
|  | 162 | +        let issue = issue.context("failed to get issue")?; | 
|  | 163 | +        let issue_labels: Vec<&str> = issue.labels.iter().map(|l| l.name.as_str()).collect(); | 
|  | 164 | + | 
|  | 165 | +        // Check issue for a prerequisite priority label | 
|  | 166 | +        // If none, skip this issue | 
|  | 167 | +        if !contains_any(&issue_labels, &PRIORITY_LABELS) { | 
|  | 168 | +            continue; | 
|  | 169 | +        } | 
|  | 170 | + | 
|  | 171 | +        // Get the labels to be added the PR according to the matching (required) regression label | 
|  | 172 | +        // that is found in the configuration that this handler has received | 
|  | 173 | +        // If no regression label is found, skip this issue | 
|  | 174 | +        let add_labels = issue_labels.iter().find_map(|l| input.labels.get(*l)); | 
|  | 175 | +        if add_labels.is_none() { | 
|  | 176 | +            log::warn!( | 
|  | 177 | +                "Skipping backport nomination: nothing to do for issue #{}. No config found for regression label ({:?})", | 
|  | 178 | +                issue.number, | 
|  | 179 | +                REGRESSION_LABELS | 
|  | 180 | +            ); | 
|  | 181 | +            continue; | 
|  | 182 | +        } | 
|  | 183 | + | 
|  | 184 | +        // Add backport nomination label(s) to PR | 
|  | 185 | +        let mut new_labels = pr.labels().to_owned(); | 
|  | 186 | +        new_labels.extend( | 
|  | 187 | +            add_labels | 
|  | 188 | +                .expect("failed to unwrap add_labels") | 
|  | 189 | +                .iter() | 
|  | 190 | +                .cloned() | 
|  | 191 | +                .map(|name| Label { name }), | 
|  | 192 | +        ); | 
|  | 193 | +        log::debug!( | 
|  | 194 | +            "PR#{} adding labels for backport {:?}", | 
|  | 195 | +            pr.number, | 
|  | 196 | +            add_labels | 
|  | 197 | +        ); | 
|  | 198 | +        let _ = pr | 
|  | 199 | +            .add_labels(&ctx.github, new_labels) | 
|  | 200 | +            .await | 
|  | 201 | +            .context("failed to add backport labels to the PR"); | 
|  | 202 | +    } | 
|  | 203 | + | 
|  | 204 | +    Ok(()) | 
|  | 205 | +} | 
|  | 206 | + | 
|  | 207 | +fn contains_any(haystack: &[&str], needles: &[&str]) -> bool { | 
|  | 208 | +    needles.iter().any(|needle| haystack.contains(needle)) | 
|  | 209 | +} | 
|  | 210 | + | 
|  | 211 | +#[cfg(test)] | 
|  | 212 | +mod tests { | 
|  | 213 | +    use crate::handlers::backport::CLOSES_ISSUE_REGEXP; | 
|  | 214 | + | 
|  | 215 | +    #[tokio::test] | 
|  | 216 | +    async fn backport_match_comment() { | 
|  | 217 | +        let test_strings = vec![ | 
|  | 218 | +            ("close #10", vec![10]), | 
|  | 219 | +            ("closes #10", vec![10]), | 
|  | 220 | +            ("closed #10", vec![10]), | 
|  | 221 | +            ("Closes #10", vec![10]), | 
|  | 222 | +            ("close  #10", vec![10]), | 
|  | 223 | +            ("close rust-lang/rust#10", vec![10]), | 
|  | 224 | +            ("cLose: rust-lang/rust#10", vec![10]), | 
|  | 225 | +            ("fix #10", vec![10]), | 
|  | 226 | +            ("fixes #10", vec![10]), | 
|  | 227 | +            ("fixed #10", vec![10]), | 
|  | 228 | +            ("resolve #10", vec![10]), | 
|  | 229 | +            ("resolves #10", vec![10]), | 
|  | 230 | +            ("resolved #10", vec![10]), | 
|  | 231 | +            ( | 
|  | 232 | +                "Fixes #20, Resolves #21, closed #22, LOL #23", | 
|  | 233 | +                vec![20, 21, 22], | 
|  | 234 | +            ), | 
|  | 235 | +            ("Resolved #10", vec![10]), | 
|  | 236 | +            ("Fixes #10", vec![10]), | 
|  | 237 | +            ("Closes #10", vec![10]), | 
|  | 238 | +        ]; | 
|  | 239 | +        for test_case in test_strings { | 
|  | 240 | +            let mut ids: Vec<u64> = vec![]; | 
|  | 241 | +            let test_str = test_case.0; | 
|  | 242 | +            let expected = test_case.1; | 
|  | 243 | +            for caps in CLOSES_ISSUE_REGEXP.captures_iter(test_str) { | 
|  | 244 | +                // eprintln!("caps {:?}", caps); | 
|  | 245 | +                let id = &caps["issue_num"]; | 
|  | 246 | +                ids.push(id.parse::<u64>().unwrap()); | 
|  | 247 | +            } | 
|  | 248 | +            // eprintln!("ids={:?}", ids); | 
|  | 249 | +            assert_eq!(ids, expected); | 
|  | 250 | +        } | 
|  | 251 | +    } | 
|  | 252 | +} | 
0 commit comments