From a651055ee5cc4299e8063736881b137365bd7a52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 27 Oct 2026 05:47:31 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20co-authors=20of=20pushed=20?= =?UTF-8?q?commits=20get=20credit=20on=20their=20contribution=20calendar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../migrations/0067_coauthored_commits.sql | 13 +++ crates/forge-core/src/store/contributions.rs | 98 +++++++++++++++++-- crates/forge-core/src/store/migrate.rs | 1 + crates/forge-core/src/store/user_delete.rs | 1 + crates/forge-web/src/i18n/misc.rs | 14 ++- crates/forge-web/src/post_update.rs | 81 ++++++++++++++- crates/forge-web/src/views/heatmap.rs | 8 ++ 7 files changed, 205 insertions(+), 11 deletions(-) create mode 100644 crates/forge-core/migrations/0067_coauthored_commits.sql diff --git a/crates/forge-core/migrations/0067_coauthored_commits.sql b/crates/forge-core/migrations/0067_coauthored_commits.sql new file mode 100644 index 0000000..a56f2ec --- /dev/null +++ b/crates/forge-core/migrations/0067_coauthored_commits.sql @@ -0,0 +1,13 @@ +-- Commits a user is credited with as a co-author (a `Co-authored-by:` trailer) in a branch push. +-- One row per (user, repo, commit); `created_at` is the push time. Applied by store/migrate.rs. + +CREATE TABLE coauthored_commits ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE, + commit_oid TEXT NOT NULL, + summary TEXT NOT NULL, + created_at TEXT NOT NULL, + UNIQUE(user_id, repo_id, commit_oid) +); +CREATE INDEX coauthored_commits_user_created ON coauthored_commits(user_id, created_at); diff --git a/crates/forge-core/src/store/contributions.rs b/crates/forge-core/src/store/contributions.rs index 20737c7..57c9fca 100644 --- a/crates/forge-core/src/store/contributions.rs +++ b/crates/forge-core/src/store/contributions.rs @@ -6,20 +6,22 @@ use jiff::Timestamp; use turso::{Row, Value}; use super::push_recent::{ZERO_OID_SHA1, ZERO_OID_SHA256}; -use super::{Store, col_int, col_text, fetch_all}; +use super::{Store, col_int, col_text, db_err, fetch_all, new_id}; use crate::error::{Error, Result}; use crate::tz::local_date; /// Most contributions `contributions_between` returns for one day. const DAY_LIMIT: u32 = 200; -/// What a contribution was: a branch push, or an issue, pull request or comment the user wrote. +/// What a contribution was: a branch push, an issue, pull request or comment the user wrote, or +/// a commit the user was credited with as a co-author. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ContributionKind { Push, Issue, Pull, Comment, + CoAuthored, } /// One contribution, with the repo it landed in. @@ -34,8 +36,10 @@ pub struct ContributionItem { pub ref_name: String, /// The issue or pull request number (a comment's is its issue's); 0 for a push. pub number: i64, - /// The issue or pull request title; empty for a push. + /// The issue or pull request title, or a co-authored commit's summary; empty for a push. pub title: String, + /// The co-authored commit's object id; empty for everything else. + pub commit: String, } fn map_item(row: &Row) -> Result { @@ -44,6 +48,7 @@ fn map_item(row: &Row) -> Result { "issue" => ContributionKind::Issue, "pull" => ContributionKind::Pull, "comment" => ContributionKind::Comment, + "coauthored" => ContributionKind::CoAuthored, other => { return Err(Error::Database(format!( "unknown contribution kind {other:?}" @@ -58,6 +63,7 @@ fn map_item(row: &Row) -> Result { ref_name: col_text(row, 4)?, number: col_int(row, 5)?, title: col_text(row, 6)?, + commit: col_text(row, 7)?, }) } @@ -84,6 +90,9 @@ impl Store { UNION ALL \ SELECT substr(created_at, 1, 16) FROM comments \ WHERE author_id = ?1 AND created_at >= ?2 \ + UNION ALL \ + SELECT substr(created_at, 1, 16) FROM coauthored_commits \ + WHERE user_id = ?1 AND created_at >= ?2 \ ) GROUP BY minute"; let params = vec![ Value::Text(user_id.to_string()), @@ -121,20 +130,25 @@ impl Store { ) -> Result> { // Parameters: ?1 user, ?2 from, ?3 to, ?4 and ?5 zero oids. let sql = "SELECT 'push' AS created_kind, o.username, r.name, p.created_at, p.ref_name, \ - 0, '' FROM push_events p \ + 0, '', '' FROM push_events p \ JOIN repos r ON r.id = p.repo_id JOIN users o ON o.id = r.owner_id \ WHERE p.actor_id = ?1 AND p.created_at >= ?2 AND p.created_at < ?3 \ AND p.new_oid NOT IN (?4, ?5) \ UNION ALL \ - SELECT i.kind, o.username, r.name, i.created_at, '', i.number, i.title FROM issues i \ + SELECT i.kind, o.username, r.name, i.created_at, '', i.number, i.title, '' FROM issues i \ JOIN repos r ON r.id = i.repo_id JOIN users o ON o.id = r.owner_id \ WHERE i.author_id = ?1 AND i.created_at >= ?2 AND i.created_at < ?3 \ AND i.kind IN ('issue', 'pull') \ UNION ALL \ - SELECT 'comment', o.username, r.name, c.created_at, '', i.number, i.title \ + SELECT 'comment', o.username, r.name, c.created_at, '', i.number, i.title, '' \ FROM comments c JOIN issues i ON i.id = c.issue_id \ JOIN repos r ON r.id = i.repo_id JOIN users o ON o.id = r.owner_id \ WHERE c.author_id = ?1 AND c.created_at >= ?2 AND c.created_at < ?3 \ + UNION ALL \ + SELECT 'coauthored', o.username, r.name, k.created_at, '', 0, k.summary, k.commit_oid \ + FROM coauthored_commits k \ + JOIN repos r ON r.id = k.repo_id JOIN users o ON o.id = r.owner_id \ + WHERE k.user_id = ?1 AND k.created_at >= ?2 AND k.created_at < ?3 \ ORDER BY created_at DESC LIMIT ?6"; let params = vec![ Value::Text(user_id.to_string()), @@ -148,6 +162,36 @@ impl Store { let conn = self.read_conn().await; fetch_all(&conn, sql, params, map_item).await } + + /// Credits `user_id` with a co-authored commit in `repo_id`. A commit is recorded once per + /// user and repo; a repeat (the same commit pushed again) is ignored. `created_at` is the push + /// time as an RFC 3339 stamp. + pub async fn record_coauthored_commit( + &self, + user_id: &str, + repo_id: &str, + commit_oid: &str, + summary: &str, + created_at: &str, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT OR IGNORE INTO coauthored_commits \ + (id, user_id, repo_id, commit_oid, summary, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + ( + new_id(), + user_id.to_string(), + repo_id.to_string(), + commit_oid.to_string(), + summary.to_string(), + created_at.to_string(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } } #[cfg(test)] @@ -220,6 +264,48 @@ mod tests { assert_eq!(items[1].ref_name, "refs/heads/main"); } + #[tokio::test] + async fn coauthored_commit_shows_in_counts() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "x", false) + .await + .unwrap(); + let bob = store.create_user("bob", None, "x", false).await.unwrap(); + let demo = store + .create_repo(&bob.id, "demo", "", Visibility::Public, "main") + .await + .unwrap(); + let at = "2026-03-01T10:00:00.000000000Z"; + store + .record_coauthored_commit(&tahinli.id, &demo.id, OID, "pair session", at) + .await + .unwrap(); + // A repeat of the same commit is ignored. + store + .record_coauthored_commit(&tahinli.id, &demo.id, OID, "pair session", at) + .await + .unwrap(); + + let since = "2026-03-01T00:00:00.000000000Z"; + let counts = store + .contribution_counts(&tahinli.id, since, "UTC") + .await + .unwrap(); + assert_eq!(counts, vec![("2026-03-01".to_string(), 1)]); + + let items = store + .contributions_between(&tahinli.id, since, "2026-03-02T00:00:00.000000000Z") + .await + .unwrap(); + assert_eq!(items.len(), 1); + assert_eq!(items[0].kind, ContributionKind::CoAuthored); + assert_eq!(items[0].repo_owner, "bob"); + assert_eq!(items[0].title, "pair session"); + assert_eq!(items[0].commit, OID); + } + #[tokio::test] async fn counts_pushes_issues_pulls_and_comments_per_day() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index fd3d913..1afdff8 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -106,6 +106,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ (64, include_str!("../../migrations/0064_merge_queue.sql")), (65, include_str!("../../migrations/0065_hue_colours.sql")), (66, include_str!("../../migrations/0066_session_ip.sql")), + (67, include_str!("../../migrations/0067_coauthored_commits.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/user_delete.rs b/crates/forge-core/src/store/user_delete.rs index f02e5a0..85a8548 100644 --- a/crates/forge-core/src/store/user_delete.rs +++ b/crates/forge-core/src/store/user_delete.rs @@ -118,6 +118,7 @@ const REMOVED: &[(&str, &str, &str)] = &[ ("collaborations", "collaborators", "user_id"), ("stars", "stars", "user_id"), ("profile pins", "profile_pins", "user_id"), + ("co-authored commits", "coauthored_commits", "user_id"), ("issue assignments", "issue_assignees", "user_id"), ("recovery codes", "recovery_codes", "user_id"), ("passkeys", "passkeys", "user_id"), diff --git a/crates/forge-web/src/i18n/misc.rs b/crates/forge-web/src/i18n/misc.rs index 4963d34..45b201c 100644 --- a/crates/forge-web/src/i18n/misc.rs +++ b/crates/forge-web/src/i18n/misc.rs @@ -729,6 +729,9 @@ pub fn day_item_words( ("Opened pull request".to_owned(), format!("in {repo}")) } (Lang::En, ContributionKind::Comment) => ("Commented on".to_owned(), format!("in {repo}")), + (Lang::En, ContributionKind::CoAuthored) => { + (format!("Co-authored a commit in {repo}:"), String::new()) + } (Lang::Tr, ContributionKind::Push) => { (String::new(), format!("deposunda {branch} dalına gönderim")) } @@ -739,9 +742,14 @@ pub fn day_item_words( String::new(), format!("çekme isteğini {repo} deposunda açtı"), ), - (Lang::Tr, ContributionKind::Comment) => { - (String::new(), format!("konusuna {repo} deposunda yorum yaptı")) - } + (Lang::Tr, ContributionKind::Comment) => ( + String::new(), + format!("konusuna {repo} deposunda yorum yaptı"), + ), + (Lang::Tr, ContributionKind::CoAuthored) => ( + String::new(), + format!("commit'ine {repo} deposunda ortak yazar oldu"), + ), } } diff --git a/crates/forge-web/src/post_update.rs b/crates/forge-web/src/post_update.rs index 21b7295..aa16530 100644 --- a/crates/forge-web/src/post_update.rs +++ b/crates/forge-web/src/post_update.rs @@ -4,7 +4,9 @@ //! 0. Webhook events for the ref: push, and create or delete (see `webhooks::emit`). //! 1. Closing keywords and references from the commits a default-branch update added. These run //! in a spawned task and are not coalesced: every range must be processed. -//! 2. Pull request sync for `refs/heads/` (see `pulls_sync`), inline. +//! 2. Co-author credit for the commits a branch update added (see `credit_coauthors`), also +//! spawned. +//! 3. Pull request sync for `refs/heads/` (see `pulls_sync`), inline. //! //! Maintenance is not part of this: it is coalesced per repo and runs once per push through //! `internal::trigger_maintenance`. Callers that update a ref outside receive-pack (the merge @@ -13,8 +15,9 @@ use std::path::PathBuf; use forge_core::issue_refs::{find_closing_refs, find_issue_refs}; +use forge_core::time::now_stamp; use forge_core::{IssueState, Repo, StateReason}; -use forge_git::history; +use forge_git::{history, trailers}; use serde_json::json; use crate::internal::is_zero_oid; @@ -27,6 +30,8 @@ use crate::webhooks::emit::{Sender, emit_item_action, emit_ref_update, lookup_se const MAX_PUSH_COMMITS: usize = 500; /// Commits read for a push that creates the branch. const MAX_NEW_BRANCH_COMMITS: usize = 50; +/// Commits read for co-author credit from a push that updates an existing branch. +const MAX_COAUTHOR_COMMITS: usize = 200; /// Runs the per-ref post-update work for `refname`, moving `old` to `new`. `actor_id` is the user /// who made the change (empty for system updates). Closing-keyword work is spawned; pull request @@ -85,6 +90,23 @@ pub async fn after_ref_update( } } } + if refname.starts_with("refs/heads/") && !is_zero_oid(new) { + match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) { + Ok(repo_dir) => { + tokio::spawn(credit_coauthors( + state.clone(), + repo.clone(), + repo_dir, + actor_id.to_owned(), + old.to_owned(), + new.to_owned(), + )); + } + Err(e) => { + tracing::error!(error = %e, repo_id = %repo.id, "co-authors: bad repo path"); + } + } + } let synced = pulls_sync::sync_pulls_for_ref(state, repo, actor_id, refname, old, new).await; // A push can move, merge or open any pull of the repo, so every pull page is woken. crate::pages::pull_live::bump_repo_pulls(state, &repo.id).await; @@ -123,6 +145,61 @@ async fn close_from_pushed_commits( } } +/// Credits each registered co-author (a `Co-authored-by:` trailer) of the commits a branch update +/// added. The pusher and a co-author whose address is the commit's own author are skipped. Errors +/// are logged; the push has already succeeded. +async fn credit_coauthors( + state: AppState, + repo: Repo, + repo_dir: PathBuf, + actor_id: String, + old: String, + new: String, +) { + let old = (!is_zero_oid(&old)).then_some(old.as_str()); + let max = if old.is_some() { + MAX_COAUTHOR_COMMITS + } else { + MAX_NEW_BRANCH_COMMITS + }; + let commits = match history::new_commits(&state.git, &repo_dir, old, &new, max).await { + Ok(commits) => commits, + Err(e) => { + tracing::error!(error = %e, repo_id = %repo.id, "co-authors: listing commits failed"); + return; + } + }; + let actor = (!actor_id.is_empty()).then_some(actor_id.as_str()); + let at = now_stamp(); + for commit in &commits { + for co in trailers::co_authors(&commit.message) { + if co.email.eq_ignore_ascii_case(&commit.author_email) { + continue; + } + let user = match state.store.verified_user_by_email(&co.email).await { + Ok(Some(user)) => user, + Ok(None) => continue, + Err(e) => { + tracing::error!(error = %e, repo_id = %repo.id, "co-authors: user lookup failed"); + continue; + } + }; + if Some(user.id.as_str()) == actor { + continue; + } + let recorded = state + .store + .record_coauthored_commit(&user.id, &repo.id, &commit.oid, &commit.summary, &at) + .await; + if let Err(e) = recorded { + tracing::error!(error = %e, repo_id = %repo.id, commit = %commit.oid, "co-authors: recording failed"); + continue; + } + state.live.bump(&crate::live::Topic::User(user.id.clone())); + } + } +} + /// Closes open issues named by closing keywords in `text`, and records a `referenced` event on /// every other issue it mentions, once per (issue, commit). async fn apply_commit_refs( diff --git a/crates/forge-web/src/views/heatmap.rs b/crates/forge-web/src/views/heatmap.rs index 371ac68..099ee93 100644 --- a/crates/forge-web/src/views/heatmap.rs +++ b/crates/forge-web/src/views/heatmap.rs @@ -231,6 +231,14 @@ fn day_row(lang: Lang, item: &ContributionItem, now: i64) -> DayRow { format!("/{repo}/pulls/{}", item.number), format!("#{} {}", item.number, item.title), ), + ContributionKind::CoAuthored => { + let summary = if item.title.is_empty() { + item.commit.chars().take(7).collect() + } else { + item.title.clone() + }; + (format!("/{repo}/commit/{}", item.commit), summary) + } }; DayRow { before,