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
31 changes: 31 additions & 0 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,7 @@ or removing a command fails until the table changes in the same commit.
| `git.changedFileGroups` | Group the changed files of a commit, stash or shelf by folder, folders and files in natural order |
| `git.worktreeCreationPreview` | Derive the worktree creation dialog's reference choices, checked branch name, suggested destination and readiness without running Git |
| `git.pushPreview` | Resolve a local branch push destination and the bounded commits not present on that remote base |
| `git.workspacePushPreview` | Review pushing the checked-out branch of every bound repository, in push order |
| `git.commit` | Return one structured commit by revision with its full message body |
| `git.commitFiles` | Return files changed by one commit |
| `git.comparison` | Return files changed between a reference and the working tree |
Expand Down Expand Up @@ -1525,6 +1526,36 @@ so a repository change after validation cannot add unreviewed commits to the
operation. Because Git cannot infer an upstream from an OID source, Core
explicitly configures the reviewed local branch after a successful first push.

`git.workspacePushPreview` reviews pushing several repositories at once, like
IntelliJ IDEA's Push dialog, which lists every repository of a project with what
it would push. It accepts `repositories: [{ id, root }]` (the bindings
`git.workspaceCommitPrepare` takes, at most 10,000, IDs unique), an optional
`limit` (default 100) and `pushTags` applied to every preview, and optional
`pushTargets: { <repository-id>: "publish" | "upstream" }` for divergent
upstreams. It returns `{ repositories: [{ id, state, branch?, preview?,
needsTarget, records, detail? }] }` with one entry per binding. `state` is
`ready` (commits to send, or the remote branch does not exist yet), `upToDate`,
`noRemote` (no remote configured), `emptyRepository` (the branch has no commit),
`detachedHead`, or `failed` (the root is not a readable repository, or Git could
not resolve the destination; `detail` carries Core's message and Git's output).
`branch` is the checked-out branch's short name, absent when HEAD is detached or
the repository could not be read. `preview` is present for `ready` and
`upToDate` and is exactly the `git.pushPreview` of that branch with the same
`limit`, `pushTags` and `pushTarget`; a client pushes a repository with `git.write`
`push`, that preview as `expectedPush`, the same `pushTags` and `pushTarget`, and
`checkSubmodules: true`. `needsTarget` is true when the upstream has a different
name (`targetKind: divergent`) and `pushTargets` gave that repository no
destination; such a push is refused until the client previews again with one.
The list is in push order: a repository comes after every listed repository it
records as a gitlink, otherwise in request order, using the relations
`git.workspaceCommitPrepare` orders commits by. `records` names those listed
submodules, so a client skips a parent whose submodule push failed instead of
letting `--recurse-submodules=check` refuse it. A failed repository does not fail
the request; duplicate IDs, more than 10,000 repositories, an unsupported
`pushTags`, a `pushTargets` key that names no listed repository, unknown fields,
or a gitlink cycle return `invalid_request`. Repositories are read one after
another, nothing is fetched and nothing is written.

New reference-based workflows send `gitReference` as `{ "fullName": string,
"shortName": string, "kind": "local" | "remote" | "tag" }`. Core verifies
that all three fields describe the same namespace and validates the full ref
Expand Down
7 changes: 7 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -869,6 +869,8 @@ pub enum GitCommand {
WorktreeCreationPreview,
/// Resolves the destination and commits for a branch push (`git.pushPreview`).
PushPreview,
/// Reviews pushing every workspace repository, in push order (`git.workspacePushPreview`).
WorkspacePushPreview,
/// Resolves metadata for one commit (`git.commit`).
Commit,
/// Lists paths changed by one commit (`git.commitFiles`).
Expand Down Expand Up @@ -1484,6 +1486,7 @@ impl CoreCommand {
"git.changedFileGroups" => Some(Self::Git(GitCommand::ChangedFileGroups)),
"git.worktreeCreationPreview" => Some(Self::Git(GitCommand::WorktreeCreationPreview)),
"git.pushPreview" => Some(Self::Git(GitCommand::PushPreview)),
"git.workspacePushPreview" => Some(Self::Git(GitCommand::WorkspacePushPreview)),
"git.commit" => Some(Self::Git(GitCommand::Commit)),
"git.commitFiles" => Some(Self::Git(GitCommand::CommitFiles)),
"git.comparison" => Some(Self::Git(GitCommand::Comparison)),
Expand Down Expand Up @@ -1752,6 +1755,10 @@ mod tests {
CoreCommand::parse("git.pushPreview"),
Some(CoreCommand::Git(GitCommand::PushPreview))
));
assert!(matches!(
CoreCommand::parse("git.workspacePushPreview"),
Some(CoreCommand::Git(GitCommand::WorkspacePushPreview))
));
}

