From 373b038561e1b33f05fba23db5389c9928466ae2 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Mon, 16 Nov 2026 22:05:13 +0800 Subject: [PATCH] =?UTF-8?q?feat(git):=20=E5=A4=9A=E4=BB=93=E5=BA=93?= =?UTF-8?q?=E6=8E=A8=E9=80=81=E9=A2=84=E8=A7=88=20git.workspacePushPreview?= =?UTF-8?q?=EF=BC=8C=E6=8C=89=E5=AD=90=E6=A8=A1=E5=9D=97=E5=85=88=E4=BA=8E?= =?UTF-8?q?=E7=88=B6=E4=BB=93=E5=BA=93=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 参照 IDEA 的推送对话框:一次读取所有绑定仓库,逐个给出 ready / upToDate / noRemote / emptyRepository / detachedHead / failed 状态、当前分支和 git.pushPreview 结果;列表按 gitlink 关系排序(子仓库先于记录它的父仓库), records 列出父仓库记录的子仓库,客户端在子仓库推送失败时跳过父仓库。 分歧上游未指定目标时 needsTarget 为 true。 Refs 1lck/Lithe-IDEA#2013 --- rust/contracts/rust-core-api.md | 31 ++ rust/crates/core/src/protocol/command.rs | 7 + .../crates/core/src/runtime/dispatcher/git.rs | 19 ++ rust/crates/core/tests/git_push.rs | 237 +++++++++++++++ rust/crates/git/src/lib.rs | 1 + rust/crates/git/src/workspace_commit.rs | 6 +- rust/crates/git/src/workspace_push.rs | 279 ++++++++++++++++++ 7 files changed, 577 insertions(+), 3 deletions(-) create mode 100644 rust/crates/git/src/workspace_push.rs diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index f00107ef..d43100b5 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -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 | @@ -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: { : "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 diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 933880d6..f6e7992c 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -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`). @@ -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)), @@ -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] diff --git a/rust/crates/core/src/runtime/dispatcher/git.rs b/rust/crates/core/src/runtime/dispatcher/git.rs index e585ce36..27be3dc8 100644 --- a/rust/crates/core/src/runtime/dispatcher/git.rs +++ b/rust/crates/core/src/runtime/dispatcher/git.rs @@ -39,6 +39,25 @@ pub(super) fn dispatch(command: GitCommand, id: Option, payload: Value) Err(error) => CoreResponse::failure(id, error), } } + GitCommand::WorkspacePushPreview => { + let result = serde_json::from_value::(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::(payload) .map_err(|error| { diff --git a/rust/crates/core/tests/git_push.rs b/rust/crates/core/tests/git_push.rs index 31991cf2..df248d3f 100644 --- a/rust/crates/core/tests/git_push.rs +++ b/rust/crates/core/tests/git_push.rs @@ -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 { + 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(¤t); + add_bare_remote(&fixture, ¤t, "current-origin"); + require_git(¤t, &["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", ¤t), + 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}" + ); + } +} diff --git a/rust/crates/git/src/lib.rs b/rust/crates/git/src/lib.rs index 8f58783c..9af40a23 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; +pub mod workspace_push; mod workspace_repositories; pub mod workspace_status; pub use commit_state::{inspect as commit_state, GitCommitGitlink, GitCommitState}; diff --git a/rust/crates/git/src/workspace_commit.rs b/rust/crates/git/src/workspace_commit.rs index 563f8be4..334a8860 100644 --- a/rust/crates/git/src/workspace_commit.rs +++ b/rust/crates/git/src/workspace_commit.rs @@ -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 { @@ -560,7 +560,7 @@ fn settle_push_targets( Ok((confirmed, questions)) } -fn relations( +pub(crate) fn relations( bindings: &[RepositoryBinding], states: &BTreeMap, ) -> Result, CoreError> { @@ -584,7 +584,7 @@ fn relations( Ok(relations) } -fn commit_order( +pub(crate) fn commit_order( mut remaining: Vec, relations: &[Relation], ) -> Result, CoreError> { diff --git a/rust/crates/git/src/workspace_push.rs b/rust/crates/git/src/workspace_push.rs new file mode 100644 index 00000000..6db51daf --- /dev/null +++ b/rust/crates/git/src/workspace_push.rs @@ -0,0 +1,279 @@ +//! Reviews a push of several workspace repositories at once (`git.workspacePushPreview`). +//! +//! IntelliJ IDEA's Push dialog lists every repository of a project with the branch +//! it would push, the destination, and the commits that remote lacks, and checks +//! the ones that have something to send. Core reads each repository the host +//! binds and says whether it can push and, when it cannot, why: it has no commit +//! yet, HEAD is detached, no remote is configured, or Git failed to answer. Each +//! repository that can push carries its `git.pushPreview`, which the host sends +//! back unchanged as the `expectedPush` of that repository's reviewed `push`. +//! +//! The list comes in push order: a submodule before every listed repository that +//! records it, and otherwise in the order the host listed them. Pushing the +//! checked repositories in that order lets `--recurse-submodules=check` find each +//! recorded commit on its remote. `records` names those submodules, so a host +//! skips a parent whose submodule push failed instead of letting Git refuse it. +//! +//! Every repository is read in turn on the calling thread, because Git's +//! execution options, such as the operation's cancellation, are thread-local. + +use super::{ + commit_state, execute_git_readonly, push_preview, validate_root, GitCommitState, + GitPushPreviewRequest, GitPushPreviewResponse, GitPushTargetKind, PushTargetChoiceRequest, +}; +use crate::workspace_commit::{commit_order, relations, validate_bindings, RepositoryBinding}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// Bounds one workspace's repository list, as `workspace.repositories` does. +const MAX_REPOSITORIES: usize = 10_000; +/// Commits each preview lists when the host does not ask for another number. +const DEFAULT_LIMIT: usize = 100; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// Request to review pushing the checked-out branch of every bound repository. +pub struct PreviewRequest { + /// The repositories to review, in the order the host lists them. + pub repositories: Vec, + /// Commits each preview lists, clamped like `git.pushPreview`. + #[serde(default = "default_limit")] + pub limit: usize, + /// Tag scope every preview resolves: `none`, `all`, or `reachable`. + #[serde(default)] + pub push_tags: Option, + /// Destinations the user picked for divergent upstreams, by repository ID. + #[serde(default)] + pub push_targets: BTreeMap, +} + +fn default_limit() -> usize { + DEFAULT_LIMIT +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +/// Every bound repository in push order. +pub struct PreviewResponse { + pub repositories: Vec, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +/// Whether a repository can push, and why not. +pub enum PushState { + /// The preview has commits to send or publishes a new remote branch. + Ready, + /// The remote already has every commit of the branch. + UpToDate, + /// No remote is configured, so there is nowhere to push. + NoRemote, + /// The checked-out branch has no commit yet. + EmptyRepository, + /// HEAD names a commit instead of a branch. + DetachedHead, + /// Git could not read the repository or resolve its destination; see `detail`. + Failed, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +/// The push review of one repository. +pub struct RepositoryPush { + /// The repository's binding ID. + pub id: String, + pub state: PushState, + /// Short name of the checked-out branch; absent when HEAD is detached or the + /// repository could not be read. + #[serde(skip_serializing_if = "Option::is_none")] + pub branch: Option, + /// The `git.pushPreview` of a `ready` or `upToDate` repository. + #[serde(skip_serializing_if = "Option::is_none")] + pub preview: Option, + /// True when the upstream has another name and the request picked no + /// destination for it; the push is refused until one is picked. + pub needs_target: bool, + /// IDs of the listed repositories this one records as submodules. They come + /// earlier in the list, and this repository should not push after one of + /// them failed to. + pub records: Vec, + /// What Git or Core said about a `failed` repository. + #[serde(skip_serializing_if = "Option::is_none")] + pub detail: Option, +} + +impl RepositoryPush { + fn new(id: &str, state: PushState) -> Self { + Self { + id: id.into(), + state, + branch: None, + preview: None, + needs_target: false, + records: Vec::new(), + detail: None, + } + } + + fn failed(id: &str, error: CoreError) -> Self { + let mut push = Self::new(id, PushState::Failed); + push.detail = Some(match error.details { + Some(details) if !details.trim().is_empty() => { + format!("{}: {}", error.message, details.trim()) + } + _ => error.message, + }); + push + } +} + +fn invalid(message: &str) -> CoreError { + CoreError::new(ErrorCode::InvalidRequest, message) +} + +/// Reviews pushing every bound repository and orders the list for pushing. +pub fn preview(request: PreviewRequest) -> Result { + if request.repositories.len() > MAX_REPOSITORIES { + return Err(invalid("Too many workspace repositories")); + } + validate_bindings(&request.repositories)?; + // Checked once here: every preview would otherwise fail alike. + if !matches!( + request.push_tags.as_deref(), + None | Some("none" | "all" | "reachable") + ) { + return Err(invalid("Unsupported Git push tag scope")); + } + if let Some(id) = request.push_targets.keys().find(|id| { + !request + .repositories + .iter() + .any(|binding| &binding.id == *id) + }) { + return Err(invalid(&format!( + "Push target names a repository that is not listed: {id}" + ))); + } + + let mut reviews = BTreeMap::new(); + let mut read = Vec::new(); + let mut states = BTreeMap::new(); + for binding in &request.repositories { + let (review, state) = review(binding, &request); + if let Some((root, state)) = state { + read.push(RepositoryBinding { + id: binding.id.clone(), + root, + }); + states.insert(binding.id.clone(), state); + } + reviews.insert(binding.id.clone(), review); + } + + let relations = relations(&read, &states)?; + let order = commit_order( + request.repositories.iter().map(|b| b.id.clone()).collect(), + &relations, + )?; + let repositories = order + .into_iter() + .map(|id| { + let mut review = reviews + .remove(&id) + .expect("every listed repository is reviewed"); + review.records = relations + .iter() + .filter(|relation| relation.parent == id) + .map(|relation| relation.child.clone()) + .collect(); + review + }) + .collect(); + Ok(PreviewResponse { repositories }) +} + +/// Reviews one repository, and returns the state its submodule records are read +/// from when the repository could be read. +fn review( + binding: &RepositoryBinding, + request: &PreviewRequest, +) -> (RepositoryPush, Option<(String, GitCommitState)>) { + let id = binding.id.as_str(); + let root = match validate_root(&binding.root) { + Ok(root) => root, + Err(error) => return (RepositoryPush::failed(id, error), None), + }; + let state = match commit_state::inspect_root(&root) { + Ok(state) => state, + Err(error) => return (RepositoryPush::failed(id, error), None), + }; + let push = review_state(id, &root, &state, request); + (push, Some((root, state))) +} + +fn review_state( + id: &str, + root: &str, + state: &GitCommitState, + request: &PreviewRequest, +) -> RepositoryPush { + let branch = state.branch.as_deref().map(|branch| { + branch + .strip_prefix("refs/heads/") + .unwrap_or(branch) + .to_string() + }); + let Some(branch) = branch else { + return RepositoryPush::new(id, PushState::DetachedHead); + }; + let mut push = if state.head.is_none() { + RepositoryPush::new(id, PushState::EmptyRepository) + } else { + match has_remote(root) { + Ok(false) => RepositoryPush::new(id, PushState::NoRemote), + Ok(true) => preview_branch(id, root, request), + Err(error) => RepositoryPush::failed(id, error), + } + }; + push.branch = Some(branch); + push +} + +fn has_remote(root: &str) -> Result { + let remotes = execute_git_readonly(root, &["remote".into()], None)?; + if remotes.exit_code != 0 { + return Err( + CoreError::new(ErrorCode::ProcessFailed, "Could not list Git remotes") + .with_details(remotes.output), + ); + } + Ok(remotes.output.lines().any(|line| !line.trim().is_empty())) +} + +fn preview_branch(id: &str, root: &str, request: &PreviewRequest) -> RepositoryPush { + let target = request.push_targets.get(id).copied(); + let preview = push_preview(GitPushPreviewRequest { + root: root.into(), + reference: None, + git_reference: None, + limit: request.limit, + push_tags: request.push_tags.clone(), + push_target: target, + }); + match preview { + Ok(preview) => { + let state = if preview.commits.is_empty() && !preview.creates_remote_branch { + PushState::UpToDate + } else { + PushState::Ready + }; + let mut push = RepositoryPush::new(id, state); + push.needs_target = + preview.target_kind == GitPushTargetKind::Divergent && target.is_none(); + push.preview = Some(preview); + push + } + Err(error) => RepositoryPush::failed(id, error), + } +}