Skip to content

Commit e78eeab

Browse files
committed
feat(git): workspace repository identities, selection and change groups in Core
A folder without its own .git that holds several independent repositories is opened as one project (1lck/Lithe-IDEA#2013). The desktop decided in Go which repository a view acts on, how the repositories' changes group and stage, and whether a parent still has to record a nested commit, and it assumed the opened folder is always a repository. Core now owns those rules so every host shares them. - workspace.repositories entries carry id (relative to the opened folder, `/`-separated, `..` for an enclosing repository), name and role (workspace or nested). A folder outside every repository has no workspace entry. Remote workspaces compute IDs from host paths. - git.workspaceRepositorySelection takes the discovery entries and the previous pick, and answers the repository to act on, whether it fell back, and the others in discovery order. - git.workspaceChangeGroups takes the discovery entries with their git.status changes, and answers per-repository groups, counts, the checkbox states, the paths each checkbox stages or unstages, and whether the deepest listed ancestor's gitlink to a nested repository moved. An untracked or ignored independent repository gets no parent hint. - git.workspaceCommitPrepare accepts workspaceRepositories and binds every nested repository the host did not bind, except for path-scoped commits and retries, so the reviewed plan never gains repositories between attempts. Fixtures: rust/fixtures/git/workspace-repository-selection-v1.json, rust/fixtures/git/workspace-change-groups-v1.json, and the extended rust/fixtures/workspace/repositories-v1.json. Refs 1lck/Lithe-IDEA#2013
1 parent ad148ec commit e78eeab

20 files changed

Lines changed: 2162 additions & 26 deletions

‎rust/contracts/rust-core-api.md‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -770,6 +770,8 @@ or removing a command fails until the table changes in the same commit.
770770
| `git.historyLocate` | Append bounded history pages until one commit is found and report the budget, window cursor, and exhaustion |
771771
| `git.branchNamePreview` | Clean and validate a new branch name against already loaded references without running Git |
772772
| `git.repositoryColorAssignments` | Assign color slots to a bounded page of ordered repository identities |
773+
| `git.workspaceRepositorySelection` | Choose the workspace repository a view acts on and the others it lists for switching, from discovery entries and the previous pick |
774+
| `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 |
773775
| `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 |
774776
| `git.historyWindow` | Plan a history refresh window, page merge, and selection retention over commit identities |
775777
| `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
898900
errors remain visible. In particular, Windows may reject an over-MAX_PATH Git
899901
working directory at process creation even when filesystem lookup succeeds;
900902
this is reported as `process_start_failed`, not a missing repository. Shared examples live in `rust/fixtures/git/windows-paths.json`.
903+
Each entry also carries the portable identity clients key repositories by:
904+
`id` is the root relative to the opened folder with `/` separators — `.` for the
905+
folder itself, `service-a` or `libs/core` below it, and one `..` per level for an
906+
enclosing repository (`../..` when the folder is `packages/app` of a checkout).
907+
It is the ID that `git.workspaceRepositorySelection`, `git.workspaceChangeGroups`,
908+
`git.workspaceCommitPrepare` and `git.repositoryColorAssignments` take; a remote
909+
workspace computes it from host paths, so it is the same as for a local folder.
910+
`role` is `workspace` for the repository that contains the opened folder (the
911+
folder itself or an enclosing checkout), at most one entry and always first, and
912+
`nested` for every repository below the folder. An opened folder outside every
913+
repository — a parent folder that only holds independent checkouts — has no
914+
`workspace` entry, and clients must not assume one exists. `name` is the label
915+
views show: the root folder's name for the workspace repository and the `id` for
916+
a nested one, so same-named folders in different places stay distinguishable. It
917+
is a file name, never translated. See `rust/fixtures/workspace/repositories-v1.json`.
901918
Core treats both
902919
`.git` directories and `.git` files as repository markers, but a marker only
903920
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
19611978
stale results, and never recompute the slots per row. Color palettes remain native
19621979
presentation. See `rust/fixtures/git/repository-colors-v1.json`.
19631980

1981+
`git.workspaceRepositorySelection` is pure. It accepts `{ repositories,
1982+
selected? }`, where `repositories` are the `workspace.repositories` entries
1983+
`{ path, id, name, role }` passed back unchanged and in discovery order, and
1984+
`selected` is the ID the view acted on before. The response is
1985+
`{ active, fellBack, others }`: `active` is `selected` while it is still listed,
1986+
otherwise the entry with role `workspace`, otherwise the first entry, and `null`
1987+
for an empty list; `fellBack` is `true` only when `selected` was given and is no
1988+
longer listed, so the view drops state that belonged to it such as an open
1989+
history cursor or a reference filter; `others` are the remaining IDs in
1990+
discovery order, the groups the branch popup and the Git Log list for switching.
1991+
The list holds at most 10,000 entries. An ID that is empty, longer than 4,096
1992+
bytes, starts with `/`, or contains `\` or NUL, an empty path or name, a repeated
1993+
ID or path, more than one `workspace` role, an unknown role, an empty `selected`,
1994+
or an unknown field fails with `invalid_request`. See
1995+
`rust/fixtures/git/workspace-repository-selection-v1.json`.
1996+
1997+
`git.workspaceChangeGroups` is pure and validates `repositories` the same way;
1998+
each entry also carries `changes`, the `git.status` changes read for that
1999+
repository, passed through unchanged. Core reads `path`, `originalPath`,
2000+
`staged`, `worktree`, `canToggleStaging`, `submodule.commitChanged`, and
2001+
`untrackedFileCount`; other change fields are accepted and ignored. At most
2002+
1,000,000 changes are accepted across the request, and an empty change path or
2003+
original path fails with `invalid_request`. The response is `{ groups,
2004+
fileCount, stagedCount, allStaged, stageAll? }`. `groups` lists the repositories
2005+
that have changes in discovery order, each `{ id, name, role, fileCount,
2006+
stagedCount, allStaged, toggleable, staging?, parentReference? }`. `fileCount`
2007+
counts each file of a summarized untracked directory. `allStaged` is `true` when
2008+
every change with `canToggleStaging` is staged with nothing left in the
2009+
worktree and at least one exists. `staging` is `{ operation, paths }` and is
2010+
absent when the checkbox writes nothing: `unstage` takes the staged changes that
2011+
can toggle when `allStaged`, and `stage` otherwise takes the changes that can
2012+
toggle and are unstaged or still changed in the worktree. Paths are
2013+
repository-relative in change order, with both sides of a rename. `stageAll`
2014+
is the workspace line's checkbox: one `operation`, chosen from `allStaged`
2015+
across every repository, applied to every repository with something to write,
2016+
as `{ operation, repositories: [{ id, paths }] }`. `parentReference` is present
2017+
when the deepest listed ancestor's status lists the repository as a gitlink:
2018+
`moved` when its recorded commit changed and `unchanged` when only the child's
2019+
content did. An independent repository the ancestor tracks as untracked or
2020+
ignores has none. Ancestry is compared on host paths, so a remote workspace's
2021+
enclosing repository and its nested ones still relate. Views own folding,
2022+
drawing, and running the staging writes. See
2023+
`rust/fixtures/git/workspace-change-groups-v1.json`.
2024+
19642025
`git.branchNamePreview` is pure: it never starts Git and only reads the
19652026
reference facts the host already loaded. It accepts `rawName` (at most 1,024
19662027
characters; longer input is `invalid_request`), `requireName` (`true` on submit,
@@ -4923,6 +4984,16 @@ finds real gitlink relationships, includes clean parents when requested, orders
49234984
children first, and adds push-only child work where needed. Cycles fail closed.
49244985
A changed reviewed plan must be displayed and confirmed again before any step.
49254986

4987+
Optional `workspaceRepositories` takes the opened folder's `workspace.repositories`
4988+
entries unchanged, validated as `git.workspaceRepositorySelection` validates them,
4989+
and binds every `nested` entry whose root `repositories` does not already bind, in
4990+
discovery order, under its discovery `id`. A commit of the workspace therefore also
4991+
commits the repositories nested in it, so the host binds only what it chose itself
4992+
(usually the `workspace` entry, which Core never adds). An entry whose root no
4993+
longer exists is skipped. Nothing is added while a `pathScope` is given or the
4994+
`previous` plan had one, and a retry adds only IDs the `previous` session already
4995+
held, so the reviewed plan never gains repositories between attempts.
4996+
49264997
When `push` is set, Core also checks whether any repository's branch tracks a
49274998
differently named remote branch (a `divergent` push destination, see
49284999
`git.pushPreview`). Those repositories are returned as `pushTargetQuestions: [{

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -847,6 +847,10 @@ pub enum GitCommand {
847847
BranchNamePreview,
848848
/// Assigns palette slots to a page of ordered repository identities.
849849
RepositoryColorAssignments,
850+
/// Chooses the workspace repository a view acts on (`git.workspaceRepositorySelection`).
851+
WorkspaceRepositorySelection,
852+
/// Groups workspace repositories' changes and plans their staging (`git.workspaceChangeGroups`).
853+
WorkspaceChangeGroups,
850854
/// Plans a branch Update or Pull from collected facts (`git.updatePlan`).
851855
UpdatePlan,
852856
/// Plans history refresh windows, page merges, and selection retention (`git.historyWindow`).
@@ -1468,6 +1472,10 @@ impl CoreCommand {
14681472
"git.repositoryColorAssignments" => {
14691473
Some(Self::Git(GitCommand::RepositoryColorAssignments))
14701474
}
1475+
"git.workspaceRepositorySelection" => {
1476+
Some(Self::Git(GitCommand::WorkspaceRepositorySelection))
1477+
}
1478+
"git.workspaceChangeGroups" => Some(Self::Git(GitCommand::WorkspaceChangeGroups)),
14711479
"git.updatePlan" => Some(Self::Git(GitCommand::UpdatePlan)),
14721480
"git.historyWindow" => Some(Self::Git(GitCommand::HistoryWindow)),
14731481
"git.graphProjection" => Some(Self::Git(GitCommand::GraphProjection)),

‎rust/crates/core/src/runtime/dispatcher/git.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,14 @@ pub(super) fn dispatch(command: GitCommand, id: Option<String>, payload: Value)
419419
GitCommand::RepositoryColorAssignments => {
420420
plugin_response(id, payload, lithe_git::repository_color_assignments_command)
421421
}
422+
GitCommand::WorkspaceRepositorySelection => plugin_response(
423+
id,
424+
payload,
425+
lithe_git::workspace_repository_selection_command,
426+
),
427+
GitCommand::WorkspaceChangeGroups => {
428+
plugin_response(id, payload, lithe_git::workspace_change_groups_command)
429+
}
422430
GitCommand::UpdatePlan => plugin_response(id, payload, lithe_git::update_plan_command),
423431
GitCommand::HistoryWindow => {
424432
plugin_response(id, payload, lithe_git::history_window_command)

‎rust/crates/core/src/tests/git.rs‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -327,12 +327,24 @@ fn workspace_repositories_discovers_multiple_child_repositories() {
327327
.expect("workspace repositories response should be JSON");
328328

329329
assert_eq!(response["ok"], true, "{response:?}");
330+
// The opened folder is no repository itself, so every entry is nested and keyed
331+
// by its path below the folder.
332+
let nested_id = format!("service-a/vendor{}", "/d".repeat(40));
330333
assert_eq!(
331334
response["data"]["repositories"],
332335
serde_json::json!([
333-
{ "path": reported_repository_path(&first) },
334-
{ "path": reported_repository_path(&second) },
335-
{ "path": reported_repository_path(&nested) }
336+
{
337+
"path": reported_repository_path(&first),
338+
"id": "service-a", "name": "service-a", "role": "nested"
339+
},
340+
{
341+
"path": reported_repository_path(&second),
342+
"id": "service-b", "name": "service-b", "role": "nested"
343+
},
344+
{
345+
"path": reported_repository_path(&nested),
346+
"id": nested_id, "name": nested_id, "role": "nested"
347+
}
336348
])
337349
);
338350

@@ -374,7 +386,10 @@ fn workspace_repositories_skips_dangling_gitfile_pointers() {
374386
assert_eq!(response["ok"], true, "{response:?}");
375387
assert_eq!(
376388
response["data"]["repositories"],
377-
serde_json::json!([{ "path": reported_repository_path(&healthy) }])
389+
serde_json::json!([{
390+
"path": reported_repository_path(&healthy),
391+
"id": "healthy", "name": "healthy", "role": "nested"
392+
}])
378393
);
379394

380395
fs::remove_dir_all(root).expect("temporary workspace should be removable");

‎rust/crates/core/src/tests/git_repository_discovery.rs‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,23 @@ fn canonical(root: &Path) -> String {
6666
.replace('\\', "/")
6767
}
6868

69+
fn folder_name(root: &Path) -> String {
70+
canonical(root).rsplit('/').next().unwrap().to_owned()
71+
}
72+
73+
/// Role, ID and name of every discovered repository, in discovery order.
74+
fn identities(root: &Path) -> Vec<(String, String, String)> {
75+
data("workspace.repositories", json!({"root": root}))["repositories"]
76+
.as_array()
77+
.unwrap()
78+
.iter()
79+
.map(|entry| {
80+
let field = |name: &str| entry[name].as_str().unwrap().to_owned();
81+
(field("role"), field("id"), field("name"))
82+
})
83+
.collect()
84+
}
85+
6986
fn fixture() -> Value {
7087
serde_json::from_str(include_str!(
7188
"../../../../fixtures/workspace/repository-visibility-v1.json"
@@ -172,7 +189,10 @@ fn discovery_respects_explicit_depth_limits() {
172189
"workspace.repositories",
173190
json!({"root": root, "maxDepth": 0})
174191
)["repositories"],
175-
json!([{"path": canonical(&root)}])
192+
json!([{
193+
"path": canonical(&root), "id": ".",
194+
"name": folder_name(&root), "role": "workspace"
195+
}])
176196
);
177197
}
178198

@@ -187,3 +207,41 @@ fn discovery_does_not_follow_directory_symlinks() {
187207
std::os::unix::fs::symlink(&root, root.join("cycle")).unwrap();
188208
assert_eq!(discover(&root), vec![canonical(&root)]);
189209
}
210+
211+
#[test]
212+
fn discovery_keys_repositories_by_their_place_relative_to_the_opened_folder() {
213+
let owned =
214+
|role: &str, id: &str, name: &str| (role.to_owned(), id.to_owned(), name.to_owned());
215+
let workspace = Workspace::new();
216+
// A folder outside every repository has no workspace repository; each nested
217+
// one is keyed and named by its path below the folder.
218+
workspace.initialize("backend");
219+
workspace.initialize("frontend/web");
220+
assert_eq!(
221+
identities(&workspace.0),
222+
vec![
223+
owned("nested", "backend", "backend"),
224+
owned("nested", "frontend/web", "frontend/web"),
225+
]
226+
);
227+
228+
// A folder inside a repository reaches the enclosing repository through `..`
229+
// segments, and that repository keeps its own folder name.
230+
let enclosing = workspace.initialize("mono");
231+
let opened = enclosing.join("packages").join("app");
232+
fs::create_dir_all(&opened).unwrap();
233+
workspace.initialize("mono/packages/app/vendor/lib");
234+
assert_eq!(
235+
identities(&opened),
236+
vec![
237+
owned("workspace", "../..", &folder_name(&enclosing)),
238+
owned("nested", "vendor/lib", "vendor/lib"),
239+
]
240+
);
241+
242+
// The repository at the opened folder is the workspace repository with ID `.`.
243+
assert_eq!(
244+
identities(&enclosing)[0],
245+
owned("workspace", ".", &folder_name(&enclosing))
246+
);
247+
}

‎rust/crates/core/src/tests/git_workspace_commit.rs‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1152,3 +1152,66 @@ fn git_workspace_changelist_guard_checks_newly_staged_directory_members_and_over
11521152
);
11531153
assert!(repo.0.join("dir/new.txt").exists());
11541154
}
1155+
1156+
fn bound_ids(prepared: &Value) -> Vec<String> {
1157+
prepared["session"]["plan"]["repositories"]
1158+
.as_array()
1159+
.unwrap()
1160+
.iter()
1161+
.map(|binding| binding["id"].as_str().unwrap().to_owned())
1162+
.collect()
1163+
}
1164+
1165+
#[test]
1166+
fn git_workspace_commit_binds_discovered_nested_repositories_outside_scopes_and_retries() {
1167+
let repo = repository("workspace-commit-discovered");
1168+
let child = repo.0.join("libs/B");
1169+
init(&child);
1170+
let gone = repo.0.join("gone");
1171+
init(&gone);
1172+
staged_file(&repo.0, "parent.txt", "one");
1173+
staged_file(&child, "child.txt", "one");
1174+
let discovered = request(&repo.0, "workspace.repositories", json!({}));
1175+
assert_eq!(discovered["ok"], true, "{discovered}");
1176+
let discovered = discovered["data"]["repositories"].clone();
1177+
fs::remove_dir_all(&gone).unwrap();
1178+
let own = json!([{"id": ".", "root": repo.0}]);
1179+
1180+
// Core binds the nested entries; the removed one is skipped, and the workspace
1181+
// entry is the host's own binding.
1182+
let prepared = prepare_workspace_with(
1183+
&repo.0,
1184+
&[(".", &repo.0)],
1185+
json!({"workspaceRepositories": discovered}),
1186+
);
1187+
assert_eq!(bound_ids(&prepared), [".", "libs/B"], "{prepared}");
1188+
1189+
// A path-scoped commit acts only on the repositories the host bound.
1190+
let scoped = prepare_workspace_with(
1191+
&repo.0,
1192+
&[(".", &repo.0)],
1193+
json!({"workspaceRepositories": discovered,
1194+
"pathScope": {"include": true, "paths": {".": ["parent.txt"]}}}),
1195+
);
1196+
assert_eq!(bound_ids(&scoped), ["."], "{scoped}");
1197+
1198+
// A retry keeps the previous plan's repositories instead of gaining new ones.
1199+
let first = prepare_workspace_with(&repo.0, &[(".", &repo.0)], json!({}));
1200+
let mut retry = first["session"]["plan"].clone();
1201+
retry["repositories"] = own;
1202+
retry["previous"] = first["session"].clone();
1203+
retry["workspaceRepositories"] = discovered.clone();
1204+
let retried = request(&repo.0, "git.workspaceCommitPrepare", retry);
1205+
assert_eq!(retried["ok"], true, "{retried}");
1206+
assert_eq!(bound_ids(&retried["data"]), ["."], "{retried}");
1207+
1208+
let mut invalid = discovered;
1209+
invalid[0]["id"] = json!("/absolute");
1210+
let rejected = request(
1211+
&repo.0,
1212+
"git.workspaceCommitPrepare",
1213+
json!({"repositories": [{"id": ".", "root": repo.0}], "message": "batch",
1214+
"includeParentReferences": false, "workspaceRepositories": invalid}),
1215+
);
1216+
assert_eq!(rejected["error"]["code"], "invalid_request", "{rejected}");
1217+
}

0 commit comments

Comments
 (0)