#[test]
Expand Down
19 changes: 19 additions & 0 deletions rust/crates/core/src/runtime/dispatcher/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,25 @@ pub(super) fn dispatch(command: GitCommand, id: Option<String>, payload: Value)
Err(error) => CoreResponse::failure(id, error),
}
}
GitCommand::WorkspacePushPreview => {
let result = serde_json::from_value::<git::workspace_push::PreviewRequest>(payload)
.map_err(|error| {
CoreError::new(
ErrorCode::InvalidRequest,
"Invalid workspace push preview request",
)
.with_details(error.to_string())
})
.and_then(git::workspace_push::preview);
match result {
Ok(data) => CoreResponse::success(
id,
serde_json::to_value(data)
.expect("Workspace push preview response should encode"),
),
Err(error) => CoreResponse::failure(id, error),
}
}
GitCommand::WorkspaceCommitStep => {
let result = serde_json::from_value::<git::workspace_commit::StepRequest>(payload)
.map_err(|error| {
Expand Down
237 changes: 237 additions & 0 deletions rust/crates/core/tests/git_push.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1317,3 +1317,240 @@ fn new_worktree_freezes_tracking_semantics() {
);
assert_no_upstream(&repository, "feature/from-commit");
}

fn workspace_push_preview(payload: Value) -> Value {
let request = json!({
"id": "test-git.workspacePushPreview",
"command": "git.workspacePushPreview",
"payload": payload
});
serde_json::from_str(&execute_json(
&serde_json::to_string(&request).expect("Core request should encode"),
))
.expect("Core response should be JSON")
}

/// A repository with one commit on `main` and no remote.
fn local_repository(directory: &Path) {
fs::create_dir_all(directory).expect("repository should be creatable");
require_git(directory, &["init", "-q"]);
require_git(directory, &["config", "user.email", "tests@lithe.local"]);
require_git(directory, &["config", "user.name", "Lithe Tests"]);
fs::write(directory.join("file.txt"), "initial\n").expect("fixture should be writable");
require_git(directory, &["add", "file.txt"]);
require_git(directory, &["commit", "-q", "-m", "initial"]);
require_git(directory, &["branch", "-M", "main"]);
}

fn commit_file(directory: &Path, name: &str, subject: &str) {
fs::write(directory.join(name), format!("{subject}\n")).expect("fixture should be writable");
require_git(directory, &["add", name]);
require_git(directory, &["commit", "-q", "-m", subject]);
}

fn binding(id: &str, root: &Path) -> Value {
json!({ "id": id, "root": root })
}

fn subjects(repository: &Value) -> Vec<String> {
repository["preview"]["commits"]
.as_array()
.expect("a preview lists its commits")
.iter()
.map(|commit| commit["subject"].as_str().unwrap_or_default().to_string())
.collect()
}

/// IDEA's Push dialog lists every repository of the project. Core says which can
/// push and why the others cannot, and lists a submodule before the repository
/// that records it, so pushing the checked ones in order passes
/// `--recurse-submodules=check`.
#[test]
fn workspace_push_preview_reviews_every_repository_in_push_order() {
let fixture = GitFixture::new();
let (parent, _) = initialize_repository(&fixture);
let child = parent.join("child");
local_repository(&child);
add_bare_remote(&fixture, &child, "origin");
require_git(&child, &["push", "-q", "-u", "origin", "main"]);
commit_file(&child, "child.txt", "child work");
require_git(&parent, &["add", "child"]);
require_git(&parent, &["commit", "-q", "-m", "record child"]);

let current = fixture.root.join("current");
local_repository(&current);
add_bare_remote(&fixture, &current, "current-origin");
require_git(&current, &["push", "-q", "-u", "current-origin", "main"]);
let local = fixture.root.join("local");
local_repository(&local);
let empty = fixture.root.join("empty");
fs::create_dir_all(&empty).expect("repository should be creatable");
require_git(&empty, &["init", "-q", "-b", "main"]);
let detached = fixture.root.join("detached");
local_repository(&detached);
require_git(&detached, &["switch", "-q", "--detach"]);
let plain = fixture.root.join("plain");
fs::create_dir_all(&plain).expect("folder should be creatable");

let response = workspace_push_preview(json!({
"repositories": [
binding("repository", &parent),
binding("repository/child", &child),
binding("current", &current),
binding("local", &local),
binding("empty", &empty),
binding("detached", &detached),
binding("plain", &plain),
]
}));
assert_eq!(response["ok"], true, "response: {response}");
let repositories = response["data"]["repositories"]
.as_array()
.expect("the response lists the repositories");
let ids: Vec<_> = repositories
.iter()
.map(|r| r["id"].as_str().unwrap())
.collect();
assert_eq!(
ids,
[
"repository/child",
"repository",
"current",
"local",
"empty",
"detached",
"plain"
],
"a submodule pushes before the repository that records it"
);
let states: Vec<_> = repositories
.iter()
.map(|r| r["state"].as_str().unwrap())
.collect();
assert_eq!(
states,
[
"ready",
"ready",
"upToDate",
"noRemote",
"emptyRepository",
"detachedHead",
"failed"
]
);
assert_eq!(subjects(&repositories[0]), ["child work"]);
assert_eq!(subjects(&repositories[1]), ["record child"]);
assert_eq!(repositories[1]["records"], json!(["repository/child"]));
assert_eq!(repositories[0]["records"], json!([]));
assert!(subjects(&repositories[2]).is_empty());
for (index, branch) in [
(0, "main"),
(1, "main"),
(2, "main"),
(3, "main"),
(4, "main"),
] {
assert_eq!(
repositories[index]["branch"], branch,
"response: {response}"
);
}
assert!(repositories[5].get("branch").is_none());
assert!(repositories[3].get("preview").is_none());
assert!(repositories[6]["detail"]
.as_str()
.is_some_and(|d| !d.is_empty()));
assert!(repositories.iter().all(|r| r["needsTarget"] == false));

// Each preview is the review its repository's push is checked against. Pushed in
// the listed order, the parent passes the submodule check; before the child it
// would not.
let early = core(
"git.write",
&parent,
json!({
"operation": "push",
"checkSubmodules": true,
"expectedPush": workspace_expectation(&repositories[1]),
}),
);
assert_eq!(early["ok"], true, "response: {early}");
assert_ne!(early["data"]["exitCode"], 0, "response: {early}");
assert!(
early["data"]["stderr"]
.as_str()
.is_some_and(|stderr| stderr.contains("child")),
"Git names the submodule it could not find: {early}"
);
for (repository, root) in [(&repositories[0], &child), (&repositories[1], &parent)] {
let pushed = core(
"git.write",
root,
json!({
"operation": "push",
"checkSubmodules": true,
"expectedPush": workspace_expectation(repository),
}),
);
assert_eq!(pushed["ok"], true, "response: {pushed}");
assert_eq!(pushed["data"]["exitCode"], 0, "response: {pushed}");
}
let again = workspace_push_preview(json!({
"repositories": [binding("repository", &parent), binding("repository/child", &child)]
}));
let states: Vec<_> = again["data"]["repositories"]
.as_array()
.unwrap()
.iter()
.map(|r| r["state"].as_str().unwrap())
.collect();
assert_eq!(states, ["upToDate", "upToDate"], "response: {again}");
}

fn workspace_expectation(repository: &Value) -> Value {
push_expectation(&json!({ "data": repository["preview"] }))
}

/// A divergent upstream is still reviewed, but marked as needing a destination
/// until the request picks one for that repository.
#[test]
fn workspace_push_preview_asks_for_a_divergent_destination() {
let fixture = GitFixture::new();
let (repository, _) = divergent_feature_branch(&fixture);
let unanswered = workspace_push_preview(json!({
"repositories": [binding("topic", &repository)]
}));
let review = &unanswered["data"]["repositories"][0];
assert_eq!(review["state"], "ready", "response: {unanswered}");
assert_eq!(review["needsTarget"], true, "response: {unanswered}");
assert_eq!(review["preview"]["targetKind"], "divergent");

let answered = workspace_push_preview(json!({
"repositories": [binding("topic", &repository)],
"pushTargets": { "topic": "upstream" }
}));
let review = &answered["data"]["repositories"][0];
assert_eq!(review["needsTarget"], false, "response: {answered}");
assert_eq!(review["preview"]["remoteBranch"], "main");
}

#[test]
fn workspace_push_preview_rejects_requests_discovery_cannot_produce() {
let fixture = GitFixture::new();
let (repository, _) = initialize_repository(&fixture);
for payload in [
json!({ "repositories": [binding("a", &repository), binding("a", &fixture.root)] }),
json!({ "repositories": [binding("a", &repository)], "pushTags": "some" }),
json!({ "repositories": [binding("a", &repository)], "pushTargets": { "b": "publish" } }),
json!({ "repositories": [binding("a", &repository)], "unknown": true }),
] {
let response = workspace_push_preview(payload.clone());
assert_eq!(response["ok"], false, "payload: {payload}");
assert_eq!(
response["error"]["code"], "invalid_request",
"payload: {payload}"
);
}
}
1 change: 1 addition & 0 deletions rust/crates/git/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub mod contracts;
mod deleted_selection;
mod diff_blocks;
pub mod workspace_commit;
pub mod workspace_push;
mod workspace_repositories;
pub mod workspace_status;
pub use commit_state::{inspect as commit_state, GitCommitGitlink, GitCommitState};
Expand Down
6 changes: 3 additions & 3 deletions rust/crates/git/src/workspace_commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ fn invalid(message: &str) -> CoreError {
CoreError::new(ErrorCode::InvalidRequest, message)
}

fn validate_bindings(bindings: &[RepositoryBinding]) -> Result<(), CoreError> {
pub(crate) fn validate_bindings(bindings: &[RepositoryBinding]) -> Result<(), CoreError> {
let mut ids = BTreeSet::new();
let mut roots = BTreeSet::new();
for binding in bindings {
Expand Down Expand Up @@ -560,7 +560,7 @@ fn settle_push_targets(
Ok((confirmed, questions))
}

fn relations(
pub(crate) fn relations(
bindings: &[RepositoryBinding],
states: &BTreeMap<String, GitCommitState>,
) -> Result<Vec<Relation>, CoreError> {
Expand All @@ -584,7 +584,7 @@ fn relations(
Ok(relations)
}

fn commit_order(
pub(crate) fn commit_order(
mut remaining: Vec<String>,
relations: &[Relation],
) -> Result<Vec<String>, CoreError> {
Expand Down
Loading
Loading