Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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: [{
Expand Down
8 changes: 8 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down Expand Up @@ -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)),
Expand Down
8 changes: 8 additions & 0 deletions rust/crates/core/src/runtime/dispatcher/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,14 @@ pub(super) fn dispatch(command: GitCommand, id: Option<String>, 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)
Expand Down
23 changes: 19 additions & 4 deletions rust/crates/core/src/tests/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
])
);

Expand Down Expand Up @@ -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");
Expand Down
60 changes: 59 additions & 1 deletion rust/crates/core/src/tests/git_repository_discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
}])
);
}

Expand All @@ -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))
);
}
63 changes: 63 additions & 0 deletions rust/crates/core/src/tests/git_workspace_commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
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}");
}
Loading
Loading