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
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,41 @@ allowOverrideAction: false
> boundary because repository maintainers with write access can still change
> the repository configuration.

### Labeling pull requests

DCO2 can keep a label in sync with the DCO check result. When enabled, the label is added to open pull requests whose DCO check fails, and removed when the check passes (including when it passes thanks to remediation commits or the `Set DCO to pass` action).

By default, this feature is **disabled**. To enable it, set the name of the label to use in the [configuration file](docs/config/dco.yml) (`.github/dco.yml`):

```yaml
label: needs-dco
```

The label name can have up to 50 characters. Blank names, names longer than 50 characters, `.` and `..` are ignored, and labeling stays disabled. If the label does not exist in the repository, DCO2 creates it. Existing labels (including their colors and descriptions) are never modified.

Labeling requires the `Pull requests: write` permission (`Issues: write` can be used instead, as it also allows managing labels):

- When using the [public DCO2 application](https://github.com/apps/dco-2), the organization or account owner must approve the updated permissions requested by the application.
- When running your own instance of DCO2, add this permission to your GitHub App. No changes to the DCO2 server configuration are required.

Approving this permission is optional. DCO checks keep working without it, but DCO2 will not label pull requests. It may take up to about an hour for labeling to start after approving the permission or updating the configuration file.

Labeling is done on a best-effort basis:

- Closed pull requests are never labeled or unlabeled.
- Disabling the option does not remove labels already applied.
- When several pull requests from forks share the same head commit, the `Set DCO to pass` action only removes the label from the pull request whose check run was used. The label is removed from the other pull requests on the next push, or it can be removed manually.
- Pull requests that were already open when labeling was enabled are labeled the next time new commits are pushed to them. To label them right away, you can use the [label-open-prs.sh](docs/scripts/label-open-prs.sh) sample script, which requires bash 4 or later and the [GitHub CLI](https://cli.github.com):

```text
docs/scripts/label-open-prs.sh --dry-run OWNER/REPO needs-dco
```

The script labels the open pull requests whose latest DCO2 check failed. Remove `--dry-run` to apply the changes, and use `--app-slug` to set your GitHub App's slug when running your own instance of DCO2. Using the `Set DCO to pass` action on a pull request from a fork labeled by the script may not remove the label if its DCO check run does not reference the pull request; in that case, the label is removed on the next push, or it can be removed manually.

> [!NOTE]
> When several commits are pushed in very quick succession, a stale label may occasionally remain on a pull request until the next push.

## Deployment

We'll soon provide some documentation about how to deploy your own instance of DCO2.
Expand Down
1 change: 1 addition & 0 deletions dco2/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ tracing = { workspace = true }
indoc = { workspace = true }
mockall = { workspace = true }
pretty_assertions = { workspace = true }
tokio = { workspace = true, features = ["test-util"] }
220 changes: 215 additions & 5 deletions dco2/src/dco/event/mod.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
//! This module contains the logic to process GitHub webhook events.

use std::collections::HashSet;
use std::{
collections::{BTreeSet, HashSet},
time::Duration,
};

use anyhow::{Context, Result};
use askama::Template;
use chrono::Utc;
use tokio::time::timeout;
use tracing::{debug, info, warn};

use crate::{
dco::check::{CheckInput, check},
github::{
CheckRun, CheckRunAction, CheckRunConclusion, CheckRunEvent, CheckRunEventAction, CheckRunStatus,
Commit, DynGHClient, Event, MergeGroupEvent, MergeGroupEventAction, NewCheckRunInput,
PullRequestEvent, PullRequestEventAction,
Commit, Config, Ctx, DynGHClient, Event, LabelsPermissionError, MergeGroupEvent,
MergeGroupEventAction, NewCheckRunInput, PullRequestEvent, PullRequestEventAction, PullRequestLabel,
is_rate_limit_error,
},
};

Expand Down Expand Up @@ -42,6 +48,20 @@ const OVERRIDE_ACTION_DESCRIPTION: &str = "Manually set DCO check result to pass
/// Summary of the override action.
const OVERRIDE_ACTION_SUMMARY: &str = "Check result was manually set to passed";

/// Maximum time the synchronization of the label of a pull request can take,
/// so that it does not delay the check run (e.g. when requests are retried).
const SYNC_LABEL_TIMEOUT: Duration = Duration::from_secs(3);

/// Input used to synchronize the label of a pull request. When the event
/// includes the labels of the pull request, they are used to skip the
/// synchronization if no change is needed.
struct SyncLabelInput<'a> {
head_sha: &'a str,
labels: Option<&'a [PullRequestLabel]>,
pr_number: i64,
should_be_labeled: bool,
}

/// Process the GitHub webhook event provided, taking the appropriate action.
pub async fn process_event(gh_client: DynGHClient, event: &Event) -> Result<()> {
match event {
Expand Down Expand Up @@ -79,6 +99,7 @@ async fn process_check_run_event(gh_client: DynGHClient, event: &CheckRunEvent)
actions: vec![],
completed_at: Utc::now(),
conclusion: CheckRunConclusion::Success,
external_id: event.check_run.external_id.clone(),
head_sha: event.check_run.head_sha.clone(),
name: CHECK_NAME.to_string(),
started_at,
Expand All @@ -87,6 +108,33 @@ async fn process_check_run_event(gh_client: DynGHClient, event: &CheckRunEvent)
title: OVERRIDE_ACTION_SUMMARY.to_string(),
});
gh_client.create_check_run(&ctx, &check_run).await.context("error creating check run")?;

// Remove the label from the pull requests associated with the check
// run: the one it was created for (external id) and those reported
// by GitHub that target this repository
let pr_numbers: BTreeSet<i64> = event
.check_run
.external_id
.iter()
.filter_map(|external_id| external_id.parse().ok())
.chain(
event
.check_run
.pull_requests
.iter()
.filter(|pr| pr.base.repo.id == event.repository.id)
.map(|pr| pr.number),
)
.collect();
for pr_number in pr_numbers {
let input = SyncLabelInput {
head_sha: &event.check_run.head_sha,
labels: None,
pr_number,
should_be_labeled: false,
};
sync_label(&gh_client, &ctx, &config, &input).await;
}
}

