From f1b236a283a34c0a264fe7b8bcb0275dd3e8e6e6 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Mon, 16 Nov 2026 19:45:51 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(git):=20=E5=A4=9A=E4=BB=93=E5=BA=93=20?= =?UTF-8?q?Git=20Log=20=E6=8C=89=E6=97=B6=E9=97=B4=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E5=90=84=E4=BB=93=E5=BA=93=E5=8E=86=E5=8F=B2=EF=BC=8C=E5=B7=A5?= =?UTF-8?q?=E4=BD=9C=E5=8C=BA=E4=BB=93=E5=BA=93=E9=80=89=E6=8B=A9=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E4=B8=80=E7=BB=84=E4=BB=93=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 git.workspaceHistoryMerge:按日期交错已加载的各仓库历史,保持每个仓库自身顺序;有未加载页的仓库读完即停并列入 pending,加载更多时已有行不变 - 多个仓库同时出现的哈希改用 @ 作键,图形投影不会把不同仓库连在一起 - git.workspaceRepositorySelection 新增 chosen:一组仓库的选择按发现顺序保留,全部失效时回退到一个仓库 - 补齐 fixture、API 文档与真实 git 测试 --- rust/contracts/rust-core-api.md | 40 +++- rust/crates/core/src/protocol/command.rs | 5 +- .../crates/core/src/runtime/dispatcher/git.rs | 3 + .../src/tests/git_workspace_repositories.rs | 72 +++++- rust/crates/git/src/lib.rs | 1 + rust/crates/git/src/workspace_repositories.rs | 9 +- .../workspace_repositories/history_merge.rs | 223 +++++++++++++++++ .../src/workspace_repositories/selection.rs | 112 ++++++--- .../git/src/workspace_repositories/tests.rs | 61 ++++- .../git/workspace-history-merge-v1.json | 225 ++++++++++++++++++ .../workspace-repository-selection-v1.json | 67 ++++++ 11 files changed, 775 insertions(+), 43 deletions(-) create mode 100644 rust/crates/git/src/workspace_repositories/history_merge.rs create mode 100644 rust/fixtures/git/workspace-history-merge-v1.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index f7222ee9..3ac751b1 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -769,8 +769,9 @@ or removing a command fails until the table changes in the same commit. | `git.historyLocate` | Append bounded history pages until one commit is found and report the budget, window cursor, and exhaustion | | `git.branchNamePreview` | Clean and validate a new branch name against already loaded references without running Git | | `git.repositoryColorAssignments` | Assign color slots to a bounded page of ordered repository identities | -| `git.workspaceRepositorySelection` | Choose the workspace repository a view acts on and the others it lists for switching, from discovery entries and the previous pick | +| `git.workspaceRepositorySelection` | Choose the workspace repository, or the set of repositories, a view acts on and the others it lists for switching, from discovery entries and the previous pick | | `git.workspaceChangeGroups` | Group every workspace repository's status changes, plan each group's and the workspace line's staging, and report what a listed ancestor records for a submodule | +| `git.workspaceHistoryMerge` | Interleave the loaded history pages of several workspace repositories into one stable newest-first list with collision-safe commit keys, and name the repositories whose next page it waits on | | `git.updatePlan` | Route a branch Update and gate a Pull from facts the host collected: blockers, strategy default, whether to ask, and the expected checkout | | `git.historyWindow` | Plan a history refresh window, page merge, and selection retention over commit identities | | `git.graphProjection` | Project a loaded history window into commit-graph lanes, color IDs, routes, print elements, and labels, optionally filtered | @@ -2041,12 +2042,47 @@ for an empty list; `fellBack` is `true` only when `selected` was given and is no longer listed, so the view drops state that belonged to it such as an open history cursor or a reference filter; `others` are the remaining IDs in discovery order, the groups the branch popup and the Git Log list for switching. +A view that acts on several repositories at once, such as a Git Log that shows +the histories of a chosen set in one list, sends `chosen`, the IDs it picked +before in any order, instead of `selected`; an empty list is no pick. The +response then also carries `chosen`: the listed picks in discovery order, or +`[active]` when none is listed (`[]` for an empty workspace). `active` is the +first of them, `others` are every ID outside them, and `fellBack` is `true` when +any pick is no longer listed. Without `chosen` in the request the response has +no `chosen` field. The list holds at most 10,000 entries. An ID that is empty, longer than 4,096 bytes, starts with `/`, or contains `\` or NUL, an empty path or name, a repeated ID or path, more than one `workspace` role, an unknown role, an empty `selected`, -or an unknown field fails with `invalid_request`. See +both `selected` and `chosen`, a `chosen` ID that is invalid or repeated, or an +unknown field fails with `invalid_request`. See `rust/fixtures/git/workspace-repository-selection-v1.json`. +`git.workspaceHistoryMerge` is pure. It accepts `{ repositories }`, the +repositories a log walks in the order the view lists them, each +`{ id, commits, complete }`: `id` is the `workspace.repositories` ID, `commits` +are every commit loaded so far in the order Git walked them as +`{ hash, parentHashes?, timestamp? }` (`timestamp` is the `git.historyPage` +`dateUnixSeconds`), and `complete` is `true` once no page is left. The response +is `{ entries, pending }`. `entries` is the merged list newest first, each +`{ repository, index, key, parentKeys }`: `repository` indexes the request's +`repositories`, `index` that repository's `commits`. Each repository keeps its +own order; among the next commits of the repositories the newest timestamp goes +first, a commit without one takes the timestamp placed before it in its +repository, and equal timestamps go in request order. The merge stops as soon as +a repository that is not `complete` has no loaded commit left, because its next +page may hold a newer commit than every one still unplaced; `pending` lists those +repositories' indices in request order, and is empty when every loaded commit is +placed and no page is left. A view loads the next page of each pending repository +and asks again; the earlier entries stay the same, so rows only grow at the end. +`key` is the commit's hash, except that a hash more than one repository names, +as a commit or as a parent, is keyed `@` in each of them; `parentKeys` +apply the same rule, so `git.graphProjection` laid out over the keys never joins +two repositories. At most 10,000 repositories and 20,000 commits in total are +accepted. An invalid or repeated `id`, a hash or parent that is not 1 to 64 +hexadecimal digits, a commit repeated within one repository, a missing +`complete`, or an unknown field fails with `invalid_request`. See +`rust/fixtures/git/workspace-history-merge-v1.json`. + `git.workspaceChangeGroups` is pure and validates `repositories` the same way; each entry also carries `changes`, the `git.status` changes read for that repository, passed through unchanged. Core reads `path`, `originalPath`, diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 1f75702e..933880d6 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -844,10 +844,12 @@ pub enum GitCommand { BranchNamePreview, /// Assigns palette slots to a page of ordered repository identities. RepositoryColorAssignments, - /// Chooses the workspace repository a view acts on (`git.workspaceRepositorySelection`). + /// Chooses the workspace repositories a view acts on (`git.workspaceRepositorySelection`). WorkspaceRepositorySelection, /// Groups workspace repositories' changes and plans their staging (`git.workspaceChangeGroups`). WorkspaceChangeGroups, + /// Interleaves the loaded histories of workspace repositories (`git.workspaceHistoryMerge`). + WorkspaceHistoryMerge, /// Plans a branch Update or Pull from collected facts (`git.updatePlan`). UpdatePlan, /// Plans history refresh windows, page merges, and selection retention (`git.historyWindow`). @@ -1472,6 +1474,7 @@ impl CoreCommand { Some(Self::Git(GitCommand::WorkspaceRepositorySelection)) } "git.workspaceChangeGroups" => Some(Self::Git(GitCommand::WorkspaceChangeGroups)), + "git.workspaceHistoryMerge" => Some(Self::Git(GitCommand::WorkspaceHistoryMerge)), "git.updatePlan" => Some(Self::Git(GitCommand::UpdatePlan)), "git.historyWindow" => Some(Self::Git(GitCommand::HistoryWindow)), "git.graphProjection" => Some(Self::Git(GitCommand::GraphProjection)), diff --git a/rust/crates/core/src/runtime/dispatcher/git.rs b/rust/crates/core/src/runtime/dispatcher/git.rs index 961cd0ae..e585ce36 100644 --- a/rust/crates/core/src/runtime/dispatcher/git.rs +++ b/rust/crates/core/src/runtime/dispatcher/git.rs @@ -427,6 +427,9 @@ pub(super) fn dispatch(command: GitCommand, id: Option, payload: Value) GitCommand::WorkspaceChangeGroups => { plugin_response(id, payload, lithe_git::workspace_change_groups_command) } + GitCommand::WorkspaceHistoryMerge => { + plugin_response(id, payload, lithe_git::workspace_history_merge_command) + } GitCommand::UpdatePlan => plugin_response(id, payload, lithe_git::update_plan_command), GitCommand::HistoryWindow => { plugin_response(id, payload, lithe_git::history_window_command) diff --git a/rust/crates/core/src/tests/git_workspace_repositories.rs b/rust/crates/core/src/tests/git_workspace_repositories.rs index 60083990..36e286a4 100644 --- a/rust/crates/core/src/tests/git_workspace_repositories.rs +++ b/rust/crates/core/src/tests/git_workspace_repositories.rs @@ -63,7 +63,7 @@ fn check_fixture(command: &str, fixture: &str) { } #[test] -fn selection_and_change_groups_match_their_shared_fixtures() { +fn selection_change_groups_and_history_merge_match_their_shared_fixtures() { check_fixture( "git.workspaceRepositorySelection", include_str!("../../../../fixtures/git/workspace-repository-selection-v1.json"), @@ -72,6 +72,10 @@ fn selection_and_change_groups_match_their_shared_fixtures() { "git.workspaceChangeGroups", include_str!("../../../../fixtures/git/workspace-change-groups-v1.json"), ); + check_fixture( + "git.workspaceHistoryMerge", + include_str!("../../../../fixtures/git/workspace-history-merge-v1.json"), + ); } /// Discovery entries with the status each repository reports, as hosts send them. @@ -169,3 +173,69 @@ fn discovery_and_status_pass_through_to_selection_and_change_groups() { "{groups}" ); } + +/// Commits `message` in `root` with `date` as both the author and the committer date. +fn commit_at(root: &Path, message: &str, date: &str) { + fs::write(root.join("file.txt"), message).unwrap(); + git(root, &["add", "file.txt"]); + git(root, &["commit", "-qm", message, "--date", date]); +} + +/// One `git.historyPage` page of `root` as the merge takes it. +fn history_page(root: &Path, id: &str, limit: usize) -> Value { + let page = data( + "git.historyPage", + json!({"root": root, "order": "date", "limit": limit}), + ); + let commits = page["commits"] + .as_array() + .unwrap() + .iter() + .map(|commit| { + json!({ + "hash": commit["hash"], + "parentHashes": commit["parentHashes"], + "timestamp": commit["dateUnixSeconds"], + }) + }) + .collect::>(); + json!({"id": id, "complete": page["hasMore"] == false, "commits": commits}) +} + +#[test] +fn history_pages_pass_through_to_the_history_merge() { + let folder = Folder(temporary_root("workspace-history-merge")); + let backend = folder.0.join("backend"); + let frontend = folder.0.join("frontend"); + init(&backend); + init(&frontend); + commit_at(&backend, "backend one", "2026-01-01T10:00:00+00:00"); + commit_at(&frontend, "frontend one", "2026-01-02T10:00:00+00:00"); + commit_at(&backend, "backend two", "2026-01-03T10:00:00+00:00"); + + // A first page that leaves backend's older commit unread stops after it. + let merged = data( + "git.workspaceHistoryMerge", + json!({"repositories": [history_page(&backend, "backend", 1), history_page(&frontend, "frontend", 100)]}), + ); + assert_eq!(merged["pending"], json!([0]), "{merged}"); + assert_eq!(merged["entries"].as_array().unwrap().len(), 1, "{merged}"); + + let merged = data( + "git.workspaceHistoryMerge", + json!({"repositories": [history_page(&backend, "backend", 100), history_page(&frontend, "frontend", 100)]}), + ); + let order = merged["entries"] + .as_array() + .unwrap() + .iter() + .map(|entry| { + ( + entry["repository"].as_u64().unwrap(), + entry["index"].as_u64().unwrap(), + ) + }) + .collect::>(); + assert_eq!(order, [(0, 0), (1, 0), (0, 1)], "{merged}"); + assert_eq!(merged["pending"], json!([]), "{merged}"); +} diff --git a/rust/crates/git/src/lib.rs b/rust/crates/git/src/lib.rs index 37ba8c02..8f58783c 100644 --- a/rust/crates/git/src/lib.rs +++ b/rust/crates/git/src/lib.rs @@ -127,6 +127,7 @@ pub use shelf::shelf_command; pub use update_plan::command as update_plan_command; pub use workspace_repositories::{ change_groups_command as workspace_change_groups_command, + history_merge_command as workspace_history_merge_command, selection_command as workspace_repository_selection_command, }; pub use worktree_rules::creation_preview_command as worktree_creation_preview_command; diff --git a/rust/crates/git/src/workspace_repositories.rs b/rust/crates/git/src/workspace_repositories.rs index 6ce5ab5a..cfb38dbf 100644 --- a/rust/crates/git/src/workspace_repositories.rs +++ b/rust/crates/git/src/workspace_repositories.rs @@ -4,16 +4,19 @@ //! that contains the folder, if any, and the independent repositories nested //! below it. A folder without `.git` that holds several repositories lists only //! nested ones. Hosts pass those discovery entries back unchanged, together with -//! what they read from each repository, and Core decides which repository a view -//! acts on and how the repositories' changes group and stage. Views keep drawing, -//! folding, and the native Git writes the plans name. +//! what they read from each repository, and Core decides which repositories a +//! view acts on, how the repositories' changes group and stage, and how their +//! histories interleave in one log. Views keep drawing, folding, and the native +//! Git reads and writes the plans name. mod change_groups; +mod history_merge; mod selection; #[cfg(test)] mod tests; pub use change_groups::command as change_groups_command; +pub use history_merge::command as history_merge_command; pub use selection::command as selection_command; use crate::contracts::WorkspaceRepositoryRole; diff --git a/rust/crates/git/src/workspace_repositories/history_merge.rs b/rust/crates/git/src/workspace_repositories/history_merge.rs new file mode 100644 index 00000000..c6169c6f --- /dev/null +++ b/rust/crates/git/src/workspace_repositories/history_merge.rs @@ -0,0 +1,223 @@ +//! Interleaves the loaded histories of several workspace repositories into one list. +//! +//! A Git Log that walks several repositories at once shows their commits in one +//! list, newest first, as IntelliJ IDEA shows the roots of a project. Each +//! repository's history arrives a page at a time in Git's own order; Core +//! merges what is loaded, keeping each repository's order and placing the +//! repositories' commits by their dates. +//! +//! The list only grows at its end as pages arrive. The merge stops at the first +//! point where a repository with pages left has no loaded commit: its next page +//! may hold a newer commit than every one still to place, so placing them now +//! would move rows once that page arrives. That repository is pending, and the +//! view loads its next page before it asks again. +//! +//! The commits of different repositories are different objects even when a +//! hash repeats, such as two clones of one project in the same folder. A hash +//! that more than one repository names, as a commit or as a parent, is keyed +//! `@` in each of them, so a graph laid out from the keys never joins +//! two repositories. Every other key is the hash itself. + +use super::{invalid, valid_id, MAX_REPOSITORIES}; +use lithe_protocol::CoreError; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::cmp::Reverse; +use std::collections::{BinaryHeap, HashMap, HashSet}; + +/// Matches the commit bound of `git.graphProjection`, which lays out the merged list. +const MAX_COMMITS: usize = 20_000; +/// SHA-256 object names are the longest Git writes. +const MAX_HASH_BYTES: usize = 64; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Request { + /// The repositories the view walks, in the order the view lists them. + repositories: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RepositoryHistory { + /// The repository's `workspace.repositories` ID. + id: String, + /// Every commit loaded so far, in the order Git walked them. + commits: Vec, + /// True when `commits` hold the whole walk, so no page is left to load. + complete: bool, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CommitInput { + hash: String, + #[serde(default)] + parent_hashes: Vec, + /// Seconds since the Unix epoch the list places the commit by; absent when + /// Git reported no valid date, so the commit stays beside the one before it. + #[serde(default)] + timestamp: Option, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct Response { + /// The merged list, newest first. + entries: Vec, + /// Indices of the repositories whose next page the list waits on, in request + /// order. Empty when every loaded commit is placed and no page is left. + pending: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct Entry { + /// Index of the commit's repository in the request. + repository: usize, + /// Index of the commit in that repository's `commits`. + index: usize, + /// The commit's identity in the merged list. + key: String, + /// The keys of the commit's parents, in Git's parent order. + parent_keys: Vec, +} + +/// Handles `git.workspaceHistoryMerge`. +pub fn command(payload: Value) -> Result { + let request: Request = serde_json::from_value(payload).map_err(|error| { + invalid("Invalid workspace history merge request").with_details(error.to_string()) + })?; + validate(&request.repositories)?; + let shared = shared_hashes(&request.repositories); + let key = |repository: &RepositoryHistory, hash: &str| { + if shared.contains(hash) { + format!("{hash}@{}", repository.id) + } else { + hash.to_owned() + } + }; + let (placed, pending) = merge(&request.repositories); + let entries = placed + .into_iter() + .map(|(repository_index, index)| { + let repository = &request.repositories[repository_index]; + let commit = &repository.commits[index]; + Entry { + repository: repository_index, + index, + key: key(repository, &commit.hash), + parent_keys: commit + .parent_hashes + .iter() + .map(|parent| key(repository, parent)) + .collect(), + } + }) + .collect(); + Ok(serde_json::to_value(Response { entries, pending }) + .expect("workspace history merge should encode")) +} + +/// Rejects requests a view cannot send: too many repositories or commits, an +/// invalid or repeated ID, a hash that is not a Git object name, or a commit +/// listed twice in one repository. +fn validate(repositories: &[RepositoryHistory]) -> Result<(), CoreError> { + if repositories.len() > MAX_REPOSITORIES { + return Err(invalid("Too many repositories in a history merge")); + } + let total: usize = repositories + .iter() + .map(|repository| repository.commits.len()) + .sum(); + if total > MAX_COMMITS { + return Err(invalid("Too many commits in a history merge")); + } + let mut ids = HashSet::with_capacity(repositories.len()); + for repository in repositories { + if !valid_id(&repository.id) || !ids.insert(repository.id.as_str()) { + return Err(invalid( + "Invalid or repeated repository ID in a history merge", + )); + } + let mut hashes = HashSet::with_capacity(repository.commits.len()); + for commit in &repository.commits { + if !object_name(&commit.hash) || !commit.parent_hashes.iter().all(|p| object_name(p)) { + return Err(invalid("Invalid commit hash in a history merge")); + } + if !hashes.insert(commit.hash.as_str()) { + return Err(invalid("Repeated commit in a history merge")); + } + } + } + Ok(()) +} + +/// A Git object name: hexadecimal and at most as long as a SHA-256 name. The +/// shape keeps a `@` key unambiguous. +fn object_name(hash: &str) -> bool { + !hash.is_empty() && hash.len() <= MAX_HASH_BYTES && hash.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// The hashes more than one repository names, as a commit or as a parent. +fn shared_hashes(repositories: &[RepositoryHistory]) -> HashSet<&str> { + let mut owner: HashMap<&str, usize> = HashMap::new(); + let mut shared = HashSet::new(); + for (index, repository) in repositories.iter().enumerate() { + for commit in &repository.commits { + let names = std::iter::once(commit.hash.as_str()) + .chain(commit.parent_hashes.iter().map(String::as_str)); + for hash in names { + if *owner.entry(hash).or_insert(index) != index { + shared.insert(hash); + } + } + } + } + shared +} + +/// Places the loaded commits newest first while no repository with pages left +/// has run out, keeping each repository's own order. A commit without a date +/// takes the date of the one placed before it in its repository, so it stays +/// beside it; the first commit of a repository without one goes first. Equal +/// dates go in request order. Returns the placed `(repository, index)` pairs and +/// the repositories the merge stopped for. +fn merge(repositories: &[RepositoryHistory]) -> (Vec<(usize, usize)>, Vec) { + let mut next = vec![0usize; repositories.len()]; + let mut last = vec![i64::MAX; repositories.len()]; + let date = |repository: usize, index: usize, last: &[i64]| { + repositories[repository].commits[index] + .timestamp + .unwrap_or(last[repository]) + }; + // Newest date first, then the lowest repository index. + let mut heads = BinaryHeap::new(); + let mut stalled = Vec::new(); + for (index, repository) in repositories.iter().enumerate() { + if !repository.commits.is_empty() { + heads.push((date(index, 0, &last), Reverse(index))); + } else if !repository.complete { + stalled.push(index); + } + } + let mut placed = Vec::new(); + while stalled.is_empty() { + let Some((placed_date, Reverse(repository))) = heads.pop() else { + break; + }; + placed.push((repository, next[repository])); + last[repository] = placed_date; + next[repository] += 1; + if next[repository] < repositories[repository].commits.len() { + heads.push(( + date(repository, next[repository], &last), + Reverse(repository), + )); + } else if !repositories[repository].complete { + stalled.push(repository); + } + } + stalled.sort_unstable(); + (placed, stalled) +} diff --git a/rust/crates/git/src/workspace_repositories/selection.rs b/rust/crates/git/src/workspace_repositories/selection.rs index b8363f5e..1019a58b 100644 --- a/rust/crates/git/src/workspace_repositories/selection.rs +++ b/rust/crates/git/src/workspace_repositories/selection.rs @@ -1,16 +1,20 @@ -//! Chooses the repository a multi-repository view acts on. +//! Chooses the repositories a multi-repository view acts on. //! -//! The branch popup and the Git Log each act on one repository of the workspace -//! and list the others as groups the user can switch to. A view keeps the -//! repository the user picked while discovery still lists it; otherwise it falls -//! back to the repository that contains the opened folder, and in a folder that -//! is no repository itself, to the first nested repository. +//! The branch popup and the Git Log each act on repositories of the workspace +//! and list the others as groups the user can switch to. A view keeps what the +//! user picked while discovery still lists it; otherwise it falls back to the +//! repository that contains the opened folder, and in a folder that is no +//! repository itself, to the first nested repository. +//! +//! A view acts on one repository (`selected`) or, like a Git Log that shows the +//! histories of several repositories in one list, on a set of them (`chosen`). -use super::{invalid, validate_discovered, DiscoveredRepository}; +use super::{invalid, valid_id, validate_discovered, DiscoveredRepository, MAX_REPOSITORIES}; use crate::contracts::WorkspaceRepositoryRole; use lithe_protocol::CoreError; use serde::{Deserialize, Serialize}; use serde_json::Value; +use std::collections::HashSet; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -20,18 +24,28 @@ struct Request { /// ID the view acted on before, absent when it has not picked one. #[serde(default)] selected: Option, + /// IDs a view that acts on several repositories at once picked before, in + /// any order; an empty list is no pick. Mutually exclusive with `selected`. + #[serde(default)] + chosen: Option>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct Response { - /// ID the view acts on, `null` when the workspace has no repository. + /// ID the view acts on, `null` when the workspace has no repository. With + /// `chosen`, the first of the repositories the view acts on. active: Option, - /// True when the picked repository is no longer listed, so the view drops - /// state that belonged to it, such as an open history walk or a reference filter. + /// True when a picked repository is no longer listed, so the view drops state + /// that belonged to the pick, such as an open history walk or a reference filter. fell_back: bool, - /// Every other ID in discovery order: the groups the view lists for switching. + /// Every ID the view does not act on, in discovery order: the groups the view + /// lists for switching. others: Vec, + /// Present when the request carried `chosen`: the IDs the view acts on, in + /// discovery order. They are the listed picks, or `active` alone when none is. + #[serde(skip_serializing_if = "Option::is_none")] + chosen: Option>, } /// Handles `git.workspaceRepositorySelection`. @@ -45,39 +59,67 @@ pub fn command(payload: Value) -> Result { "A selected workspace repository ID cannot be empty", )); } - let listed = |id: &str| { - request - .repositories - .iter() - .any(|repository| repository.id == id) + if request.selected.is_some() && request.chosen.is_some() { + return Err(invalid( + "A workspace repository selection takes either selected or chosen", + )); + } + let picks: HashSet<&str> = match &request.chosen { + Some(chosen) => validate_chosen(chosen)?, + None => request.selected.iter().map(String::as_str).collect(), + }; + // Kept picks follow discovery order, whatever order the view sent them in. + let kept: Vec = request + .repositories + .iter() + .filter(|repository| picks.contains(repository.id.as_str())) + .map(|repository| repository.id.clone()) + .collect(); + let fell_back = kept.len() < picks.len(); + let acting: Vec = if kept.is_empty() { + fallback(&request.repositories).into_iter().collect() + } else { + kept }; - let kept = request.selected.as_deref().filter(|id| listed(id)); - let fell_back = request.selected.is_some() && kept.is_none(); - let active = kept - .or_else(|| { - request - .repositories - .iter() - .find(|repository| repository.role == WorkspaceRepositoryRole::Workspace) - .map(|repository| repository.id.as_str()) - }) - .or_else(|| { - request - .repositories - .first() - .map(|repository| repository.id.as_str()) - }) - .map(str::to_owned); let others = request .repositories .iter() - .filter(|repository| Some(&repository.id) != active.as_ref()) + .filter(|repository| !acting.contains(&repository.id)) .map(|repository| repository.id.clone()) .collect(); Ok(serde_json::to_value(Response { - active, + active: acting.first().cloned(), fell_back, others, + chosen: request.chosen.is_some().then_some(acting), }) .expect("workspace repository selection should encode")) } + +/// The repository a view acts on without a listed pick: the one that contains +/// the opened folder, otherwise the first listed one. +fn fallback(repositories: &[DiscoveredRepository]) -> Option { + repositories + .iter() + .find(|repository| repository.role == WorkspaceRepositoryRole::Workspace) + .or_else(|| repositories.first()) + .map(|repository| repository.id.clone()) +} + +/// Rejects a `chosen` list discovery cannot form: more IDs than a workspace +/// lists, or an invalid or repeated ID. +fn validate_chosen(chosen: &[String]) -> Result, CoreError> { + if chosen.len() > MAX_REPOSITORIES { + return Err(invalid("Too many chosen workspace repositories")); + } + let mut picks = HashSet::with_capacity(chosen.len()); + for id in chosen { + if !valid_id(id) { + return Err(invalid("Invalid chosen workspace repository ID")); + } + if !picks.insert(id.as_str()) { + return Err(invalid("Duplicate chosen workspace repository")); + } + } + Ok(picks) +} diff --git a/rust/crates/git/src/workspace_repositories/tests.rs b/rust/crates/git/src/workspace_repositories/tests.rs index a9081068..19af52f3 100644 --- a/rust/crates/git/src/workspace_repositories/tests.rs +++ b/rust/crates/git/src/workspace_repositories/tests.rs @@ -1,6 +1,6 @@ //! Workspace repository projections against their shared fixtures. -use super::{change_groups_command, selection_command, MAX_REPOSITORIES}; +use super::{change_groups_command, history_merge_command, selection_command, MAX_REPOSITORIES}; use lithe_protocol::CoreError; use serde_json::{json, Value}; @@ -39,6 +39,65 @@ fn change_groups_match_the_shared_fixture() { ); } +#[test] +fn history_merge_matches_the_shared_fixture() { + check_fixture( + include_str!("../../../../fixtures/git/workspace-history-merge-v1.json"), + history_merge_command, + ); +} + +/// The loaded commits of one repository: `count` commits a minute apart, newest +/// first, each the child of the next. The last loaded one has a parent unless +/// the walk is complete, as a page cut mid-history does. +fn history(id: &str, count: usize, newest: i64, complete: bool) -> Value { + let commits = (0..count) + .map(|index| { + let parents = if index + 1 < count || !complete { + vec![format!("{:x}{:06x}", id.len(), index + 1)] + } else { + Vec::new() + }; + json!({ + "hash": format!("{:x}{index:06x}", id.len()), + "parentHashes": parents, + "timestamp": newest - 60 * index as i64, + }) + }) + .collect::>(); + json!({"id": id, "complete": complete, "commits": commits}) +} + +#[test] +fn history_merge_rows_only_grow_at_the_end_as_pages_arrive() { + let first = history_merge_command(json!({"repositories": [ + history("a", 100, 10_000, false), + history("bb", 100, 9_000, true), + ]})) + .unwrap(); + let second = history_merge_command(json!({"repositories": [ + history("a", 200, 10_000, false), + history("bb", 100, 9_000, true), + ]})) + .unwrap(); + let placed = first["entries"].as_array().unwrap(); + assert_eq!(first["pending"], json!([0])); + assert_eq!( + &second["entries"].as_array().unwrap()[..placed.len()], + placed + ); + assert!(second["entries"].as_array().unwrap().len() > placed.len()); +} + +#[test] +fn history_merges_past_the_commit_bound_are_rejected() { + let request = json!({"repositories": [ + history("a", 10_001, 100_000_000, true), + history("bb", 10_000, 100_000_000, true), + ]}); + assert!(history_merge_command(request).is_err()); +} + #[test] fn repository_lists_past_the_bound_are_rejected() { let repositories = (0..=MAX_REPOSITORIES) diff --git a/rust/fixtures/git/workspace-history-merge-v1.json b/rust/fixtures/git/workspace-history-merge-v1.json new file mode 100644 index 00000000..1bc1232d --- /dev/null +++ b/rust/fixtures/git/workspace-history-merge-v1.json @@ -0,0 +1,225 @@ +{ + "version": 1, + "description": "git.workspaceHistoryMerge interleaves the loaded histories of the repositories a log walks, newest first, keeping each repository's own order. It stops where a repository that is not complete has no loaded commit left, and lists it in pending, so later pages only add rows at the end. A commit without a timestamp takes the one placed before it in its repository; equal timestamps go in request order. A hash more than one repository names, as a commit or as a parent, is keyed @ in each; every other key is the hash.", + "cases": [ + { + "name": "repositoriesInterleaveByDate", + "request": { + "repositories": [ + {"id": "backend", "complete": true, "commits": [ + {"hash": "aaa3", "parentHashes": ["aaa1"], "timestamp": 300}, + {"hash": "aaa1", "timestamp": 100} + ]}, + {"id": "frontend", "complete": true, "commits": [ + {"hash": "bbb2", "timestamp": 200} + ]} + ] + }, + "response": { + "entries": [ + {"repository": 0, "index": 0, "key": "aaa3", "parentKeys": ["aaa1"]}, + {"repository": 1, "index": 0, "key": "bbb2", "parentKeys": []}, + {"repository": 0, "index": 1, "key": "aaa1", "parentKeys": []} + ], + "pending": [] + } + }, + { + "name": "aRepositoryWithPagesLeftStopsTheMergeWhenItRunsOut", + "request": { + "repositories": [ + {"id": "backend", "complete": false, "commits": [ + {"hash": "aaa4", "parentHashes": ["aaa2"], "timestamp": 400}, + {"hash": "aaa2", "parentHashes": ["aaa0"], "timestamp": 200} + ]}, + {"id": "frontend", "complete": true, "commits": [ + {"hash": "bbb3", "parentHashes": ["bbb1"], "timestamp": 300}, + {"hash": "bbb1", "timestamp": 100} + ]} + ] + }, + "response": { + "entries": [ + {"repository": 0, "index": 0, "key": "aaa4", "parentKeys": ["aaa2"]}, + {"repository": 1, "index": 0, "key": "bbb3", "parentKeys": ["bbb1"]}, + {"repository": 0, "index": 1, "key": "aaa2", "parentKeys": ["aaa0"]} + ], + "pending": [0] + } + }, + { + "name": "anIncompleteRepositoryWithNothingLoadedPlacesNothing", + "request": { + "repositories": [ + {"id": "backend", "complete": true, "commits": [{"hash": "aaa1", "timestamp": 100}]}, + {"id": "frontend", "complete": false, "commits": []}, + {"id": "docs", "complete": false, "commits": []} + ] + }, + "response": {"entries": [], "pending": [1, 2]} + }, + { + "name": "aCompleteEmptyRepositoryDoesNotStopTheMerge", + "request": { + "repositories": [ + {"id": "backend", "complete": true, "commits": []}, + {"id": "frontend", "complete": true, "commits": [{"hash": "bbb1", "timestamp": 100}]} + ] + }, + "response": { + "entries": [{"repository": 1, "index": 0, "key": "bbb1", "parentKeys": []}], + "pending": [] + } + }, + { + "name": "aHashTwoRepositoriesHoldIsKeyedPerRepository", + "request": { + "repositories": [ + {"id": "app", "complete": true, "commits": [ + {"hash": "ccc2", "parentHashes": ["ccc1"], "timestamp": 200}, + {"hash": "ccc1", "timestamp": 100} + ]}, + {"id": "vendor/app", "complete": true, "commits": [ + {"hash": "ddd3", "parentHashes": ["ccc2"], "timestamp": 300}, + {"hash": "ccc2", "parentHashes": ["ccc1"], "timestamp": 200}, + {"hash": "ccc1", "timestamp": 100} + ]} + ] + }, + "response": { + "entries": [ + {"repository": 1, "index": 0, "key": "ddd3", "parentKeys": ["ccc2@vendor/app"]}, + {"repository": 0, "index": 0, "key": "ccc2@app", "parentKeys": ["ccc1@app"]}, + {"repository": 1, "index": 1, "key": "ccc2@vendor/app", "parentKeys": ["ccc1@vendor/app"]}, + {"repository": 0, "index": 1, "key": "ccc1@app", "parentKeys": []}, + {"repository": 1, "index": 2, "key": "ccc1@vendor/app", "parentKeys": []} + ], + "pending": [] + } + }, + { + "name": "aParentAnotherRepositoryLoadedIsKeyedPerRepository", + "request": { + "repositories": [ + {"id": "app", "complete": false, "commits": [ + {"hash": "aaa2", "parentHashes": ["eee1"], "timestamp": 200} + ]}, + {"id": "lib", "complete": true, "commits": [ + {"hash": "eee1", "timestamp": 100} + ]} + ] + }, + "response": { + "entries": [ + {"repository": 0, "index": 0, "key": "aaa2", "parentKeys": ["eee1@app"]} + ], + "pending": [0] + } + }, + { + "name": "aCommitWithoutADateStaysBesideTheOneBeforeIt", + "request": { + "repositories": [ + {"id": "backend", "complete": true, "commits": [ + {"hash": "aaa3", "parentHashes": ["aaa2"], "timestamp": 300}, + {"hash": "aaa2", "parentHashes": ["aaa1"]}, + {"hash": "aaa1", "timestamp": 100} + ]}, + {"id": "frontend", "complete": true, "commits": [ + {"hash": "bbb2", "timestamp": 250} + ]} + ] + }, + "response": { + "entries": [ + {"repository": 0, "index": 0, "key": "aaa3", "parentKeys": ["aaa2"]}, + {"repository": 0, "index": 1, "key": "aaa2", "parentKeys": ["aaa1"]}, + {"repository": 1, "index": 0, "key": "bbb2", "parentKeys": []}, + {"repository": 0, "index": 2, "key": "aaa1", "parentKeys": []} + ], + "pending": [] + } + }, + { + "name": "aRepositoryKeepsGitsOrderEvenWhenItsDatesDoNot", + "request": { + "repositories": [ + {"id": "backend", "complete": true, "commits": [ + {"hash": "aaa2", "parentHashes": ["aaa1"], "timestamp": 100}, + {"hash": "aaa1", "timestamp": 300} + ]}, + {"id": "frontend", "complete": true, "commits": [ + {"hash": "bbb1", "timestamp": 200} + ]} + ] + }, + "response": { + "entries": [ + {"repository": 1, "index": 0, "key": "bbb1", "parentKeys": []}, + {"repository": 0, "index": 0, "key": "aaa2", "parentKeys": ["aaa1"]}, + {"repository": 0, "index": 1, "key": "aaa1", "parentKeys": []} + ], + "pending": [] + } + }, + { + "name": "equalDatesGoInRequestOrder", + "request": { + "repositories": [ + {"id": "frontend", "complete": true, "commits": [{"hash": "bbb1", "timestamp": 100}]}, + {"id": "backend", "complete": true, "commits": [{"hash": "aaa1", "timestamp": 100}]} + ] + }, + "response": { + "entries": [ + {"repository": 0, "index": 0, "key": "bbb1", "parentKeys": []}, + {"repository": 1, "index": 0, "key": "aaa1", "parentKeys": []} + ], + "pending": [] + } + }, + { + "name": "noRepositories", + "request": {"repositories": []}, + "response": {"entries": [], "pending": []} + } + ], + "invalid": [ + { + "name": "repeatedRepository", + "request": {"repositories": [ + {"id": "a", "complete": true, "commits": []}, + {"id": "a", "complete": true, "commits": []} + ]} + }, + { + "name": "absoluteRepositoryId", + "request": {"repositories": [{"id": "/w/a", "complete": true, "commits": []}]} + }, + { + "name": "repeatedCommitInOneRepository", + "request": {"repositories": [{"id": "a", "complete": true, "commits": [ + {"hash": "aaa1", "timestamp": 1}, + {"hash": "aaa1", "timestamp": 1} + ]}]} + }, + { + "name": "hashThatIsNoObjectName", + "request": {"repositories": [{"id": "a", "complete": true, "commits": [{"hash": "HEAD", "timestamp": 1}]}]} + }, + { + "name": "parentThatIsNoObjectName", + "request": {"repositories": [{"id": "a", "complete": true, "commits": [ + {"hash": "aaa1", "parentHashes": ["aaa0@b"], "timestamp": 1} + ]}]} + }, + { + "name": "missingComplete", + "request": {"repositories": [{"id": "a", "commits": []}]} + }, + { + "name": "unknownField", + "request": {"repositories": [], "cursor": "x"} + } + ] +} diff --git a/rust/fixtures/git/workspace-repository-selection-v1.json b/rust/fixtures/git/workspace-repository-selection-v1.json index ee961033..a41d9a1f 100644 --- a/rust/fixtures/git/workspace-repository-selection-v1.json +++ b/rust/fixtures/git/workspace-repository-selection-v1.json @@ -59,6 +59,57 @@ "name": "noRepositories", "request": {"repositories": [], "selected": "service-a"}, "response": {"active": null, "fellBack": true, "others": []} + }, + { + "name": "chosenPicksFollowDiscoveryOrder", + "request": { + "repositories": [ + {"path": "/projects/shop", "id": ".", "name": "shop", "role": "workspace"}, + {"path": "/projects/shop/modules/payments", "id": "modules/payments", "name": "modules/payments", "role": "nested"}, + {"path": "/projects/shop/tools", "id": "tools", "name": "tools", "role": "nested"} + ], + "chosen": ["tools", "."] + }, + "response": {"active": ".", "fellBack": false, "others": ["modules/payments"], "chosen": [".", "tools"]} + }, + { + "name": "aRemovedChosenPickDropsOnlyThatPick", + "request": { + "repositories": [ + {"path": "/workspace/service-a", "id": "service-a", "name": "service-a", "role": "nested"}, + {"path": "/workspace/service-b", "id": "service-b", "name": "service-b", "role": "nested"}, + {"path": "/workspace/service-c", "id": "service-c", "name": "service-c", "role": "nested"} + ], + "chosen": ["service-c", "service-old", "service-b"] + }, + "response": {"active": "service-b", "fellBack": true, "others": ["service-a"], "chosen": ["service-b", "service-c"]} + }, + { + "name": "noListedChosenPickFallsBackToOneRepository", + "request": { + "repositories": [ + {"path": "/projects/shop", "id": ".", "name": "shop", "role": "workspace"}, + {"path": "/projects/shop/tools", "id": "tools", "name": "tools", "role": "nested"} + ], + "chosen": ["vendor/old"] + }, + "response": {"active": ".", "fellBack": true, "others": ["tools"], "chosen": ["."]} + }, + { + "name": "anEmptyChosenListIsNoPick", + "request": { + "repositories": [ + {"path": "/workspace/service-a", "id": "service-a", "name": "service-a", "role": "nested"}, + {"path": "/workspace/service-b", "id": "service-b", "name": "service-b", "role": "nested"} + ], + "chosen": [] + }, + "response": {"active": "service-a", "fellBack": false, "others": ["service-b"], "chosen": ["service-a"]} + }, + { + "name": "chosenWithNoRepositories", + "request": {"repositories": [], "chosen": ["service-a"]}, + "response": {"active": null, "fellBack": true, "others": [], "chosen": []} } ], "invalid": [ @@ -109,6 +160,22 @@ "name": "unknownRole", "request": {"repositories": [{"path": "/w/a", "id": "a", "name": "a", "role": "submodule"}]} }, + { + "name": "selectedAndChosen", + "request": {"repositories": [], "selected": "a", "chosen": ["a"]} + }, + { + "name": "duplicateChosenPick", + "request": {"repositories": [], "chosen": ["a", "a"]} + }, + { + "name": "emptyChosenPick", + "request": {"repositories": [], "chosen": [""]} + }, + { + "name": "absoluteChosenPick", + "request": {"repositories": [], "chosen": ["/w/a"]} + }, { "name": "unknownField", "request": {"repositories": [], "active": "a"} From e458f5b6b6d2876cad6aae34e611fa159705e11b Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Mon, 16 Nov 2026 21:28:28 +0800 Subject: [PATCH 2/2] =?UTF-8?q?feat(git):=20historyPage=20=E5=8F=AF?= =?UTF-8?q?=E8=AE=BE=E8=AF=BB=E5=8F=96=E4=B8=8A=E9=99=90=20maxCommits?= =?UTF-8?q?=EF=BC=8C=E8=AF=BB=E6=BB=A1=E6=97=B6=E8=BF=94=E5=9B=9E=20limitR?= =?UTF-8?q?eached=EF=BC=9Bgraph=20=E4=B8=8E=E6=B7=B7=E6=8E=92=E4=B8=8A?= =?UTF-8?q?=E9=99=90=E5=8D=87=E5=88=B0=2010=20=E4=B8=87=E6=9D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - git.historyPage 新增可选的 maxCommits(1–100,000,省略为 5,000):首页为游标固定上限, 后续页省略或重复同一值,不同值返回 invalid_request 且不消耗游标;与 offset 同用或越界返回 invalid_request,已弃用的 offset 分页仍按 5,000。 - 流读满 maxCommits 而历史还有后续时,最后一页返回 limitReached: true(hasMore 为 false), 客户端据此区分“读到上限”和“已读完”,提示用户调大上限;其余情况省略该字段。git log 多要一条, 只用来判断是否还有后续,不返回。 - 共享上限 MAX_LOG_COMMITS = 100,000:git.graphProjection 与 git.workspaceHistoryMerge 的提交上限从 20,000 升到它,桌面端可把单仓库与多仓库日志上限设到 10 万条。 - 更新 rust-core-api.md;新增 date order 测试中的 maxCommits/limitReached 断言,合并上限测试改用共享常量。 Refs 1lck/Lithe-IDEA#2013 --- rust/contracts/rust-core-api.md | 23 +++- rust/crates/git/src/contracts.rs | 3 + rust/crates/git/src/graph.rs | 5 +- rust/crates/git/src/history.rs | 126 +++++++++++++++--- rust/crates/git/src/tests.rs | 1 + .../workspace_repositories/history_merge.rs | 2 +- .../git/src/workspace_repositories/tests.rs | 5 +- 7 files changed, 135 insertions(+), 30 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index b304e3eb..f00107ef 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -1795,7 +1795,8 @@ Each visible row carries `commitHash`, integer `lane` and `laneCount`, a signed `printElements` (the up and down half-edges with `position`, `adjacentPosition`, `colorId`, `isDotted`, `isMissing`, `hasArrow`, `isTerminal`, `targetHash`). Hosts own pixels, curves, and the mapping from a color ID to a theme color; `colorId` `0` means -an unreferenced fragment. Requests over 20,000 commits fail with `invalid_request`. +an unreferenced fragment. Requests over 100,000 commits, the largest Git Log a +`git.historyPage` stream reads, fail with `invalid_request`. `rust/fixtures/git/graph-projection-v1.json` defines the rules and `rust/fixtures/git/graph-idea/` holds the pinned IntelliJ oracles. @@ -1959,7 +1960,7 @@ core clamps it to `1...5000`). It remains the compatibility command that combines `git.references` with the first `git.historyPage`. New clients use `git.references` with `{ "root": string }` and request commits separately with `git.historyPage` using `root`, optional full `reference`, nullable opaque -`cursor`, `limit`, and optional `order` (`"topo"` or `"date"`). Omitted +`cursor`, `limit`, optional `maxCommits`, and optional `order` (`"topo"` or `"date"`). Omitted `order` preserves the original `git log --topo-order` behavior. `"date"` uses `git log --date-order`: committer date descending whenever the child-before- parent constraint permits, independently of the displayed author date. macOS @@ -1970,9 +1971,17 @@ continuations must repeat the same order. A mismatched order returns `rust/fixtures/git/history-page-date-request-v1.json`. The first request omits `cursor`; each later request returns the prior page's `nextCursor`. Core keeps one bounded, backpressured -`git log` stream behind that cursor and clamps the stream to the first 5,000 -commits, so later pages continue traversal instead of replaying earlier commits. -A history page returns `commits`, nullable `nextCursor`, and `hasMore`. Clients +`git log` stream behind that cursor and clamps the stream to the first +`maxCommits` commits, so later pages continue traversal instead of replaying earlier +commits. `maxCommits` is 1 to 100,000 and defaults to 5,000; the first page fixes it +for the cursor, a continuation omits it or repeats the same value, and a different +value returns `invalid_request` without consuming the cursor. `maxCommits` with +`offset`, or out of range, fails with `invalid_request`; the deprecated offset pages +keep the 5,000 bound. +A history page returns `commits`, nullable `nextCursor`, and `hasMore`. When the +stream stops at `maxCommits` while the history goes on, the last page also returns +`limitReached: true` with `hasMore: false`, so a client can tell a bounded log from +a finished one and offer a larger bound; the field is omitted otherwise. Clients call `git.historyCursorClose` with `root` and `cursor` when abandoning an unfinished stream, and discard and close a late page when its repository, selected reference, or owning `operationId` is stale. Core also expires idle @@ -2077,8 +2086,8 @@ and asks again; the earlier entries stay the same, so rows only grow at the end. `key` is the commit's hash, except that a hash more than one repository names, as a commit or as a parent, is keyed `@` in each of them; `parentKeys` apply the same rule, so `git.graphProjection` laid out over the keys never joins -two repositories. At most 10,000 repositories and 20,000 commits in total are -accepted. An invalid or repeated `id`, a hash or parent that is not 1 to 64 +two repositories. At most 10,000 repositories and 100,000 commits in total, +the bound of `git.graphProjection`, are accepted. An invalid or repeated `id`, a hash or parent that is not 1 to 64 hexadecimal digits, a commit repeated within one repository, a missing `complete`, or an unknown field fails with `invalid_request`. See `rust/fixtures/git/workspace-history-merge-v1.json`. diff --git a/rust/crates/git/src/contracts.rs b/rust/crates/git/src/contracts.rs index 790d9c59..dae63988 100644 --- a/rust/crates/git/src/contracts.rs +++ b/rust/crates/git/src/contracts.rs @@ -215,6 +215,9 @@ pub struct GitHistoryPageResponse { #[serde(skip_serializing_if = "Option::is_none")] pub next_offset: Option, pub(crate) has_more: bool, + /// The stream stopped at its `maxCommits` while the history goes on; omitted when false. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub(crate) limit_reached: bool, } #[derive(Debug, Clone, Serialize)] diff --git a/rust/crates/git/src/graph.rs b/rust/crates/git/src/graph.rs index 879b6681..058258db 100644 --- a/rust/crates/git/src/graph.rs +++ b/rust/crates/git/src/graph.rs @@ -30,8 +30,9 @@ use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; const GRAPH_PROJECTION_VERSION: u32 = 1; -/// Largest commit list (scoped window or repository context) one request may carry. -const MAX_COMMITS: usize = 20_000; +/// Largest commit list (scoped window or repository context) one request may carry: the +/// largest Git Log a view may read. +const MAX_COMMITS: usize = crate::history::MAX_LOG_COMMITS; /// IntelliJ samples at most this many rows when recommending a graph width. const RECOMMENDED_WIDTH_SAMPLE_SIZE: usize = 20_000; const RECOMMENDED_WIDTH_WEIGHT_RATIO: f64 = 0.1; diff --git a/rust/crates/git/src/history.rs b/rust/crates/git/src/history.rs index 3db756d4..02b51df2 100644 --- a/rust/crates/git/src/history.rs +++ b/rust/crates/git/src/history.rs @@ -20,7 +20,11 @@ use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; const DEFAULT_HISTORY_LIMIT: usize = 300; -const MAX_HISTORY_COMMITS: usize = 5_000; +/// Commits one history stream reads when its first page names no `maxCommits`. +const DEFAULT_MAX_HISTORY_COMMITS: usize = 5_000; +/// Largest Git Log a view may read: the most `maxCommits` one stream accepts, and the most +/// commits `git.graphProjection` and `git.workspaceHistoryMerge` take in one request. +pub(crate) const MAX_LOG_COMMITS: usize = 100_000; const RECENT_BRANCH_LIMIT: usize = 5; const RECENT_BRANCH_REFLOG_LIMIT: &str = "100"; const DEFAULT_BRANCH_FALLBACKS: [&str; 2] = ["main", "master"]; @@ -78,6 +82,11 @@ pub struct GitHistoryPageRequest { pub offset: Option, #[serde(default = "default_history_limit")] pub(crate) limit: usize, + /// Most commits the stream reads in all, `1..=MAX_LOG_COMMITS`; omission is + /// `DEFAULT_MAX_HISTORY_COMMITS`. The first page fixes it for the cursor, and a + /// continuation omits it or repeats the same value. + #[serde(default)] + pub(crate) max_commits: Option, } /// Git-native ordering policies that both preserve child-before-parent order. @@ -173,6 +182,7 @@ pub fn history(request: GitHistoryRequest) -> Result Result Result Result Result { + Ok((commits, has_more, limit_reached)) => { let next_cursor = has_more.then(|| session.cursor.clone()); if has_more { session.last_access = Instant::now(); @@ -398,6 +430,7 @@ pub fn history_page(request: GitHistoryPageRequest) -> Result { @@ -442,6 +475,7 @@ pub fn history_locate( cursor: cursor.clone(), offset: None, limit: request.limit, + max_commits: None, }) { Ok(page) => page, Err(error) => { @@ -541,12 +575,13 @@ fn offset_history_page( offset: usize, requested_limit: usize, ) -> Result { - if offset >= MAX_HISTORY_COMMITS { + if offset >= DEFAULT_MAX_HISTORY_COMMITS { return Ok(GitHistoryPageResponse { commits: Vec::new(), next_cursor: None, next_offset: None, has_more: false, + limit_reached: false, }); } validate_reference(reference.as_deref())?; @@ -567,10 +602,11 @@ fn offset_history_page( next_cursor: None, next_offset: None, has_more: false, + limit_reached: false, }); } } - let limit = requested_limit.clamp(1, MAX_HISTORY_COMMITS - offset); + let limit = requested_limit.clamp(1, DEFAULT_MAX_HISTORY_COMMITS - offset); let mut arguments = vec!["log".to_string()]; if let Some(reference) = reference { arguments.push(reference); @@ -607,7 +643,8 @@ fn offset_history_page( .lines() .filter_map(parse_commit) .collect::>(); - let has_more = commits.len() > limit && offset.saturating_add(limit) < MAX_HISTORY_COMMITS; + let has_more = + commits.len() > limit && offset.saturating_add(limit) < DEFAULT_MAX_HISTORY_COMMITS; commits.truncate(limit); let next_offset = has_more.then_some(offset.saturating_add(commits.len())); Ok(GitHistoryPageResponse { @@ -615,6 +652,7 @@ fn offset_history_page( next_cursor: None, next_offset, has_more, + limit_reached: false, }) } @@ -668,6 +706,8 @@ struct HistorySession { stderr_reader: Option>>, pending: Option, emitted: usize, + /// Most commits the stream reads, fixed by its first page. + max_commits: usize, last_access: Instant, finished: bool, /// Records the one `git log` process this cursor owns when it ends. @@ -714,10 +754,13 @@ impl Drop for HistorySessionLease { } impl HistorySession { + /// Starts `git log` for at most `max_commits` commits, plus one that only tells whether the + /// history goes on past them. fn start( root: String, reference: Option, order: HistoryOrder, + max_commits: usize, ) -> Result { cancellation::check()?; let mut arguments = vec!["log".to_string()]; @@ -734,7 +777,7 @@ impl HistorySession { "--decorate=short".to_string(), format!("--decorate-refs-exclude={INTERNAL_REF_PREFIX}*"), "-n".to_string(), - MAX_HISTORY_COMMITS.to_string(), + (max_commits + 1).to_string(), GIT_COMMIT_DATE_ARGUMENT.to_string(), "--pretty=format:%H%x1f%h%x1f%P%x1f%an%x1f%ae%x1f%ad%x1f%s%x1f%D".to_string(), ]); @@ -763,6 +806,7 @@ impl HistorySession { stderr_reader: None, pending: None, emitted: 0, + max_commits, last_access: Instant::now(), finished: false, trace: Some(trace), @@ -809,32 +853,42 @@ impl HistorySession { stderr_reader: Some(stderr_reader), pending: None, emitted: 0, + max_commits, last_access: Instant::now(), finished: false, trace: Some(trace), }) } - fn read_page(&mut self, limit: usize) -> Result<(Vec, bool), CoreError> { + /// Reads the next page of at most `limit` commits and returns it, whether more follow, and + /// whether the stream stopped at `max_commits` while the history goes on. + fn read_page( + &mut self, + limit: usize, + ) -> Result<(Vec, bool, bool), CoreError> { let deadline = Instant::now() + HISTORY_PAGE_DEADLINE; let mut commits = Vec::with_capacity(limit); if let Some(commit) = self.pending.take() { commits.push(commit); } - while commits.len() < limit && self.emitted + commits.len() < MAX_HISTORY_COMMITS { + while commits.len() < limit && self.emitted + commits.len() < self.max_commits { let Some(commit) = self.next_commit(deadline)? else { break; }; commits.push(commit); } self.emitted += commits.len(); - let has_more = if self.emitted >= MAX_HISTORY_COMMITS || self.finished { - false - } else { - self.pending = self.next_commit(deadline)?; - self.pending.is_some() - }; - Ok((commits, has_more)) + if self.finished { + return Ok((commits, false, false)); + } + if self.emitted >= self.max_commits { + // Git was asked for one commit past the bound; it only tells that the history + // goes on, and is never returned. + let beyond = self.next_commit(deadline)?.is_some(); + return Ok((commits, false, beyond)); + } + self.pending = self.next_commit(deadline)?; + Ok((commits, self.pending.is_some(), false)) } fn next_commit(&mut self, deadline: Instant) -> Result, CoreError> { @@ -1461,6 +1515,41 @@ mod tests { page(json!({"order": "authorDate", "limit": 20}))["ok"], false ); + + // The first page fixes how many commits the stream reads; the last page says the + // history goes on past them, and a continuation cannot change the bound. + let bounded = + page(json!({"reference": "HEAD", "order": "date", "maxCommits": 3, "limit": 2})); + let bounded_cursor = bounded["data"]["nextCursor"] + .as_str() + .expect("bounded cursor") + .to_string(); + repository.cursors.push(bounded_cursor.clone()); + assert_eq!(subjects(&bounded), ["merge", "b2"]); + assert_eq!(bounded["data"]["limitReached"], Value::Null); + let rebound = page(json!({ + "reference": "HEAD", "order": "date", "cursor": bounded_cursor, "maxCommits": 4, "limit": 2 + })); + assert_eq!(rebound["error"]["code"], "invalid_request", "{rebound}"); + let last = page(json!({ + "reference": "HEAD", "order": "date", "cursor": bounded_cursor, "maxCommits": 3, "limit": 2 + })); + assert_eq!(subjects(&last), ["a2"]); + assert_eq!(last["data"]["hasMore"], false); + assert_eq!(last["data"]["nextCursor"], Value::Null); + assert_eq!(last["data"]["limitReached"], true); + let whole = + page(json!({"reference": "HEAD", "order": "date", "maxCommits": 6, "limit": 20})); + assert_eq!(subjects(&whole).len(), 6); + assert_eq!(whole["data"]["hasMore"], false); + assert_eq!(whole["data"]["limitReached"], Value::Null); + for invalid in [ + json!({"maxCommits": 0}), + json!({"maxCommits": super::MAX_LOG_COMMITS + 1}), + json!({"maxCommits": 3, "offset": 0}), + ] { + assert_eq!(page(invalid)["error"]["code"], "invalid_request"); + } } #[test] @@ -1581,6 +1670,7 @@ mod tests { stderr_reader: None, pending: None, emitted: 0, + max_commits: super::DEFAULT_MAX_HISTORY_COMMITS, last_access, finished: true, trace: None, diff --git a/rust/crates/git/src/tests.rs b/rust/crates/git/src/tests.rs index 0127ca4a..270adc3d 100644 --- a/rust/crates/git/src/tests.rs +++ b/rust/crates/git/src/tests.rs @@ -746,6 +746,7 @@ fn history_page_response_matches_shared_fixture() { next_cursor: Some("git-history-cursor-fixture".into()), next_offset: None, has_more: true, + limit_reached: false, }; assert_eq!( diff --git a/rust/crates/git/src/workspace_repositories/history_merge.rs b/rust/crates/git/src/workspace_repositories/history_merge.rs index c6169c6f..b3e06913 100644 --- a/rust/crates/git/src/workspace_repositories/history_merge.rs +++ b/rust/crates/git/src/workspace_repositories/history_merge.rs @@ -26,7 +26,7 @@ use std::cmp::Reverse; use std::collections::{BinaryHeap, HashMap, HashSet}; /// Matches the commit bound of `git.graphProjection`, which lays out the merged list. -const MAX_COMMITS: usize = 20_000; +const MAX_COMMITS: usize = crate::history::MAX_LOG_COMMITS; /// SHA-256 object names are the longest Git writes. const MAX_HASH_BYTES: usize = 64; diff --git a/rust/crates/git/src/workspace_repositories/tests.rs b/rust/crates/git/src/workspace_repositories/tests.rs index 19af52f3..3c58f52b 100644 --- a/rust/crates/git/src/workspace_repositories/tests.rs +++ b/rust/crates/git/src/workspace_repositories/tests.rs @@ -91,9 +91,10 @@ fn history_merge_rows_only_grow_at_the_end_as_pages_arrive() { #[test] fn history_merges_past_the_commit_bound_are_rejected() { + let half = crate::history::MAX_LOG_COMMITS / 2; let request = json!({"repositories": [ - history("a", 10_001, 100_000_000, true), - history("bb", 10_000, 100_000_000, true), + history("a", half + 1, 100_000_000, true), + history("bb", half, 100_000_000, true), ]}); assert!(history_merge_command(request).is_err()); }