diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 0c2afc0c..4b95e906 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -770,6 +770,8 @@ 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.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.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 | @@ -898,6 +900,21 @@ embedded spaces and long paths are not rejected by length; native Git/filesystem errors remain visible. In particular, Windows may reject an over-MAX_PATH Git working directory at process creation even when filesystem lookup succeeds; this is reported as `process_start_failed`, not a missing repository. Shared examples live in `rust/fixtures/git/windows-paths.json`. +Each entry also carries the portable identity clients key repositories by: +`id` is the root relative to the opened folder with `/` separators — `.` for the +folder itself, `service-a` or `libs/core` below it, and one `..` per level for an +enclosing repository (`../..` when the folder is `packages/app` of a checkout). +It is the ID that `git.workspaceRepositorySelection`, `git.workspaceChangeGroups`, +`git.workspaceCommitPrepare` and `git.repositoryColorAssignments` take; a remote +workspace computes it from host paths, so it is the same as for a local folder. +`role` is `workspace` for the repository that contains the opened folder (the +folder itself or an enclosing checkout), at most one entry and always first, and +`nested` for every repository below the folder. An opened folder outside every +repository — a parent folder that only holds independent checkouts — has no +`workspace` entry, and clients must not assume one exists. `name` is the label +views show: the root folder's name for the workspace repository and the `id` for +a nested one, so same-named folders in different places stay distinguishable. It +is a file name, never translated. See `rust/fixtures/workspace/repositories-v1.json`. Core treats both `.git` directories and `.git` files as repository markers, but a marker only becomes a listed repository when Git can open it: a `.git` directory needs @@ -1961,6 +1978,50 @@ Callers must keep pages from the same list generation together, cancel or discar stale results, and never recompute the slots per row. Color palettes remain native presentation. See `rust/fixtures/git/repository-colors-v1.json`. +`git.workspaceRepositorySelection` is pure. It accepts `{ repositories, +selected? }`, where `repositories` are the `workspace.repositories` entries +`{ path, id, name, role }` passed back unchanged and in discovery order, and +`selected` is the ID the view acted on before. The response is +`{ active, fellBack, others }`: `active` is `selected` while it is still listed, +otherwise the entry with role `workspace`, otherwise the first entry, and `null` +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. +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 +`rust/fixtures/git/workspace-repository-selection-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`, +`staged`, `worktree`, `canToggleStaging`, `submodule.commitChanged`, and +`untrackedFileCount`; other change fields are accepted and ignored. At most +1,000,000 changes are accepted across the request, and an empty change path or +original path fails with `invalid_request`. The response is `{ groups, +fileCount, stagedCount, allStaged, stageAll? }`. `groups` lists the repositories +that have changes in discovery order, each `{ id, name, role, fileCount, +stagedCount, allStaged, toggleable, staging?, parentReference? }`. `fileCount` +counts each file of a summarized untracked directory. `allStaged` is `true` when +every change with `canToggleStaging` is staged with nothing left in the +worktree and at least one exists. `staging` is `{ operation, paths }` and is +absent when the checkbox writes nothing: `unstage` takes the staged changes that +can toggle when `allStaged`, and `stage` otherwise takes the changes that can +toggle and are unstaged or still changed in the worktree. Paths are +repository-relative in change order, with both sides of a rename. `stageAll` +is the workspace line's checkbox: one `operation`, chosen from `allStaged` +across every repository, applied to every repository with something to write, +as `{ operation, repositories: [{ id, paths }] }`. `parentReference` is present +when the deepest listed ancestor's status lists the repository as a gitlink: +`moved` when its recorded commit changed and `unchanged` when only the child's +content did. An independent repository the ancestor tracks as untracked or +ignores has none. Ancestry is compared on host paths, so a remote workspace's +enclosing repository and its nested ones still relate. Views own folding, +drawing, and running the staging writes. See +`rust/fixtures/git/workspace-change-groups-v1.json`. + `git.branchNamePreview` is pure: it never starts Git and only reads the reference facts the host already loaded. It accepts `rawName` (at most 1,024 characters; longer input is `invalid_request`), `requireName` (`true` on submit, @@ -4923,6 +4984,16 @@ finds real gitlink relationships, includes clean parents when requested, orders children first, and adds push-only child work where needed. Cycles fail closed. A changed reviewed plan must be displayed and confirmed again before any step. +Optional `workspaceRepositories` takes the opened folder's `workspace.repositories` +entries unchanged, validated as `git.workspaceRepositorySelection` validates them, +and binds every `nested` entry whose root `repositories` does not already bind, in +discovery order, under its discovery `id`. A commit of the workspace therefore also +commits the repositories nested in it, so the host binds only what it chose itself +(usually the `workspace` entry, which Core never adds). An entry whose root no +longer exists is skipped. Nothing is added while a `pathScope` is given or the +`previous` plan had one, and a retry adds only IDs the `previous` session already +held, so the reviewed plan never gains repositories between attempts. + When `push` is set, Core also checks whether any repository's branch tracks a differently named remote branch (a `divergent` push destination, see `git.pushPreview`). Those repositories are returned as `pushTargetQuestions: [{ diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 5ca28863..ea6e1b28 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -847,6 +847,10 @@ 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`). + WorkspaceRepositorySelection, + /// Groups workspace repositories' changes and plans their staging (`git.workspaceChangeGroups`). + WorkspaceChangeGroups, /// Plans a branch Update or Pull from collected facts (`git.updatePlan`). UpdatePlan, /// Plans history refresh windows, page merges, and selection retention (`git.historyWindow`). @@ -1468,6 +1472,10 @@ impl CoreCommand { "git.repositoryColorAssignments" => { Some(Self::Git(GitCommand::RepositoryColorAssignments)) } + "git.workspaceRepositorySelection" => { + Some(Self::Git(GitCommand::WorkspaceRepositorySelection)) + } + "git.workspaceChangeGroups" => Some(Self::Git(GitCommand::WorkspaceChangeGroups)), "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 7de05cbb..961cd0ae 100644 --- a/rust/crates/core/src/runtime/dispatcher/git.rs +++ b/rust/crates/core/src/runtime/dispatcher/git.rs @@ -419,6 +419,14 @@ pub(super) fn dispatch(command: GitCommand, id: Option, payload: Value) GitCommand::RepositoryColorAssignments => { plugin_response(id, payload, lithe_git::repository_color_assignments_command) } + GitCommand::WorkspaceRepositorySelection => plugin_response( + id, + payload, + lithe_git::workspace_repository_selection_command, + ), + GitCommand::WorkspaceChangeGroups => { + plugin_response(id, payload, lithe_git::workspace_change_groups_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.rs b/rust/crates/core/src/tests/git.rs index 0c77d8db..37e5bbd8 100644 --- a/rust/crates/core/src/tests/git.rs +++ b/rust/crates/core/src/tests/git.rs @@ -327,12 +327,24 @@ fn workspace_repositories_discovers_multiple_child_repositories() { .expect("workspace repositories response should be JSON"); assert_eq!(response["ok"], true, "{response:?}"); + // The opened folder is no repository itself, so every entry is nested and keyed + // by its path below the folder. + let nested_id = format!("service-a/vendor{}", "/d".repeat(40)); assert_eq!( response["data"]["repositories"], serde_json::json!([ - { "path": reported_repository_path(&first) }, - { "path": reported_repository_path(&second) }, - { "path": reported_repository_path(&nested) } + { + "path": reported_repository_path(&first), + "id": "service-a", "name": "service-a", "role": "nested" + }, + { + "path": reported_repository_path(&second), + "id": "service-b", "name": "service-b", "role": "nested" + }, + { + "path": reported_repository_path(&nested), + "id": nested_id, "name": nested_id, "role": "nested" + } ]) ); @@ -374,7 +386,10 @@ fn workspace_repositories_skips_dangling_gitfile_pointers() { assert_eq!(response["ok"], true, "{response:?}"); assert_eq!( response["data"]["repositories"], - serde_json::json!([{ "path": reported_repository_path(&healthy) }]) + serde_json::json!([{ + "path": reported_repository_path(&healthy), + "id": "healthy", "name": "healthy", "role": "nested" + }]) ); fs::remove_dir_all(root).expect("temporary workspace should be removable"); diff --git a/rust/crates/core/src/tests/git_repository_discovery.rs b/rust/crates/core/src/tests/git_repository_discovery.rs index 552c2983..d46a0fa5 100644 --- a/rust/crates/core/src/tests/git_repository_discovery.rs +++ b/rust/crates/core/src/tests/git_repository_discovery.rs @@ -66,6 +66,23 @@ fn canonical(root: &Path) -> String { .replace('\\', "/") } +fn folder_name(root: &Path) -> String { + canonical(root).rsplit('/').next().unwrap().to_owned() +} + +/// Role, ID and name of every discovered repository, in discovery order. +fn identities(root: &Path) -> Vec<(String, String, String)> { + data("workspace.repositories", json!({"root": root}))["repositories"] + .as_array() + .unwrap() + .iter() + .map(|entry| { + let field = |name: &str| entry[name].as_str().unwrap().to_owned(); + (field("role"), field("id"), field("name")) + }) + .collect() +} + fn fixture() -> Value { serde_json::from_str(include_str!( "../../../../fixtures/workspace/repository-visibility-v1.json" @@ -172,7 +189,10 @@ fn discovery_respects_explicit_depth_limits() { "workspace.repositories", json!({"root": root, "maxDepth": 0}) )["repositories"], - json!([{"path": canonical(&root)}]) + json!([{ + "path": canonical(&root), "id": ".", + "name": folder_name(&root), "role": "workspace" + }]) ); } @@ -187,3 +207,41 @@ fn discovery_does_not_follow_directory_symlinks() { std::os::unix::fs::symlink(&root, root.join("cycle")).unwrap(); assert_eq!(discover(&root), vec![canonical(&root)]); } + +#[test] +fn discovery_keys_repositories_by_their_place_relative_to_the_opened_folder() { + let owned = + |role: &str, id: &str, name: &str| (role.to_owned(), id.to_owned(), name.to_owned()); + let workspace = Workspace::new(); + // A folder outside every repository has no workspace repository; each nested + // one is keyed and named by its path below the folder. + workspace.initialize("backend"); + workspace.initialize("frontend/web"); + assert_eq!( + identities(&workspace.0), + vec![ + owned("nested", "backend", "backend"), + owned("nested", "frontend/web", "frontend/web"), + ] + ); + + // A folder inside a repository reaches the enclosing repository through `..` + // segments, and that repository keeps its own folder name. + let enclosing = workspace.initialize("mono"); + let opened = enclosing.join("packages").join("app"); + fs::create_dir_all(&opened).unwrap(); + workspace.initialize("mono/packages/app/vendor/lib"); + assert_eq!( + identities(&opened), + vec![ + owned("workspace", "../..", &folder_name(&enclosing)), + owned("nested", "vendor/lib", "vendor/lib"), + ] + ); + + // The repository at the opened folder is the workspace repository with ID `.`. + assert_eq!( + identities(&enclosing)[0], + owned("workspace", ".", &folder_name(&enclosing)) + ); +} diff --git a/rust/crates/core/src/tests/git_workspace_commit.rs b/rust/crates/core/src/tests/git_workspace_commit.rs index 333a311f..8fc7bfc5 100644 --- a/rust/crates/core/src/tests/git_workspace_commit.rs +++ b/rust/crates/core/src/tests/git_workspace_commit.rs @@ -1152,3 +1152,66 @@ fn git_workspace_changelist_guard_checks_newly_staged_directory_members_and_over ); assert!(repo.0.join("dir/new.txt").exists()); } + +fn bound_ids(prepared: &Value) -> Vec { + prepared["session"]["plan"]["repositories"] + .as_array() + .unwrap() + .iter() + .map(|binding| binding["id"].as_str().unwrap().to_owned()) + .collect() +} + +#[test] +fn git_workspace_commit_binds_discovered_nested_repositories_outside_scopes_and_retries() { + let repo = repository("workspace-commit-discovered"); + let child = repo.0.join("libs/B"); + init(&child); + let gone = repo.0.join("gone"); + init(&gone); + staged_file(&repo.0, "parent.txt", "one"); + staged_file(&child, "child.txt", "one"); + let discovered = request(&repo.0, "workspace.repositories", json!({})); + assert_eq!(discovered["ok"], true, "{discovered}"); + let discovered = discovered["data"]["repositories"].clone(); + fs::remove_dir_all(&gone).unwrap(); + let own = json!([{"id": ".", "root": repo.0}]); + + // Core binds the nested entries; the removed one is skipped, and the workspace + // entry is the host's own binding. + let prepared = prepare_workspace_with( + &repo.0, + &[(".", &repo.0)], + json!({"workspaceRepositories": discovered}), + ); + assert_eq!(bound_ids(&prepared), [".", "libs/B"], "{prepared}"); + + // A path-scoped commit acts only on the repositories the host bound. + let scoped = prepare_workspace_with( + &repo.0, + &[(".", &repo.0)], + json!({"workspaceRepositories": discovered, + "pathScope": {"include": true, "paths": {".": ["parent.txt"]}}}), + ); + assert_eq!(bound_ids(&scoped), ["."], "{scoped}"); + + // A retry keeps the previous plan's repositories instead of gaining new ones. + let first = prepare_workspace_with(&repo.0, &[(".", &repo.0)], json!({})); + let mut retry = first["session"]["plan"].clone(); + retry["repositories"] = own; + retry["previous"] = first["session"].clone(); + retry["workspaceRepositories"] = discovered.clone(); + let retried = request(&repo.0, "git.workspaceCommitPrepare", retry); + assert_eq!(retried["ok"], true, "{retried}"); + assert_eq!(bound_ids(&retried["data"]), ["."], "{retried}"); + + let mut invalid = discovered; + invalid[0]["id"] = json!("/absolute"); + let rejected = request( + &repo.0, + "git.workspaceCommitPrepare", + json!({"repositories": [{"id": ".", "root": repo.0}], "message": "batch", + "includeParentReferences": false, "workspaceRepositories": invalid}), + ); + assert_eq!(rejected["error"]["code"], "invalid_request", "{rejected}"); +} diff --git a/rust/crates/core/src/tests/git_workspace_repositories.rs b/rust/crates/core/src/tests/git_workspace_repositories.rs new file mode 100644 index 00000000..60083990 --- /dev/null +++ b/rust/crates/core/src/tests/git_workspace_repositories.rs @@ -0,0 +1,171 @@ +//! `git.workspaceRepositorySelection` and `git.workspaceChangeGroups` against +//! their shared fixtures, and against real discovery and status output passed +//! through unchanged. + +use super::support::temporary_root; +use crate::execute_json; +use serde_json::{json, Value}; +use std::fs; +use std::path::{Path, PathBuf}; + +struct Folder(PathBuf); +impl Drop for Folder { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn call(command: &str, payload: Value) -> Value { + serde_json::from_str(&execute_json( + &json!({"id":"workspace-repositories-test", "command":command, "payload":payload}) + .to_string(), + )) + .unwrap() +} + +fn data(command: &str, payload: Value) -> Value { + let response = call(command, payload); + assert_eq!(response["ok"], true, "{command}: {response}"); + response["data"].clone() +} + +fn git(root: &Path, arguments: &[&str]) { + // The shared host owns the subprocess deadline and process-tree cleanup. + let result = data("git.command", json!({"root": root, "arguments": arguments})); + assert_eq!(result["exitCode"], 0, "{arguments:?}: {result}"); +} + +fn init(root: &Path) { + fs::create_dir_all(root).unwrap(); + git(root, &["init", "-q"]); + git(root, &["config", "user.name", "Workspace Test"]); + git(root, &["config", "user.email", "workspace@example.invalid"]); + git(root, &["config", "commit.gpgsign", "false"]); + git(root, &["config", "core.autocrlf", "false"]); +} + +fn check_fixture(command: &str, fixture: &str) { + let fixture: Value = serde_json::from_str(fixture).unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let response = call(command, case["request"].clone()); + assert_eq!(response["ok"], true, "{}: {response}", case["name"]); + assert_eq!(response["data"], case["response"], "{}", case["name"]); + } + for case in fixture["invalid"].as_array().unwrap() { + let response = call(command, case["request"].clone()); + assert_eq!(response["ok"], false, "{}: {response}", case["name"]); + assert_eq!( + response["error"]["code"], "invalid_request", + "{}", + case["name"] + ); + } +} + +#[test] +fn selection_and_change_groups_match_their_shared_fixtures() { + check_fixture( + "git.workspaceRepositorySelection", + include_str!("../../../../fixtures/git/workspace-repository-selection-v1.json"), + ); + check_fixture( + "git.workspaceChangeGroups", + include_str!("../../../../fixtures/git/workspace-change-groups-v1.json"), + ); +} + +/// Discovery entries with the status each repository reports, as hosts send them. +fn repositories_with_changes(root: &Path) -> Value { + let mut repositories = + data("workspace.repositories", json!({"root": root}))["repositories"].clone(); + for repository in repositories.as_array_mut().unwrap() { + let status = data("git.status", json!({"root": repository["path"]})); + repository["changes"] = status["changes"].clone(); + } + repositories +} + +fn group<'a>(groups: &'a Value, id: &str) -> &'a Value { + groups["groups"] + .as_array() + .unwrap() + .iter() + .find(|group| group["id"] == id) + .unwrap_or_else(|| panic!("no group {id}: {groups}")) +} + +#[test] +fn discovery_and_status_pass_through_to_selection_and_change_groups() { + let parent = Folder(temporary_root("workspace-change-groups")); + init(&parent.0); + let child = parent.0.join("libs/B"); + init(&child); + fs::write(child.join("hello.ts"), "one").unwrap(); + git(&child, &["add", "hello.ts"]); + git(&child, &["commit", "-qm", "child initial"]); + fs::write(parent.0.join("parent.txt"), "parent").unwrap(); + fs::write(parent.0.join(".gitignore"), "extras/\n").unwrap(); + fs::write( + parent.0.join(".gitmodules"), + "[submodule \"B\"]\npath = libs/B\nurl = ./libs/B\n", + ) + .unwrap(); + git(&parent.0, &["add", "."]); + git(&parent.0, &["commit", "-qm", "parent initial"]); + let extras = parent.0.join("extras"); + init(&extras); + fs::write(extras.join("notes.txt"), "notes").unwrap(); + fs::write(child.join("hello.ts"), "two").unwrap(); + + let discovered = + data("workspace.repositories", json!({"root": parent.0}))["repositories"].clone(); + let selection = data( + "git.workspaceRepositorySelection", + json!({"repositories": discovered, "selected": "libs/B"}), + ); + assert_eq!( + selection, + json!({"active": "libs/B", "fellBack": false, "others": [".", "extras"]}) + ); + + // Child content alone leaves the parent's recorded commit where it was. + let groups = data( + "git.workspaceChangeGroups", + json!({"repositories": repositories_with_changes(&parent.0)}), + ); + let ids = groups["groups"] + .as_array() + .unwrap() + .iter() + .map(|group| group["id"].as_str().unwrap()) + .collect::>(); + assert_eq!(ids, [".", "extras", "libs/B"], "{groups}"); + assert_eq!(group(&groups, ".")["toggleable"], false, "{groups}"); + assert!(group(&groups, ".").get("staging").is_none(), "{groups}"); + assert!(group(&groups, "extras").get("parentReference").is_none()); + assert_eq!( + group(&groups, "extras")["staging"], + json!({"operation": "stage", "paths": ["notes.txt"]}) + ); + assert_eq!(group(&groups, "libs/B")["parentReference"], "unchanged"); + assert_eq!( + groups["stageAll"], + json!({"operation": "stage", "repositories": [ + {"id": "extras", "paths": ["notes.txt"]}, + {"id": "libs/B", "paths": ["hello.ts"]} + ]}) + ); + + // A child commit moves the gitlink; the child keeps changes so its group stays. + git(&child, &["commit", "-qam", "child update"]); + fs::write(child.join("hello.ts"), "three").unwrap(); + let groups = data( + "git.workspaceChangeGroups", + json!({"repositories": repositories_with_changes(&parent.0)}), + ); + assert_eq!( + group(&groups, "libs/B")["parentReference"], + "moved", + "{groups}" + ); +} diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index 89405728..e6e3d064 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -31,6 +31,7 @@ mod git_repository_setup; mod git_untracked_directories; mod git_update_plan; mod git_workspace_commit; +mod git_workspace_repositories; mod git_workspace_status; mod git_worktree_creation_preview; mod github; diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index cbcfa3f6..af229124 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -450,7 +450,17 @@ fn discovered_repository_keeps_host_identity(symlink: bool) { "workspace.repositories", json!({"root": placeholder}), ); - assert_eq!(discovered["repositories"], json!([{"path": expected}])); + // The identity is relative to the folder the remote host opened, never to the + // local placeholder, so it survives the path mapping unchanged. + assert_eq!( + discovered["repositories"], + json!([{ + "path": expected, + "id": if symlink { "." } else { ".." }, + "name": "host", + "role": "workspace" + }]) + ); let root = discovered["repositories"][0]["path"].as_str().unwrap(); // Simulate the bridge's next request using only the returned repository URL. diff --git a/rust/crates/git/src/contracts.rs b/rust/crates/git/src/contracts.rs index b91ad376..790d9c59 100644 --- a/rust/crates/git/src/contracts.rs +++ b/rust/crates/git/src/contracts.rs @@ -10,6 +10,28 @@ pub struct WorkspaceRepositoryResponse { /// Windows paths are plain drive or UNC paths without the verbatim `\\?\` /// prefix that canonicalization adds. pub path: String, + /// Portable identity relative to the opened folder with `/` separators: `.` for + /// the folder itself, `a/b` below it, and `..` segments for an enclosing + /// repository. Commands that key repositories by ID take this value. + pub id: String, + /// Label the views show: the root folder's name for the workspace repository, + /// and the ID for a nested one, so two nested folders with the same name stay + /// distinguishable. It is a file name, never translated. + pub name: String, + /// How the repository relates to the opened folder. + pub role: WorkspaceRepositoryRole, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +/// How a discovered repository relates to the opened folder. +pub enum WorkspaceRepositoryRole { + /// Contains the opened folder: the folder itself or an enclosing repository. At + /// most one repository has this role and it is listed first; an opened folder + /// outside every repository has none. + Workspace, + /// Lies below the opened folder. + Nested, } #[derive(Debug, Clone, Serialize)] diff --git a/rust/crates/git/src/lib.rs b/rust/crates/git/src/lib.rs index fd9f3654..37ba8c02 100644 --- a/rust/crates/git/src/lib.rs +++ b/rust/crates/git/src/lib.rs @@ -22,6 +22,7 @@ pub mod contracts; mod deleted_selection; mod diff_blocks; pub mod workspace_commit; +mod workspace_repositories; pub mod workspace_status; pub use commit_state::{inspect as commit_state, GitCommitGitlink, GitCommitState}; @@ -124,6 +125,10 @@ pub use repository_colors::assign_command as repository_color_assignments_comman pub use rollback::{rollback_plan_command, rollback_prepare_command}; 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, + selection_command as workspace_repository_selection_command, +}; pub use worktree_rules::creation_preview_command as worktree_creation_preview_command; /// Internals the `git.*` integration tests in `lithe-core` assert against. @@ -168,6 +173,7 @@ use crate::contracts::{ GitPushTagResponse, GitPushTargetKind, GitReferenceResponse, GitStashResponse, GitStashesResponse, GitStatusResponse, GitWatchContextResponse, GitWorktreeResponse, GitWorktreesResponse, WorkspaceRepositoriesResponse, WorkspaceRepositoryResponse, + WorkspaceRepositoryRole, }; use lithe_protocol::{CoreError, ErrorCode}; use lithe_workspace::fs; diff --git a/rust/crates/git/src/repository.rs b/rust/crates/git/src/repository.rs index e845c9c8..21bb4a87 100644 --- a/rust/crates/git/src/repository.rs +++ b/rust/crates/git/src/repository.rs @@ -81,21 +81,79 @@ pub fn workspace_repositories( .into_iter() .collect::>(); sort_workspace_repository_paths(&mut repositories, &workspace_root); - if let Some(repository) = containing_repository { - repositories.retain(|path| path != &repository); - repositories.insert(0, repository); + if let Some(repository) = &containing_repository { + repositories.retain(|path| path != repository); + repositories.insert(0, repository.clone()); } Ok(WorkspaceRepositoriesResponse { repositories: repositories .into_iter() - .map(|path| WorkspaceRepositoryResponse { - path: slash_separated_path(&path, Platform::HOST), + .filter_map(|path| { + workspace_repository_entry(&path, &workspace_root, containing_repository.as_ref()) }) .collect(), }) } +/// Projects one discovered root onto its portable identity, role and label. +/// +/// The opened folder's own `.git` also makes it the workspace repository when +/// `rev-parse` could not report it, so the role does not hinge on that one process. +/// Both paths are canonical, so a repository is always the folder, below it, or an +/// ancestor of it; anything else has no portable identity to key by and is dropped. +fn workspace_repository_entry( + path: &Path, + workspace_root: &Path, + containing_repository: Option<&PathBuf>, +) -> Option { + let role = if containing_repository.is_some_and(|repository| repository == path) + || path == workspace_root + { + WorkspaceRepositoryRole::Workspace + } else { + WorkspaceRepositoryRole::Nested + }; + let id = workspace_repository_id(path, workspace_root)?; + let name = match role { + WorkspaceRepositoryRole::Workspace => path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| slash_separated_path(path, Platform::HOST)), + WorkspaceRepositoryRole::Nested => id.clone(), + }; + Some(WorkspaceRepositoryResponse { + path: slash_separated_path(path, Platform::HOST), + id, + name, + role, + }) +} + +/// Identity of `repository` relative to the opened folder: `.` for the folder itself, +/// its `/`-separated path below the folder, or one `..` per level for an enclosing +/// repository. `None` when the two paths share no ancestry. +/// +/// A remote workspace reports an enclosing repository in the host-path namespace, +/// a sibling of the placeholder folder, so both paths are compared as host paths. +fn workspace_repository_id(repository: &Path, workspace_root: &Path) -> Option { + let repository = lithe_workspace::remote_path(repository); + let workspace_root = lithe_workspace::remote_path(workspace_root); + let (repository, workspace_root) = (repository.as_path(), workspace_root.as_path()); + if repository == workspace_root { + return Some(".".to_string()); + } + if let Ok(relative) = repository.strip_prefix(workspace_root) { + return Some(slash_separated_path(relative, Platform::HOST)); + } + let levels = workspace_root + .strip_prefix(repository) + .ok()? + .components() + .count(); + Some(vec![".."; levels].join("/")) +} + fn repository_scan_directory_is_visible(name: &str) -> bool { // These intentional checkout containers are hidden in the file tree but // remain discoverable in Git. Apply exclusions to their children as usual. @@ -423,9 +481,54 @@ pub(crate) fn relative_or_absolute(path: &Path, root: &Path) -> String { #[cfg(test)] mod tests { - use super::validate_git_path_on; + use super::{validate_git_path_on, workspace_repository_entry}; use lithe_platform::Platform; - use std::path::Path; + use serde_json::Value; + use std::path::{Path, PathBuf}; + + #[test] + fn discovered_roots_project_onto_the_shared_identities() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../fixtures/workspace/repositories-v1.json" + )) + .unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let root = PathBuf::from(case["payload"]["root"].as_str().unwrap()); + let expected = &case["response"]["repositories"]; + // The fixture's workspace entry stands for what `rev-parse` reported. + let containing = expected + .as_array() + .unwrap() + .iter() + .find(|entry| entry["role"] == "workspace") + .map(|entry| PathBuf::from(entry["path"].as_str().unwrap())); + let actual = expected + .as_array() + .unwrap() + .iter() + .map(|entry| { + let path = PathBuf::from(entry["path"].as_str().unwrap()); + workspace_repository_entry(&path, &root, containing.as_ref()).unwrap() + }) + .collect::>(); + assert_eq!( + &serde_json::to_value(actual).unwrap(), + expected, + "{}", + case["name"] + ); + } + } + + #[test] + fn a_root_without_shared_ancestry_has_no_identity() { + assert!(workspace_repository_entry( + Path::new("/elsewhere/repo"), + Path::new("/workspace"), + None + ) + .is_none()); + } #[test] fn windows_rejects_relative_names_it_would_store_differently() { diff --git a/rust/crates/git/src/workspace_commit.rs b/rust/crates/git/src/workspace_commit.rs index 62257d12..563f8be4 100644 --- a/rust/crates/git/src/workspace_commit.rs +++ b/rust/crates/git/src/workspace_commit.rs @@ -6,8 +6,9 @@ pub use path_scope::PathScope; use super::{ commit_state, DivergentPushDestination, GitCommitGitlink, GitCommitState, GitWriteRequest, - PushTargetChoiceRequest, + PushTargetChoiceRequest, WorkspaceRepositoryRole, }; +use crate::workspace_repositories::{validate_discovered, DiscoveredRepository}; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; @@ -159,6 +160,11 @@ pub struct PrepareRequest { pub(crate) previous: Option, #[serde(default)] pub(crate) reviewed: Option, + /// `workspace.repositories` entries for the opened folder, passed back + /// unchanged. Core binds every nested one `repositories` does not already + /// bind, so a commit of the workspace also commits the repositories nested in it. + #[serde(default)] + pub(crate) workspace_repositories: Vec, } #[derive(Debug, Serialize)] @@ -209,11 +215,52 @@ fn validate_bindings(bindings: &[RepositoryBinding]) -> Result<(), CoreError> { Ok(()) } +/// Binds the nested repositories of `workspaceRepositories` that `repositories` +/// does not already bind, in discovery order. +/// +/// The entry with role `workspace` is the repository the host committed from and +/// binds itself. A path-scoped commit acts only on the repositories it names, and +/// a retry only on the repositories the previous plan bound, so neither gains +/// new ones. A nested repository removed since discovery is skipped. +fn bind_nested_repositories(request: &mut PrepareRequest) -> Result<(), CoreError> { + let discovered = std::mem::take(&mut request.workspace_repositories); + validate_discovered(&discovered)?; + let previous = request.previous.as_ref(); + if request.path_scope.is_some() || previous.is_some_and(|s| s.plan.path_scope.is_some()) { + return Ok(()); + } + for repository in discovered { + if repository.role == WorkspaceRepositoryRole::Workspace + || previous.is_some_and(|s| !s.states.contains_key(&repository.id)) + { + continue; + } + let root = match super::validate_root(&repository.path) { + Ok(root) => root, + Err(error) if matches!(error.code, ErrorCode::WorkspaceNotFound) => continue, + Err(error) => return Err(error), + }; + if request + .repositories + .iter() + .any(|binding| binding.root == root) + { + continue; + } + request.repositories.push(RepositoryBinding { + id: repository.id, + root, + }); + } + Ok(()) +} + /// Inspects every discovered repository before calculating dependencies and retry scope. pub fn prepare(mut request: PrepareRequest) -> Result { for binding in &mut request.repositories { binding.root = super::validate_root(&binding.root)?; } + bind_nested_repositories(&mut request)?; validate_bindings(&request.repositories)?; let mut states = BTreeMap::new(); for binding in &request.repositories { diff --git a/rust/crates/git/src/workspace_repositories.rs b/rust/crates/git/src/workspace_repositories.rs new file mode 100644 index 00000000..6ce5ab5a --- /dev/null +++ b/rust/crates/git/src/workspace_repositories.rs @@ -0,0 +1,109 @@ +//! Pure projections over the repositories one opened folder holds. +//! +//! `workspace.repositories` lists every repository of an opened folder: the one +//! 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. + +mod change_groups; +mod selection; +#[cfg(test)] +mod tests; + +pub use change_groups::command as change_groups_command; +pub use selection::command as selection_command; + +use crate::contracts::WorkspaceRepositoryRole; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::Deserialize; +use std::collections::HashSet; + +/// Bounds one workspace's repository list; larger lists are host bugs, not user input. +const MAX_REPOSITORIES: usize = 10_000; +/// Matches the repository color assignment bound on one identity. +const MAX_ID_BYTES: usize = 4096; + +fn invalid(message: &str) -> CoreError { + CoreError::new(ErrorCode::InvalidRequest, message) +} + +/// One `workspace.repositories` entry, passed back unchanged. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct DiscoveredRepository { + /// Core slash path of the repository root. + pub(crate) path: String, + /// Identity relative to the opened folder. + pub(crate) id: String, + /// Label the views show. + pub(crate) name: String, + /// How the repository relates to the opened folder. + pub(crate) role: WorkspaceRepositoryRole, +} + +/// Rejects discovery lists `workspace.repositories` cannot produce; see +/// [`validate_identities`]. +pub(crate) fn validate_discovered(repositories: &[DiscoveredRepository]) -> Result<(), CoreError> { + validate_identities(repositories.iter().map(|repository| Identity { + id: &repository.id, + path: &repository.path, + name: &repository.name, + role: repository.role, + })) +} + +/// The identity fields every command checks on a discovery entry. +struct Identity<'a> { + id: &'a str, + path: &'a str, + name: &'a str, + role: WorkspaceRepositoryRole, +} + +/// Rejects lists discovery cannot produce: too many entries, an empty, oversized, +/// absolute, or backslash ID, an empty path or name, a repeated ID or path, or +/// more than one repository that contains the opened folder. +fn validate_identities<'a>( + identities: impl ExactSizeIterator>, +) -> Result<(), CoreError> { + if identities.len() > MAX_REPOSITORIES { + return Err(invalid("Too many workspace repositories")); + } + let mut ids = HashSet::new(); + let mut paths = HashSet::new(); + let mut workspace = false; + for identity in identities { + if !valid_id(identity.id) { + return Err(invalid("Invalid workspace repository ID")); + } + if identity.path.is_empty() || identity.path.contains('\0') { + return Err(invalid("Invalid workspace repository path")); + } + if identity.name.is_empty() { + return Err(invalid("A workspace repository needs a name")); + } + if !ids.insert(identity.id) || !paths.insert(identity.path) { + return Err(invalid("Duplicate workspace repository")); + } + if identity.role == WorkspaceRepositoryRole::Workspace { + if workspace { + return Err(invalid("More than one workspace repository")); + } + workspace = true; + } + } + Ok(()) +} + +/// A repository ID is the `/`-separated discovery identity: never empty, never +/// absolute, and free of backslashes and NUL so it stays portable. +fn valid_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= MAX_ID_BYTES + && !id.starts_with('/') + && !id.contains('\\') + && !id.contains('\0') +} diff --git a/rust/crates/git/src/workspace_repositories/change_groups.rs b/rust/crates/git/src/workspace_repositories/change_groups.rs new file mode 100644 index 00000000..e73a9e43 --- /dev/null +++ b/rust/crates/git/src/workspace_repositories/change_groups.rs @@ -0,0 +1,325 @@ +//! Groups the changes of every workspace repository and plans their staging. +//! +//! The Commit tool window of a workspace with several repositories lists one +//! line for all changes and one group per repository that has changes. Each +//! group's checkbox and the line's checkbox stage everything they can, or +//! unstage everything once it is all staged. A nested repository that is a +//! submodule of a listed ancestor also learns whether that ancestor's recorded +//! reference to it moved, so views can say a commit here still has to be +//! recorded in the parent. + +use super::{invalid, validate_identities, Identity}; +use crate::contracts::WorkspaceRepositoryRole; +use lithe_platform::paths::slash_separated_path; +use lithe_platform::Platform; +use lithe_protocol::CoreError; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +/// Bounds the changes of one request across every repository. +const MAX_CHANGES: usize = 1_000_000; + +/// One `workspace.repositories` entry with the changes `git.status` read for it. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Repository { + path: String, + id: String, + name: String, + role: WorkspaceRepositoryRole, + /// `git.status` changes in the order status returned them. + changes: Vec, +} + +/// The fields of a `git.status` change this command reads. Other fields, such as +/// `status` and `untracked`, are accepted so hosts pass changes through verbatim. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Change { + path: String, + #[serde(default)] + original_path: Option, + staged: bool, + worktree: bool, + can_toggle_staging: bool, + #[serde(default)] + submodule: Option, + #[serde(default)] + untracked_file_count: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Submodule { + commit_changed: bool, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Request { + /// Discovery entries in discovery order. + repositories: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +enum Operation { + Stage, + Unstage, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct Staging { + operation: Operation, + /// Repository-relative paths in change order, both sides of a rename. + paths: Vec, +} + +/// Whether the listed ancestor that records a nested repository as a submodule +/// moved its recorded commit. +#[derive(Debug, Clone, Copy, Serialize)] +#[serde(rename_all = "camelCase")] +enum ParentReference { + /// The ancestor's status lists the gitlink with a new commit. + Moved, + /// The ancestor's status lists the gitlink with only content changes. + Unchanged, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct Group { + id: String, + name: String, + role: WorkspaceRepositoryRole, + /// Files the changes stand for: a summarized untracked directory counts each file. + file_count: usize, + staged_count: usize, + /// Every change that can toggle is staged in full, and there is one. + all_staged: bool, + /// Some change can be staged or unstaged. + toggleable: bool, + /// What the group's checkbox writes, absent when it writes nothing. + #[serde(skip_serializing_if = "Option::is_none")] + staging: Option, + /// Absent when no listed ancestor records the repository as a submodule. + #[serde(skip_serializing_if = "Option::is_none")] + parent_reference: Option, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct RepositoryStaging { + id: String, + paths: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct StageAll { + operation: Operation, + /// Repositories with something to write, in discovery order. + repositories: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct Response { + /// Repositories with changes, in discovery order. + groups: Vec, + file_count: usize, + staged_count: usize, + all_staged: bool, + /// What the line's checkbox writes, absent when it writes nothing. + #[serde(skip_serializing_if = "Option::is_none")] + stage_all: Option, +} + +/// Handles `git.workspaceChangeGroups`. +pub fn command(payload: Value) -> Result { + let request: Request = serde_json::from_value(payload).map_err(|error| { + invalid("Invalid workspace change groups request").with_details(error.to_string()) + })?; + let repositories = request.repositories; + validate_identities(repositories.iter().map(|repository| Identity { + id: &repository.id, + path: &repository.path, + name: &repository.name, + role: repository.role, + }))?; + validate_changes(&repositories)?; + + let parent_references = parent_references(&repositories); + let all_changes = || { + repositories + .iter() + .flat_map(|repository| &repository.changes) + }; + let everything_staged = all_staged(all_changes()); + let stage_all_operation = operation(everything_staged); + let mut stage_all = Vec::new(); + let mut groups = Vec::new(); + for (index, repository) in repositories.iter().enumerate() { + let paths = staging_paths(&repository.changes, stage_all_operation); + if !paths.is_empty() { + stage_all.push(RepositoryStaging { + id: repository.id.clone(), + paths, + }); + } + if repository.changes.is_empty() { + continue; + } + let group_all_staged = all_staged(repository.changes.iter()); + let group_operation = operation(group_all_staged); + let paths = staging_paths(&repository.changes, group_operation); + groups.push(Group { + id: repository.id.clone(), + name: repository.name.clone(), + role: repository.role, + file_count: file_count(repository.changes.iter()), + staged_count: staged_count(repository.changes.iter()), + all_staged: group_all_staged, + toggleable: repository + .changes + .iter() + .any(|change| change.can_toggle_staging), + staging: (!paths.is_empty()).then_some(Staging { + operation: group_operation, + paths, + }), + parent_reference: parent_references[index], + }); + } + Ok(serde_json::to_value(Response { + groups, + file_count: file_count(all_changes()), + staged_count: staged_count(all_changes()), + all_staged: everything_staged, + stage_all: (!stage_all.is_empty()).then_some(StageAll { + operation: stage_all_operation, + repositories: stage_all, + }), + }) + .expect("workspace change groups should encode")) +} + +fn validate_changes(repositories: &[Repository]) -> Result<(), CoreError> { + let count = repositories + .iter() + .map(|repository| repository.changes.len()) + .sum::(); + if count > MAX_CHANGES { + return Err(invalid("Too many workspace changes")); + } + let empty = |path: &str| path.is_empty() || path.contains('\0'); + if repositories + .iter() + .flat_map(|repository| &repository.changes) + .any(|change| empty(&change.path) || change.original_path.as_deref().is_some_and(empty)) + { + return Err(invalid("Invalid workspace change path")); + } + Ok(()) +} + +/// A checkbox that shows everything staged unstages; any other state stages. +fn operation(all_staged: bool) -> Operation { + if all_staged { + Operation::Unstage + } else { + Operation::Stage + } +} + +/// True when every change that can toggle is staged with nothing left in the +/// worktree, and at least one such change exists. +fn all_staged<'a>(changes: impl Iterator) -> bool { + let mut found = false; + for change in changes.filter(|change| change.can_toggle_staging) { + if !change.staged || change.worktree { + return false; + } + found = true; + } + found +} + +fn file_count<'a>(changes: impl Iterator) -> usize { + changes + .map(|change| { + change + .untracked_file_count + .filter(|count| *count > 0) + .unwrap_or(1) + }) + .sum() +} + +fn staged_count<'a>(changes: impl Iterator) -> usize { + changes.filter(|change| change.staged).count() +} + +/// Paths a checkbox writes: unstaging takes every staged change, staging every +/// change with something left to stage. Changes that cannot toggle, such as a +/// gitlink with only uncommitted child content, are never written. +fn staging_paths(changes: &[Change], operation: Operation) -> Vec { + changes + .iter() + .filter(|change| change.can_toggle_staging) + .filter(|change| match operation { + Operation::Unstage => change.staged, + Operation::Stage => !change.staged || change.worktree, + }) + .flat_map(|change| change.original_path.iter().chain([&change.path])) + .cloned() + .collect() +} + +/// For each repository, what its deepest listed ancestor records for it as a +/// submodule. Paths are compared as host paths, so a remote workspace's +/// enclosing repository and its nested ones share ancestry. +fn parent_references(repositories: &[Repository]) -> Vec> { + let paths = repositories + .iter() + .map(|repository| lithe_workspace::remote_path(Path::new(&repository.path))) + .collect::>(); + let by_path = paths + .iter() + .enumerate() + .map(|(index, path)| (path.as_path(), index)) + .collect::>(); + let gitlinks = repositories + .iter() + .map(|repository| { + repository + .changes + .iter() + .filter_map(|change| { + let submodule = change.submodule.as_ref()?; + Some((change.path.trim_end_matches('/'), submodule.commit_changed)) + }) + .collect::>() + }) + .collect::>(); + paths + .iter() + .map(|path| { + let (parent, ancestor) = path + .ancestors() + .skip(1) + .find_map(|ancestor| Some((*by_path.get(ancestor)?, ancestor)))?; + let relative = path.strip_prefix(ancestor).ok()?; + let moved = + gitlinks[parent].get(slash_separated_path(relative, Platform::HOST).as_str())?; + Some(if *moved { + ParentReference::Moved + } else { + ParentReference::Unchanged + }) + }) + .collect() +} diff --git a/rust/crates/git/src/workspace_repositories/selection.rs b/rust/crates/git/src/workspace_repositories/selection.rs new file mode 100644 index 00000000..b8363f5e --- /dev/null +++ b/rust/crates/git/src/workspace_repositories/selection.rs @@ -0,0 +1,83 @@ +//! Chooses the repository 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. + +use super::{invalid, validate_discovered, DiscoveredRepository}; +use crate::contracts::WorkspaceRepositoryRole; +use lithe_protocol::CoreError; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Request { + /// Discovery entries in discovery order. + repositories: Vec, + /// ID the view acted on before, absent when it has not picked one. + #[serde(default)] + selected: Option, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct Response { + /// ID the view acts on, `null` when the workspace has no repository. + 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. + fell_back: bool, + /// Every other ID in discovery order: the groups the view lists for switching. + others: Vec, +} + +/// Handles `git.workspaceRepositorySelection`. +pub fn command(payload: Value) -> Result { + let request: Request = serde_json::from_value(payload).map_err(|error| { + invalid("Invalid workspace repository selection request").with_details(error.to_string()) + })?; + validate_discovered(&request.repositories)?; + if request.selected.as_deref().is_some_and(str::is_empty) { + return Err(invalid( + "A selected workspace repository ID cannot be empty", + )); + } + let listed = |id: &str| { + request + .repositories + .iter() + .any(|repository| repository.id == id) + }; + 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()) + .map(|repository| repository.id.clone()) + .collect(); + Ok(serde_json::to_value(Response { + active, + fell_back, + others, + }) + .expect("workspace repository selection should encode")) +} diff --git a/rust/crates/git/src/workspace_repositories/tests.rs b/rust/crates/git/src/workspace_repositories/tests.rs new file mode 100644 index 00000000..a9081068 --- /dev/null +++ b/rust/crates/git/src/workspace_repositories/tests.rs @@ -0,0 +1,74 @@ +//! Workspace repository projections against their shared fixtures. + +use super::{change_groups_command, selection_command, MAX_REPOSITORIES}; +use lithe_protocol::CoreError; +use serde_json::{json, Value}; + +fn check_fixture(fixture: &str, command: fn(Value) -> Result) { + let fixture: Value = serde_json::from_str(fixture).unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let response = command(case["request"].clone()) + .unwrap_or_else(|error| panic!("{}: {error:?}", case["name"])); + assert_eq!(response, case["response"], "{}", case["name"]); + } + for case in fixture["invalid"].as_array().unwrap() { + let error = + command(case["request"].clone()).expect_err(case["name"].as_str().unwrap_or_default()); + assert_eq!( + serde_json::to_value(error.code).unwrap(), + "invalid_request", + "{}", + case["name"] + ); + } +} + +#[test] +fn selection_matches_the_shared_fixture() { + check_fixture( + include_str!("../../../../fixtures/git/workspace-repository-selection-v1.json"), + selection_command, + ); +} + +#[test] +fn change_groups_match_the_shared_fixture() { + check_fixture( + include_str!("../../../../fixtures/git/workspace-change-groups-v1.json"), + change_groups_command, + ); +} + +#[test] +fn repository_lists_past_the_bound_are_rejected() { + let repositories = (0..=MAX_REPOSITORIES) + .map(|index| { + let id = format!("r{index}"); + json!({"path": format!("/w/{id}"), "id": id, "name": id, "role": "nested"}) + }) + .collect::>(); + assert!(selection_command(json!({ "repositories": repositories })).is_err()); +} + +#[test] +fn ids_past_the_byte_bound_are_rejected() { + let id = "a".repeat(super::MAX_ID_BYTES + 1); + let request = + json!({"repositories": [{"path": "/w/a", "id": id, "name": "a", "role": "nested"}]}); + assert!(selection_command(request).is_err()); +} + +#[test] +fn a_repository_at_a_filesystem_root_still_parents_nested_repositories() { + let response = change_groups_command(json!({"repositories": [ + {"path": "/", "id": "..", "name": "/", "role": "workspace", "changes": [ + {"path": "w/sub", "staged": false, "worktree": true, "canToggleStaging": true, + "submodule": {"commitChanged": false}} + ]}, + {"path": "/w/sub", "id": "sub", "name": "sub", "role": "nested", "changes": [ + {"path": "a", "staged": false, "worktree": true, "canToggleStaging": true} + ]} + ]})) + .unwrap(); + assert_eq!(response["groups"][1]["parentReference"], "unchanged"); +} diff --git a/rust/fixtures/git/workspace-change-groups-v1.json b/rust/fixtures/git/workspace-change-groups-v1.json new file mode 100644 index 00000000..a774f0d2 --- /dev/null +++ b/rust/fixtures/git/workspace-change-groups-v1.json @@ -0,0 +1,782 @@ +{ + "version": 1, + "description": "git.workspaceChangeGroups takes the workspace.repositories entries unchanged, each with the git.status changes read for it. Groups are the repositories with changes in discovery order. A checkbox unstages every staged change that can toggle when all such changes are staged with nothing left in the worktree, and otherwise stages every change that can toggle and is unstaged or still changed in the worktree; paths list both sides of a rename. The workspace line applies one operation, chosen from all repositories, to every repository with something to write. parentReference is present when the deepest listed ancestor's status lists the repository as a gitlink: moved when its recorded commit changed, unchanged otherwise. An untracked or ignored independent repository has none.", + "cases": [ + { + "name": "aFolderWithoutItsOwnRepository", + "request": { + "repositories": [ + { + "path": "/workspace/service-a", + "id": "service-a", + "name": "service-a", + "role": "nested", + "changes": [ + { + "path": "a.go", + "status": "M", + "staged": false, + "worktree": true, + "untracked": false, + "canToggleStaging": true + }, + { + "path": "tmp/", + "status": "??", + "staged": false, + "worktree": true, + "untracked": true, + "canToggleStaging": true, + "untrackedFileCount": 3 + } + ] + }, + { + "path": "/workspace/service-b", + "id": "service-b", + "name": "service-b", + "role": "nested", + "changes": [ + { + "path": "main.go", + "status": "M", + "staged": true, + "worktree": false, + "untracked": false, + "canToggleStaging": true + } + ] + }, + { + "path": "/workspace/libs/core", + "id": "libs/core", + "name": "libs/core", + "role": "nested", + "changes": [] + } + ] + }, + "response": { + "groups": [ + { + "id": "service-a", + "name": "service-a", + "role": "nested", + "fileCount": 4, + "stagedCount": 0, + "allStaged": false, + "toggleable": true, + "staging": { + "operation": "stage", + "paths": [ + "a.go", + "tmp/" + ] + } + }, + { + "id": "service-b", + "name": "service-b", + "role": "nested", + "fileCount": 1, + "stagedCount": 1, + "allStaged": true, + "toggleable": true, + "staging": { + "operation": "unstage", + "paths": [ + "main.go" + ] + } + } + ], + "fileCount": 5, + "stagedCount": 1, + "allStaged": false, + "stageAll": { + "operation": "stage", + "repositories": [ + { + "id": "service-a", + "paths": [ + "a.go", + "tmp/" + ] + } + ] + } + } + }, + { + "name": "submoduleReferencesAndIndependentRepositories", + "request": { + "repositories": [ + { + "path": "/projects/shop", + "id": ".", + "name": "shop", + "role": "workspace", + "changes": [ + { + "path": "modules/payments", + "status": "M", + "staged": false, + "worktree": true, + "untracked": false, + "submodule": { + "commitChanged": false, + "trackedChanges": true, + "untrackedChanges": false + }, + "canToggleStaging": false + }, + { + "path": "vendor/tool", + "status": "M", + "staged": false, + "worktree": true, + "untracked": false, + "submodule": { + "commitChanged": true, + "trackedChanges": false, + "untrackedChanges": false + }, + "canToggleStaging": true + }, + { + "path": "README.md", + "status": "M", + "staged": true, + "worktree": false, + "untracked": false, + "canToggleStaging": true + }, + { + "path": "docs/new.md", + "originalPath": "docs/old.md", + "status": "R", + "staged": true, + "worktree": true, + "untracked": false, + "canToggleStaging": true + } + ] + }, + { + "path": "/projects/shop/extras", + "id": "extras", + "name": "extras", + "role": "nested", + "changes": [ + { + "path": "e.txt", + "status": "??", + "staged": false, + "worktree": true, + "untracked": true, + "canToggleStaging": true + } + ] + }, + { + "path": "/projects/shop/modules/payments", + "id": "modules/payments", + "name": "modules/payments", + "role": "nested", + "changes": [ + { + "path": "pay.go", + "status": "M", + "staged": false, + "worktree": true, + "untracked": false, + "canToggleStaging": true + } + ] + }, + { + "path": "/projects/shop/vendor/tool", + "id": "vendor/tool", + "name": "vendor/tool", + "role": "nested", + "changes": [ + { + "path": "x.c", + "status": "M", + "staged": true, + "worktree": false, + "untracked": false, + "canToggleStaging": true + } + ] + } + ] + }, + "response": { + "groups": [ + { + "id": ".", + "name": "shop", + "role": "workspace", + "fileCount": 4, + "stagedCount": 2, + "allStaged": false, + "toggleable": true, + "staging": { + "operation": "stage", + "paths": [ + "vendor/tool", + "docs/old.md", + "docs/new.md" + ] + } + }, + { + "id": "extras", + "name": "extras", + "role": "nested", + "fileCount": 1, + "stagedCount": 0, + "allStaged": false, + "toggleable": true, + "staging": { + "operation": "stage", + "paths": [ + "e.txt" + ] + } + }, + { + "id": "modules/payments", + "name": "modules/payments", + "role": "nested", + "fileCount": 1, + "stagedCount": 0, + "allStaged": false, + "toggleable": true, + "staging": { + "operation": "stage", + "paths": [ + "pay.go" + ] + }, + "parentReference": "unchanged" + }, + { + "id": "vendor/tool", + "name": "vendor/tool", + "role": "nested", + "fileCount": 1, + "stagedCount": 1, + "allStaged": true, + "toggleable": true, + "staging": { + "operation": "unstage", + "paths": [ + "x.c" + ] + }, + "parentReference": "moved" + } + ], + "fileCount": 7, + "stagedCount": 3, + "allStaged": false, + "stageAll": { + "operation": "stage", + "repositories": [ + { + "id": ".", + "paths": [ + "vendor/tool", + "docs/old.md", + "docs/new.md" + ] + }, + { + "id": "extras", + "paths": [ + "e.txt" + ] + }, + { + "id": "modules/payments", + "paths": [ + "pay.go" + ] + } + ] + } + } + }, + { + "name": "everythingStagedUnstagesEveryRepository", + "request": { + "repositories": [ + { + "path": "/w", + "id": ".", + "name": "w", + "role": "workspace", + "changes": [ + { + "path": "sub", + "status": "M", + "staged": true, + "worktree": false, + "untracked": false, + "submodule": { + "commitChanged": true, + "trackedChanges": false, + "untrackedChanges": false + }, + "canToggleStaging": true + }, + { + "path": "a.txt", + "status": "M", + "staged": true, + "worktree": false, + "untracked": false, + "canToggleStaging": true + } + ] + }, + { + "path": "/w/sub", + "id": "sub", + "name": "sub", + "role": "nested", + "changes": [ + { + "path": "inner", + "status": "M", + "staged": false, + "worktree": true, + "untracked": false, + "submodule": { + "commitChanged": false, + "trackedChanges": true, + "untrackedChanges": false + }, + "canToggleStaging": false + }, + { + "path": "s.txt", + "status": "M", + "staged": true, + "worktree": false, + "untracked": false, + "canToggleStaging": true + } + ] + }, + { + "path": "/w/sub/inner", + "id": "sub/inner", + "name": "sub/inner", + "role": "nested", + "changes": [ + { + "path": "i.txt", + "status": "M", + "staged": true, + "worktree": false, + "untracked": false, + "canToggleStaging": true + } + ] + } + ] + }, + "response": { + "groups": [ + { + "id": ".", + "name": "w", + "role": "workspace", + "fileCount": 2, + "stagedCount": 2, + "allStaged": true, + "toggleable": true, + "staging": { + "operation": "unstage", + "paths": [ + "sub", + "a.txt" + ] + } + }, + { + "id": "sub", + "name": "sub", + "role": "nested", + "fileCount": 2, + "stagedCount": 1, + "allStaged": true, + "toggleable": true, + "staging": { + "operation": "unstage", + "paths": [ + "s.txt" + ] + }, + "parentReference": "moved" + }, + { + "id": "sub/inner", + "name": "sub/inner", + "role": "nested", + "fileCount": 1, + "stagedCount": 1, + "allStaged": true, + "toggleable": true, + "staging": { + "operation": "unstage", + "paths": [ + "i.txt" + ] + }, + "parentReference": "unchanged" + } + ], + "fileCount": 5, + "stagedCount": 4, + "allStaged": true, + "stageAll": { + "operation": "unstage", + "repositories": [ + { + "id": ".", + "paths": [ + "sub", + "a.txt" + ] + }, + { + "id": "sub", + "paths": [ + "s.txt" + ] + }, + { + "id": "sub/inner", + "paths": [ + "i.txt" + ] + } + ] + } + } + }, + { + "name": "anOpenedSubfolderOfTheContainingRepository", + "request": { + "repositories": [ + { + "path": "/projects/mono", + "id": "../..", + "name": "mono", + "role": "workspace", + "changes": [ + { + "path": "packages/app/vendor/lib", + "status": "M", + "staged": false, + "worktree": true, + "untracked": false, + "submodule": { + "commitChanged": true, + "trackedChanges": false, + "untrackedChanges": false + }, + "canToggleStaging": true + } + ] + }, + { + "path": "/projects/mono/packages/app/vendor/lib", + "id": "vendor/lib", + "name": "vendor/lib", + "role": "nested", + "changes": [ + { + "path": "l.c", + "status": "M", + "staged": false, + "worktree": true, + "untracked": false, + "canToggleStaging": true + } + ] + } + ] + }, + "response": { + "groups": [ + { + "id": "../..", + "name": "mono", + "role": "workspace", + "fileCount": 1, + "stagedCount": 0, + "allStaged": false, + "toggleable": true, + "staging": { + "operation": "stage", + "paths": [ + "packages/app/vendor/lib" + ] + } + }, + { + "id": "vendor/lib", + "name": "vendor/lib", + "role": "nested", + "fileCount": 1, + "stagedCount": 0, + "allStaged": false, + "toggleable": true, + "staging": { + "operation": "stage", + "paths": [ + "l.c" + ] + }, + "parentReference": "moved" + } + ], + "fileCount": 2, + "stagedCount": 0, + "allStaged": false, + "stageAll": { + "operation": "stage", + "repositories": [ + { + "id": "../..", + "paths": [ + "packages/app/vendor/lib" + ] + }, + { + "id": "vendor/lib", + "paths": [ + "l.c" + ] + } + ] + } + } + }, + { + "name": "onlyChildContentChangesWriteNothing", + "request": { + "repositories": [ + { + "path": "/w", + "id": ".", + "name": "w", + "role": "workspace", + "changes": [ + { + "path": "sub", + "status": "M", + "staged": false, + "worktree": true, + "untracked": false, + "submodule": { + "commitChanged": false, + "trackedChanges": false, + "untrackedChanges": true + }, + "canToggleStaging": false + } + ] + }, + { + "path": "/w/sub", + "id": "sub", + "name": "sub", + "role": "nested", + "changes": [] + } + ] + }, + "response": { + "groups": [ + { + "id": ".", + "name": "w", + "role": "workspace", + "fileCount": 1, + "stagedCount": 0, + "allStaged": false, + "toggleable": false + } + ], + "fileCount": 1, + "stagedCount": 0, + "allStaged": false + } + }, + { + "name": "noRepositories", + "request": { + "repositories": [] + }, + "response": { + "groups": [], + "fileCount": 0, + "stagedCount": 0, + "allStaged": false + } + } + ], + "invalid": [ + { + "name": "duplicateId", + "request": { + "repositories": [ + { + "path": "/w/a", + "id": "a", + "name": "a", + "role": "nested", + "changes": [] + }, + { + "path": "/w/b", + "id": "a", + "name": "a", + "role": "nested", + "changes": [] + } + ] + } + }, + { + "name": "twoWorkspaceRepositories", + "request": { + "repositories": [ + { + "path": "/w", + "id": ".", + "name": "w", + "role": "workspace", + "changes": [] + }, + { + "path": "/", + "id": "..", + "name": "/", + "role": "workspace", + "changes": [] + } + ] + } + }, + { + "name": "missingChanges", + "request": { + "repositories": [ + { + "path": "/w", + "id": ".", + "name": "w", + "role": "workspace" + } + ] + } + }, + { + "name": "unknownRepositoryField", + "request": { + "repositories": [ + { + "path": "/w", + "id": ".", + "name": "w", + "role": "workspace", + "changes": [], + "branch": "main" + } + ] + } + }, + { + "name": "changeWithoutStagingState", + "request": { + "repositories": [ + { + "path": "/w", + "id": ".", + "name": "w", + "role": "workspace", + "changes": [ + { + "path": "a", + "status": "M", + "worktree": true, + "canToggleStaging": true + } + ] + } + ] + } + }, + { + "name": "emptyChangePath", + "request": { + "repositories": [ + { + "path": "/w", + "id": ".", + "name": "w", + "role": "workspace", + "changes": [ + { + "path": "", + "status": "M", + "staged": false, + "worktree": true, + "untracked": false, + "canToggleStaging": true + } + ] + } + ] + } + }, + { + "name": "emptyOriginalPath", + "request": { + "repositories": [ + { + "path": "/w", + "id": ".", + "name": "w", + "role": "workspace", + "changes": [ + { + "path": "a", + "status": "M", + "staged": true, + "worktree": false, + "untracked": false, + "canToggleStaging": true, + "originalPath": "" + } + ] + } + ] + } + }, + { + "name": "unknownField", + "request": { + "repositories": [], + "selected": "." + } + } + ] +} diff --git a/rust/fixtures/git/workspace-repository-selection-v1.json b/rust/fixtures/git/workspace-repository-selection-v1.json new file mode 100644 index 00000000..ee961033 --- /dev/null +++ b/rust/fixtures/git/workspace-repository-selection-v1.json @@ -0,0 +1,117 @@ +{ + "version": 1, + "description": "git.workspaceRepositorySelection takes the workspace.repositories entries unchanged and the ID a view picked before. The pick stays while it is listed; otherwise the view acts on the repository with role workspace, then on the first listed repository, and on none when nothing is listed. fellBack is true only when a pick was given and is no longer listed. others lists every other ID in discovery order.", + "cases": [ + { + "name": "noPickActsOnTheContainingRepository", + "request": { + "repositories": [ + {"path": "/projects/shop", "id": ".", "name": "shop", "role": "workspace"}, + {"path": "/projects/shop/modules/payments", "id": "modules/payments", "name": "modules/payments", "role": "nested"} + ] + }, + "response": {"active": ".", "fellBack": false, "others": ["modules/payments"]} + }, + { + "name": "aListedPickStays", + "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"} + ], + "selected": "modules/payments" + }, + "response": {"active": "modules/payments", "fellBack": false, "others": [".", "tools"]} + }, + { + "name": "aRemovedPickFallsBackToTheContainingRepository", + "request": { + "repositories": [ + {"path": "/projects/mono", "id": "../..", "name": "mono", "role": "workspace"}, + {"path": "/projects/mono/packages/app/vendor/lib", "id": "vendor/lib", "name": "vendor/lib", "role": "nested"} + ], + "selected": "vendor/old" + }, + "response": {"active": "../..", "fellBack": true, "others": ["vendor/lib"]} + }, + { + "name": "aFolderWithoutItsOwnRepositoryActsOnTheFirstNestedOne", + "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"} + ] + }, + "response": {"active": "service-a", "fellBack": false, "others": ["service-b"]} + }, + { + "name": "aRemovedPickInAFolderWithoutItsOwnRepository", + "request": { + "repositories": [ + {"path": "/workspace/service-b", "id": "service-b", "name": "service-b", "role": "nested"} + ], + "selected": "service-a" + }, + "response": {"active": "service-b", "fellBack": true, "others": []} + }, + { + "name": "noRepositories", + "request": {"repositories": [], "selected": "service-a"}, + "response": {"active": null, "fellBack": true, "others": []} + } + ], + "invalid": [ + { + "name": "duplicateId", + "request": { + "repositories": [ + {"path": "/w/a", "id": "a", "name": "a", "role": "nested"}, + {"path": "/w/b", "id": "a", "name": "a", "role": "nested"} + ] + } + }, + { + "name": "duplicatePath", + "request": { + "repositories": [ + {"path": "/w/a", "id": "a", "name": "a", "role": "nested"}, + {"path": "/w/a", "id": "b", "name": "b", "role": "nested"} + ] + } + }, + { + "name": "twoWorkspaceRepositories", + "request": { + "repositories": [ + {"path": "/w", "id": ".", "name": "w", "role": "workspace"}, + {"path": "/", "id": "..", "name": "/", "role": "workspace"} + ] + } + }, + { + "name": "absoluteId", + "request": {"repositories": [{"path": "/w/a", "id": "/w/a", "name": "a", "role": "nested"}]} + }, + { + "name": "backslashId", + "request": {"repositories": [{"path": "C:/w/a", "id": "a\\b", "name": "a\\b", "role": "nested"}]} + }, + { + "name": "emptyName", + "request": {"repositories": [{"path": "/w/a", "id": "a", "name": "", "role": "nested"}]} + }, + { + "name": "emptyPick", + "request": {"repositories": [], "selected": ""} + }, + { + "name": "unknownRole", + "request": {"repositories": [{"path": "/w/a", "id": "a", "name": "a", "role": "submodule"}]} + }, + { + "name": "unknownField", + "request": {"repositories": [], "active": "a"} + } + ] +} diff --git a/rust/fixtures/workspace/repositories-v1.json b/rust/fixtures/workspace/repositories-v1.json index 6f844397..bc94c306 100644 --- a/rust/fixtures/workspace/repositories-v1.json +++ b/rust/fixtures/workspace/repositories-v1.json @@ -1,16 +1,79 @@ { - "command": "workspace.repositories", - "payload": { - "root": "/workspace" - }, - "response": { - "repositories": [ - { - "path": "/workspace/service-a" + "cases": [ + { + "name": "opened folder holds independent checkouts and is no repository", + "command": "workspace.repositories", + "payload": { + "root": "/workspace" }, - { - "path": "/workspace/service-b" + "response": { + "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/libs/core", + "id": "libs/core", + "name": "libs/core", + "role": "nested" + } + ] } - ] - } + }, + { + "name": "opened folder is the workspace repository", + "command": "workspace.repositories", + "payload": { + "root": "/projects/shop" + }, + "response": { + "repositories": [ + { + "path": "/projects/shop", + "id": ".", + "name": "shop", + "role": "workspace" + }, + { + "path": "/projects/shop/modules/payments", + "id": "modules/payments", + "name": "modules/payments", + "role": "nested" + } + ] + } + }, + { + "name": "opened folder inside an enclosing checkout", + "command": "workspace.repositories", + "payload": { + "root": "/projects/mono/packages/app" + }, + "response": { + "repositories": [ + { + "path": "/projects/mono", + "id": "../..", + "name": "mono", + "role": "workspace" + }, + { + "path": "/projects/mono/packages/app/vendor/lib", + "id": "vendor/lib", + "name": "vendor/lib", + "role": "nested" + } + ] + } + } + ] }