Ok(())
Expand All @@ -107,6 +155,7 @@ async fn process_merge_group_event(gh_client: DynGHClient, event: &MergeGroupEve
actions: vec![],
completed_at: Utc::now(),
conclusion: CheckRunConclusion::Success,
external_id: None,
head_sha: event.merge_group.head_commit.id.clone(),
name: CHECK_NAME.to_string(),
started_at,
Expand Down Expand Up @@ -163,9 +212,10 @@ async fn process_pull_request_event(gh_client: DynGHClient, event: &PullRequestE
members,
};
let output = check(&input);
let check_failed = output.num_commits_with_errors > 0;

// Create check run
let (conclusion, title, actions) = if output.num_commits_with_errors == 0 {
// Prepare check run
let (conclusion, title, actions) = if !check_failed {
(CheckRunConclusion::Success, CHECK_PASSED_TITLE, vec![])
} else {
let actions = if output.config.override_action_is_allowed() {
Expand All @@ -184,13 +234,27 @@ async fn process_pull_request_event(gh_client: DynGHClient, event: &PullRequestE
actions,
completed_at: Utc::now(),
conclusion,
external_id: Some(event.number.to_string()),
head_sha: event.pull_request.head.sha.clone(),
name: CHECK_NAME.to_string(),
started_at,
status: CheckRunStatus::Completed,
summary: output.render().context("error rendering output template")?,
title: title.to_string(),
});

// Add or remove the label depending on the check result. This is done
// before creating the check run so that the override action can't be
// used until the label has been synchronized
let input = SyncLabelInput {
head_sha: &event.pull_request.head.sha,
labels: Some(&event.pull_request.labels),
pr_number: event.number,
should_be_labeled: check_failed,
};
sync_label(&gh_client, &ctx, &output.config, &input).await;

// Create check run
gh_client.create_check_run(&ctx, &check_run).await.context("error creating check run")?;

Ok(())
Expand Down Expand Up @@ -233,3 +297,149 @@ async fn collect_members(

Ok(members)
}

/// Find the label provided in the list of labels of a pull request, returning
/// the name of the applied label (label names are case-insensitive).
fn find_label<'a>(labels: impl IntoIterator<Item = &'a str>, label: &str) -> Option<&'a str> {
let label_lowercase = label.to_lowercase();
labels.into_iter().find(|name| name.to_lowercase() == label_lowercase)
}

/// Check if the error provided was caused by the app lacking the permissions
/// required to manage labels.
fn is_labels_permission_error(err: &anyhow::Error) -> bool {
err.chain().any(|cause| cause.is::<LabelsPermissionError>())
}

/// Synchronize the configured label of a pull request with the result of the
/// DCO check. This is a best-effort operation that must not prevent the check
/// run from being created, so errors are logged instead of returned.
async fn sync_label(gh_client: &DynGHClient, ctx: &Ctx, config: &Config, input: &SyncLabelInput<'_>) {
// Give up when the synchronization takes too long
let Ok(result) = timeout(SYNC_LABEL_TIMEOUT, try_sync_label(gh_client, ctx, config, input)).await else {
warn!(
owner = %ctx.owner,
repo = %ctx.repo,
pr_number = input.pr_number,
"label sync timed out"
);
return;
};

// Log the error found, if any
if let Err(err) = result {
// Missing permissions are expected until the installation owner
// approves them (and until access tokens issued before are renewed)
if is_labels_permission_error(&err) {
info!(
owner = %ctx.owner,
repo = %ctx.repo,
pr_number = input.pr_number,
"permissions to manage labels not granted, skipping label sync"
);
return;
}

// Rate limits are logged separately to make them easier to spot
if is_rate_limit_error(&err) {
warn!(
?err,
owner = %ctx.owner,
repo = %ctx.repo,
pr_number = input.pr_number,
"rate limited by GitHub, skipping label sync"
);
return;
}

warn!(
?err,
owner = %ctx.owner,
repo = %ctx.repo,
pr_number = input.pr_number,
"error syncing label"
);
}
}

/// Synchronize the configured label of a pull request with the result of the
/// DCO check, returning any error found.
async fn try_sync_label(
gh_client: &DynGHClient,
ctx: &Ctx,
config: &Config,
input: &SyncLabelInput<'_>,
) -> Result<()> {
// Skip when labeling is disabled or the configured label is not valid
let Some(label) = config.label() else {
if config.label.is_some() {
warn!(
owner = %ctx.owner,
repo = %ctx.repo,
"invalid label configured, skipping label sync"
);
}
return Ok(());
};

// Skip when the labels included in the event show that no change is
// needed (the current labels are checked again before changing them)
if let Some(labels) = input.labels
&& find_label(labels.iter().map(|l| l.name.as_str()), label).is_some() == input.should_be_labeled
{
return Ok(());
}

// Skip when the permissions required to manage labels are not granted
if !gh_client.can_manage_labels(ctx).await.context("error checking labels permissions")? {
info!(
owner = %ctx.owner,
repo = %ctx.repo,
pr_number = input.pr_number,
"permissions to manage labels not granted, skipping label sync"
);
return Ok(());
}

// Get the current state of the pull request, skipping it when closed or
// when its head has moved (a newer event will handle the new commits)
let pr = gh_client
.get_pull_request(ctx, input.pr_number)
.await
.context("error getting pull request")?;
if !pr.is_open || pr.head_sha != input.head_sha {
debug!(
owner = %ctx.owner,
repo = %ctx.repo,
pr_number = input.pr_number,
"pull request closed or head moved, skipping label sync"
);
return Ok(());
}

// Add or remove the label when needed (the name of the applied label is
// used when removing it, as it may differ in case from the configured one)
let applied_label = find_label(pr.labels.iter().map(String::as_str), label);
match (input.should_be_labeled, applied_label) {
(true, None) => {
gh_client.add_label(ctx, input.pr_number, label).await.context("error adding label")?;
info!(owner = %ctx.owner, repo = %ctx.repo, pr_number = input.pr_number, label, "label added");
}
(false, Some(applied_label)) => {
gh_client
.remove_label(ctx, input.pr_number, applied_label)
.await
.context("error removing label")?;
info!(
owner = %ctx.owner,
repo = %ctx.repo,
pr_number = input.pr_number,
label = applied_label,
"label removed"
);
}
_ => {}
}

Ok(())
}
Loading
Loading