diff --git a/desktop/internal/core/git_workspace_branches.go b/desktop/internal/core/git_workspace_branches.go new file mode 100644 index 0000000000..1be1d70ac8 --- /dev/null +++ b/desktop/internal/core/git_workspace_branches.go @@ -0,0 +1,117 @@ +package core + +import "context" + +// WorkspaceRepositoryReferences is one repository of a folder with several, with the references +// its git.references call returned, passed back to Core unchanged. +type WorkspaceRepositoryReferences struct { + // ID is the repository's workspace.repositories ID. + ID string `json:"id"` + References []GitReference `json:"references"` +} + +// WorkspaceCommonReferences are the branches every repository of a folder has, as IntelliJ IDEA's +// Common Local Branches and Common Remote Branches list them, in the first repository's order. +// Each is a git.references entry: IsCurrent when every repository has it checked out, +// UpstreamShortName when every repository tracks the same remote branch with it, and Ahead and +// Behind added up over the repositories. +type WorkspaceCommonReferences struct { + Local []GitReference `json:"local"` + Remote []GitReference `json:"remote"` +} + +// GitWorkspaceCommonReferences asks Core which local and remote branches every repository has +// (git.workspaceCommonReferences). It runs no process. +func (c *Client) GitWorkspaceCommonReferences(ctx context.Context, repositories []WorkspaceRepositoryReferences) (WorkspaceCommonReferences, error) { + request := struct { + Repositories []WorkspaceRepositoryReferences `json:"repositories"` + }{workspaceRepositoryReferences(repositories)} + var common WorkspaceCommonReferences + if err := c.Execute(ctx, "git.workspaceCommonReferences", request, &common); err != nil { + return WorkspaceCommonReferences{}, err + } + common.Local, common.Remote = nonNil(common.Local), nonNil(common.Remote) + return common, nil +} + +// WorkspaceBranchOperation is the branch action chosen on a common branch. +type WorkspaceBranchOperation string + +const ( + // WorkspaceBranchCheckout switches every repository to the common branch. + WorkspaceBranchCheckout WorkspaceBranchOperation = "checkout" + // WorkspaceBranchCreate creates a new local branch at the common branch in every repository. + WorkspaceBranchCreate WorkspaceBranchOperation = "createBranch" +) + +// WorkspaceBranchPlanRequest asks Core how a branch action on a common branch runs across the +// repositories. +type WorkspaceBranchPlanRequest struct { + Operation WorkspaceBranchOperation `json:"operation"` + // Reference is the full name of the common local or remote branch. + Reference string `json:"reference"` + // Name is the new branch's name for WorkspaceBranchCreate, as git.branchNamePreview cleaned it. + Name string `json:"name,omitempty"` + // Checkout switches every repository to the new branch of WorkspaceBranchCreate. + Checkout bool `json:"checkout,omitempty"` + // Repositories are the repositories the action runs in, in the order it runs. + Repositories []WorkspaceRepositoryReferences `json:"repositories"` +} + +// WorkspaceBranchPlan is Core's plan of a branch action across the repositories. +type WorkspaceBranchPlan struct { + // Steps are the writes in the order they run; the first that fails stops the action. + Steps []WorkspaceBranchStep `json:"steps"` + // Skipped are the IDs of the repositories a checkout leaves alone because they are already on + // the branch. + Skipped []string `json:"skipped"` +} + +// WorkspaceBranchStep is the write of one repository: a checkout of Reference, or a new branch +// at it. +type WorkspaceBranchStep struct { + Repository string `json:"repository"` + // Reference is this repository's fullName, shortName and kind of the common branch. + Reference GitReference `json:"reference"` + // Rollback are the writes that undo the step, in the order they run; nil when nothing can, + // because HEAD was detached or unborn before the step switched it. + Rollback []WorkspaceBranchRollback `json:"rollback"` +} + +// WorkspaceBranchRollbackOperation is the git.write operation of a rollback action. +type WorkspaceBranchRollbackOperation string + +const ( + // WorkspaceRollbackCheckout checks the previous local branch out again. + WorkspaceRollbackCheckout WorkspaceBranchRollbackOperation = "checkout" + // WorkspaceRollbackDeleteBranch deletes the branch the step created. + WorkspaceRollbackDeleteBranch WorkspaceBranchRollbackOperation = "deleteBranch" +) + +// WorkspaceBranchRollback is one write that undoes part of a step. +type WorkspaceBranchRollback struct { + Operation WorkspaceBranchRollbackOperation `json:"operation"` + Reference GitReference `json:"reference"` +} + +// GitWorkspaceBranchPlan asks Core which writes a branch action on a common branch runs in each +// repository, which repositories it skips, and what undoes each write (git.workspaceBranchPlan). +// It runs no process; the caller runs the writes. +func (c *Client) GitWorkspaceBranchPlan(ctx context.Context, request WorkspaceBranchPlanRequest) (WorkspaceBranchPlan, error) { + request.Repositories = workspaceRepositoryReferences(request.Repositories) + var plan WorkspaceBranchPlan + if err := c.Execute(ctx, "git.workspaceBranchPlan", request, &plan); err != nil { + return WorkspaceBranchPlan{}, err + } + plan.Steps, plan.Skipped = nonNil(plan.Steps), nonNil(plan.Skipped) + return plan, nil +} + +// workspaceRepositoryReferences is repositories with every list present, as Core requires. +func workspaceRepositoryReferences(repositories []WorkspaceRepositoryReferences) []WorkspaceRepositoryReferences { + out := make([]WorkspaceRepositoryReferences, len(repositories)) + for i, repository := range repositories { + out[i] = WorkspaceRepositoryReferences{ID: repository.ID, References: nonNil(repository.References)} + } + return out +} diff --git a/desktop/internal/core/gitlog.go b/desktop/internal/core/gitlog.go index fdf3e53dd5..e4fa50f01b 100644 --- a/desktop/internal/core/gitlog.go +++ b/desktop/internal/core/gitlog.go @@ -200,6 +200,10 @@ type GraphRequest struct { // CurrentBranch is the branch whose commits get the current-branch background, empty // for none. CurrentBranch string `json:"currentBranch,omitempty"` + // CheckedOutHeads gives the current-branch background to the commits of every checked-out + // branch instead, for a list that merges several repositories: each repository's own + // current branch. It cannot be combined with CurrentBranch. + CheckedOutHeads bool `json:"-"` } type graphRequestWire struct { @@ -209,6 +213,7 @@ type graphRequestWire struct { VisibleHashes []string `json:"visibleHashes"` DisplayMode string `json:"displayMode"` CurrentBranch string `json:"currentBranch,omitempty"` + CheckedOutHeads bool `json:"checkedOutHeads,omitempty"` } // GraphEdge is one edge from a row's commit to a parent. @@ -264,7 +269,8 @@ type Graph struct { // visible rows are. RecommendedLaneCount int `json:"recommendedLaneCount"` HasMissingParents bool `json:"hasMissingParents"` - // CurrentBranchHashes are the commits of the current branch. + // CurrentBranchHashes are the commits of the current branch, or of every checked-out branch + // for CheckedOutHeads. CurrentBranchHashes []string `json:"currentBranchHashes"` } @@ -281,6 +287,7 @@ func (c *Client) GitGraph(ctx context.Context, request GraphRequest) (Graph, err VisibleHashes: request.VisibleHashes, DisplayMode: mode, CurrentBranch: request.CurrentBranch, + CheckedOutHeads: request.CheckedOutHeads, } var graph Graph if err := c.Execute(ctx, "git.graphProjection", wire, &graph); err != nil { diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index ee13403216..5c1b8f81f7 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -38,12 +38,19 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.branch.checkedOut": "Checked out '{name}'", "desktop.branch.checkoutAfter": "Checkout branch after creation", "desktop.branch.checkoutFailed": "Failed to check out: {reason}", + "desktop.branch.checkoutFailedIn": "Failed to check out '{name}' in {repository}: {reason}", "desktop.branch.checkoutRevision": "Checkout Tag or Revision…", + "desktop.branch.commonCheckedOut": "Checked out '{name}' in every repository", + "desktop.branch.commonCreated": "Created branch '{name}' in every repository", + "desktop.branch.commonLocal": "Common Local Branches", + "desktop.branch.commonRemote": "Common Remote Branches", "desktop.branch.conflictHint": "Smart Checkout stashes your changes, switches branch, then restores them. Force Checkout switches and discards them.", "desktop.branch.conflictPrompt": "Your changes to these files conflict with '{name}':", "desktop.branch.conflictTitle": "Local changes would be overwritten", "desktop.branch.createFailed": "Failed to create branch: {reason}", + "desktop.branch.createFailedIn": "Failed to create branch '{name}' in {repository}: {reason}", "desktop.branch.createFrom": "Create from '{name}'.", + "desktop.branch.createFromInAll": "Create from '{name}' in every repository.", "desktop.branch.created": "Created branch '{name}'", "desktop.branch.current": "Current branch", "desktop.branch.deleteFailed": "Failed to delete branch: {reason}", @@ -53,6 +60,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.branch.detached": "Checked out '{revision}' in detached HEAD state", "desktop.branch.detachedNote": "The repository will be opened in detached HEAD state.", "desktop.branch.forceCheckout": "Force Checkout", + "desktop.branch.keepButton": "Don't Roll Back", "desktop.branch.loadFailed": "Failed to load branches: {reason}", "desktop.branch.loading": "Loading branches…", "desktop.branch.localIn": "Local Branches in {repository}", @@ -67,9 +75,16 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.branch.renameTitle": "Rename Branch", "desktop.branch.renamed": "Renamed the branch to '{name}'", "desktop.branch.repositoryPanel": "{repository} on {branch}", + "desktop.branch.repositorySeparator": ", ", "desktop.branch.revision": "Tag or revision", "desktop.branch.revisionPrompt": "Enter a tag name, branch name, commit hash, or other Git revision.", "desktop.branch.revisionTitle": "Checkout Tag or Revision", + "desktop.branch.rollbackButton": "Roll Back", + "desktop.branch.rollbackFailed": "Rollback failed in {repository}: {reason}", + "desktop.branch.rollbackImpossible": "{repositories} were on no branch before, so they cannot be rolled back.", + "desktop.branch.rollbackPrompt": "It already succeeded in {repositories}. Roll back to return every repository to the branch it was on.", + "desktop.branch.rollbackTitle": "Completed in Some Repositories Only", + "desktop.branch.rolledBack": "Rolled back {repositories}", "desktop.branch.rowMenu": "{name} actions", "desktop.branch.search": "Search for branches and actions", "desktop.branch.smartCheckout": "Smart Checkout", @@ -2938,12 +2953,19 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.branch.checkedOut": "已检出“{name}”", "desktop.branch.checkoutAfter": "创建后检出分支", "desktop.branch.checkoutFailed": "检出失败:{reason}", + "desktop.branch.checkoutFailedIn": "在 {repository} 中检出“{name}”失败:{reason}", "desktop.branch.checkoutRevision": "检出标签或修订版本…", + "desktop.branch.commonCheckedOut": "已在所有仓库检出“{name}”", + "desktop.branch.commonCreated": "已在所有仓库创建分支“{name}”", + "desktop.branch.commonLocal": "共同本地分支", + "desktop.branch.commonRemote": "共同远程分支", "desktop.branch.conflictHint": "智能检出会先贮藏你的更改,切换分支后再恢复。强制检出会直接切换并丢弃这些更改。", "desktop.branch.conflictPrompt": "你对这些文件的更改与“{name}”冲突:", "desktop.branch.conflictTitle": "本地更改将被覆盖", "desktop.branch.createFailed": "创建分支失败:{reason}", + "desktop.branch.createFailedIn": "在 {repository} 中创建分支“{name}”失败:{reason}", "desktop.branch.createFrom": "从“{name}”创建。", + "desktop.branch.createFromInAll": "在所有仓库中从“{name}”创建。", "desktop.branch.created": "已创建分支“{name}”", "desktop.branch.current": "当前分支", "desktop.branch.deleteFailed": "删除分支失败:{reason}", @@ -2953,6 +2975,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.branch.detached": "已检出“{revision}”,处于 detached HEAD 状态", "desktop.branch.detachedNote": "仓库将以 detached HEAD 状态打开。", "desktop.branch.forceCheckout": "强制检出", + "desktop.branch.keepButton": "不回滚", "desktop.branch.loadFailed": "加载分支失败:{reason}", "desktop.branch.loading": "正在加载分支…", "desktop.branch.localIn": "{repository} 中的本地分支", @@ -2967,9 +2990,16 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.branch.renameTitle": "重命名分支", "desktop.branch.renamed": "分支已重命名为“{name}”", "desktop.branch.repositoryPanel": "{repository},位于 {branch}", + "desktop.branch.repositorySeparator": "、", "desktop.branch.revision": "标签或修订版本", "desktop.branch.revisionPrompt": "输入标签名、分支名、提交 Hash 或其他 Git 修订版本。", "desktop.branch.revisionTitle": "检出标签或修订版本", + "desktop.branch.rollbackButton": "回滚", + "desktop.branch.rollbackFailed": "在 {repository} 中回滚失败:{reason}", + "desktop.branch.rollbackImpossible": "{repositories} 在操作前不在任何分支上,无法回滚。", + "desktop.branch.rollbackPrompt": "已在这些仓库中完成:{repositories}。回滚后,所有仓库会回到原来的分支。", + "desktop.branch.rollbackTitle": "只在部分仓库中完成", + "desktop.branch.rolledBack": "已回滚:{repositories}", "desktop.branch.rowMenu": "{name} 的操作", "desktop.branch.search": "搜索分支和操作", "desktop.branch.smartCheckout": "智能检出", diff --git a/desktop/internal/workbench/branch.go b/desktop/internal/workbench/branch.go index 5b2e6d0b50..5439bc9e7a 100644 --- a/desktop/internal/workbench/branch.go +++ b/desktop/internal/workbench/branch.go @@ -40,6 +40,9 @@ const ( branchDialogTag // branchDialogTagDelete confirms deleting a tag. branchDialogTagDelete + // branchDialogRollback offers to undo a branch action on a common branch that failed after + // it succeeded in some repositories (branch_common.go). + branchDialogRollback ) // branchSession is the state of the branch popup while it is open and of the dialog it @@ -88,6 +91,14 @@ type branchSession struct { busy bool // annotated says the new tag takes the typed message; otherwise it is lightweight. annotated bool + + // common are the branches every repository of a project folder with several has + // (branch_common.go). + common commonBranches + // across says the open dialog acts on a common branch in every repository: the new branch + // dialog, the conflict dialog and the rollback dialog. write is that action. + across bool + write commonWrite } // branchOperationTimeout bounds one branch write and the status read after it. @@ -114,6 +125,7 @@ func (a *App) openBranches() { b.collapsed, b.expanded = map[string]bool{}, map[string]bool{} } a.loadBranches(p) + a.loadCommonBranches(p) } // closeBranches closes the popup and the row menu in it. @@ -125,6 +137,7 @@ func (a *App) closeBranches() { // popup started it. func (a *App) leaveBranches() { a.branch.fromPopup = a.branch.open + a.branch.across = false a.closeBranches() } @@ -298,10 +311,14 @@ func (a *App) noticeCheckedOut(name string, status core.GitStatus) { } // beginCreate opens the dialog that creates a branch from r. -func (a *App) beginCreate(p *project, r core.GitReference) { +func (a *App) beginCreate(p *project, r core.GitReference) { a.openCreate(p, r, false) } + +// openCreate opens the dialog that creates a branch from r, in every repository of the folder +// when across is set and r is a common branch. +func (a *App) openCreate(p *project, r core.GitReference, across bool) { a.leaveBranches() b := &a.branch - b.dialog, b.target, b.checkout = branchDialogCreate, r, true + b.dialog, b.target, b.checkout, b.across = branchDialogCreate, r, true, across b.typed = "" b.preview = a.previewBranchName(p, "", false) b.name.SetText(b.preview.InitialName) @@ -336,15 +353,19 @@ func (a *App) beginDelete(r core.GitReference) { // cancelBranchDialog closes the open dialog without doing what it asked. func (a *App) cancelBranchDialog() { - a.branch.dialog = branchDialogNone + a.branch.dialog, a.branch.across = branchDialogNone, false } // previewBranchName asks the kernel how the typed name is cleaned and whether it can be // created. The computation is pure and answers at once. The branch being renamed is left -// out of the references, so that its own name is not a clash. +// out of the references, so that its own name is not a clash. A branch created in every +// repository must clash with none of their references. func (a *App) previewBranchName(p *project, raw string, require bool) core.BranchNamePreview { b := &a.branch refs := b.refs.References + if b.across { + refs = b.common.allReferences() + } var from *core.GitReference switch b.dialog { case branchDialogCreate: @@ -433,6 +454,10 @@ func (a *App) submitCreate(p *project) { } from, checkout := b.target, b.checkout a.performed("git.branch.create", surfaceButton) + if b.across { + a.planCommon(p, commonWrite{operation: core.WorkspaceBranchCreate, reference: from, name: name, checkout: checkout}) + return + } a.runBranchWrite(p, "git_branch_create", a.text.Branch.CreateFailed, func(ctx context.Context, kernel Kernel, root string) error { return kernel.GitCreateBranch(ctx, root, name, from, checkout) @@ -478,12 +503,17 @@ func (a *App) submitRevision(p *project) { func(a *App, status core.GitStatus) { a.noticeCheckedOut(revision, status) }) } -// resolveConflict checks out the blocked target in mode, as the conflict dialog chose. +// resolveConflict checks out the blocked target in mode, as the conflict dialog chose: in every +// repository of the planned action when the dialog is about a common branch. func (a *App) resolveConflict(p *project, mode core.CheckoutMode) { b := &a.branch if b.busy { return } + if b.across { + a.runCommon(p, b.write, mode) + return + } a.checkoutWith(p, b.target, mode) } diff --git a/desktop/internal/workbench/branch_common.go b/desktop/internal/workbench/branch_common.go new file mode 100644 index 0000000000..a916b365a2 --- /dev/null +++ b/desktop/internal/workbench/branch_common.go @@ -0,0 +1,489 @@ +package workbench + +import ( + "context" + "fmt" + "path" + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// This file runs the branch actions on the common branches of a project folder with several +// repositories, as IntelliJ IDEA's branch popup does for several roots: Core lists the local and +// remote branches every repository has (git.workspaceCommonReferences) and plans a checkout or a new +// branch across them (git.workspaceBranchPlan). The window runs the plan's writes one repository +// after another, stops at the first that fails, and offers to undo the ones that ran, so that the +// repositories do not stay on different branches. The popup draws the sections in branch_view.go. + +// workspaceBrancher is the part of the kernel the common branches use. Core's client implements +// it; a kernel that does not lists no common branch. +type workspaceBrancher interface { + GitWorkspaceCommonReferences(ctx context.Context, repositories []core.WorkspaceRepositoryReferences) (core.WorkspaceCommonReferences, error) + GitWorkspaceBranchPlan(ctx context.Context, request core.WorkspaceBranchPlanRequest) (core.WorkspaceBranchPlan, error) +} + +// commonSectionKeys are the keys of the Common Local Branches and Common Remote Branches sections, +// as branchSession.collapsed keeps them and as the rows' keys start (branchRowKey). Each is also +// its section's logSection kind, so that their folders open apart from one repository's. +var commonSectionKeys = [2]string{commonSectionPrefix + "local", commonSectionPrefix + "remote"} + +// commonSectionPrefix starts the keys of the common sections and of their rows. +const commonSectionPrefix = "common/" + +// commonBranches is what the popup of a folder with several repositories read of the branches +// every repository has. It is read again each time the popup opens. +type commonBranches struct { + // gen counts the reads; the answer of an older one is dropped. + gen int + // loading is set while the kernel reads; loaded once it answered. + loading, loaded bool + err error + // references are each repository's git.references entries in the order of + // workspaceRepositories; a new branch for every repository is checked against all of them. + references []core.WorkspaceRepositoryReferences + // sections are Core's common local and remote branches with their folder trees, in the order + // of commonSectionKeys. + sections [2]logSection +} + +// current is the common local branch every repository has checked out, or HEAD when they are on +// different branches. +func (cb *commonBranches) current() core.GitReference { + for _, r := range cb.sections[0].refs { + if r.IsCurrent { + return r + } + } + return headReference +} + +// allReferences are the references of every repository, one after another. +func (cb *commonBranches) allReferences() []core.GitReference { + var out []core.GitReference + for _, repository := range cb.references { + out = append(out, repository.References...) + } + return out +} + +// commonWrite is a branch action on a common branch that runs in every repository of the folder. +type commonWrite struct { + operation core.WorkspaceBranchOperation + // reference is the common branch the action is on; name and checkout are the new branch of + // WorkspaceBranchCreate and whether every repository switches to it. + reference core.GitReference + name string + checkout bool + // repos are the repositories the action runs in, in Core's order. + repos []workspaceRepository + // plan is Core's plan of the writes. + plan core.WorkspaceBranchPlan + // done are the steps that ran, in order. failed is the ID of the repository whose step failed, + // empty when none did, and err what Git said. + done []core.WorkspaceBranchStep + failed string + err error + // branch is the branch the first repository is on after a checkout that succeeded everywhere. + branch string +} + +// repo is the repository of the action with Core's ID id. +func (w *commonWrite) repo(id string) (workspaceRepository, bool) { + for _, repo := range w.repos { + if repo.id == id { + return repo, true + } + } + return workspaceRepository{}, false +} + +// rootOf is where the repository with Core's ID id is on disk, or an error when the action does +// not run in it, so that no write runs in another folder. +func (w *commonWrite) rootOf(id string) (string, error) { + if repo, ok := w.repo(id); ok && repo.root != "" { + return repo.root, nil + } + return "", fmt.Errorf("the workspace branch plan names repository %q, which the folder does not list", id) +} + +// names are the names of the repositories with the IDs ids, joined for a message. +func (w *commonWrite) names(lang i18n.Language, ids []string) string { + out := make([]string, 0, len(ids)) + for _, id := range ids { + if repo, ok := w.repo(id); ok { + out = append(out, repo.name) + } else { + out = append(out, id) + } + } + return strings.Join(out, i18n.Shared(lang, "desktop.branch.repositorySeparator")) +} + +// operationName names the action for the log. +func (w *commonWrite) operationName() string { + if w.operation == core.WorkspaceBranchCreate { + return "git_workspace_branch_create" + } + return "git_workspace_checkout" +} + +// planFailed words a failure of the action before any repository was written. +func (w *commonWrite) planFailed(t i18n.BranchMessages, reason string) string { + if w.operation == core.WorkspaceBranchCreate { + return t.CreateFailed(reason) + } + return t.CheckoutFailed(reason) +} + +// failedIn words the failure of the action's step in the repository failed. +func (w *commonWrite) failedIn(lang i18n.Language) string { + repository, reason := w.names(lang, []string{w.failed}), w.err.Error() + if w.operation == core.WorkspaceBranchCreate { + return i18n.SharedFormat(lang, "desktop.branch.createFailedIn", map[string]string{"name": w.name, "repository": repository, "reason": reason}) + } + return i18n.SharedFormat(lang, "desktop.branch.checkoutFailedIn", map[string]string{"name": w.reference.ShortName, "repository": repository, "reason": reason}) +} + +// succeeded words the action that ran in every repository. +func (w *commonWrite) succeeded(lang i18n.Language) string { + if w.operation == core.WorkspaceBranchCreate { + return i18n.SharedFormat(lang, "desktop.branch.commonCreated", map[string]string{"name": w.name}) + } + name := w.branch + if name == "" || name == "detached" { + name = w.reference.ShortName + } + return i18n.SharedFormat(lang, "desktop.branch.commonCheckedOut", map[string]string{"name": name}) +} + +// doneIDs are the IDs of the repositories the action's steps ran in, and of those among them that +// a rollback cannot return to their branch. +func (w *commonWrite) doneIDs() (ran, stuck []string) { + for _, step := range w.done { + ran = append(ran, step.Repository) + if step.Rollback == nil { + stuck = append(stuck, step.Repository) + } + } + return ran, stuck +} + +// loadCommonBranches reads the references of every repository of the folder in the background and +// asks Core which local and remote branches they all have. A folder with one repository, or a +// kernel without the workspace commands, has no common branch. +func (a *App) loadCommonBranches(p *project) { + cb := &a.branch.common + cb.gen++ + gen := cb.gen + brancher, ok := a.kernel.(workspaceBrancher) + repos := p.workspaceRepositories() + if !ok || !p.workspaceMode() || len(repos) < 2 { + *cb = commonBranches{gen: gen} + return + } + cb.loading = true + kernel := a.kernel + // Each repository's read is bounded on its own, so a folder of many is not cut short. + a.background(p, 0, func(ctx context.Context) func(*App) { + references, sections, err := readCommonReferences(ctx, kernel, brancher, repos) + return func(a *App) { + cb := &a.branch.common + if cb.gen != gen { + return + } + cb.loading, cb.loaded = false, true + cb.references, cb.sections, cb.err = references, sections, err + if err != nil { + a.backgroundFailed("git_workspace_common_references", err) + } + } + }) +} + +// readWorkspaceReferences reads the references of each repository as Core's workspace commands +// take them, each read bounded by gitTimeout. +func readWorkspaceReferences(ctx context.Context, kernel Kernel, repos []workspaceRepository) ([]core.WorkspaceRepositoryReferences, error) { + out := make([]core.WorkspaceRepositoryReferences, 0, len(repos)) + for _, repo := range repos { + readCtx, cancel := context.WithTimeout(ctx, gitTimeout) + refs, err := kernel.GitReferences(readCtx, repo.root) + cancel() + if err != nil { + return nil, err + } + out = append(out, core.WorkspaceRepositoryReferences{ID: repo.id, References: refs.References}) + } + return out, nil +} + +// readCommonReferences reads the references of repos, asks Core for the branches they all have, +// and has Core lay each section out as a folder tree with the common current branch first. +func readCommonReferences(ctx context.Context, kernel Kernel, brancher workspaceBrancher, repos []workspaceRepository) ([]core.WorkspaceRepositoryReferences, [2]logSection, error) { + var sections [2]logSection + references, err := readWorkspaceReferences(ctx, kernel, repos) + if err != nil { + return nil, sections, err + } + callCtx, cancel := context.WithTimeout(ctx, gitTimeout) + defer cancel() + common, err := brancher.GitWorkspaceCommonReferences(callCtx, references) + if err != nil { + return references, sections, err + } + prioritized := map[string]bool{} + for _, r := range common.Local { + if r.IsCurrent { + prioritized[r.ShortName] = true + } + } + for i, refs := range [2][]core.GitReference{common.Local, common.Remote} { + sections[i] = logSection{kind: commonSectionKeys[i], refs: refs} + if len(refs) == 0 { + continue + } + names := make([]string, len(refs)) + for j, r := range refs { + names[j] = r.ShortName + } + nodes, err := kernel.GitReferenceTree(callCtx, names, prioritized) + if err != nil { + return references, sections, err + } + sections[i].nodes = nodes + } + return references, sections, nil +} + +// checkoutCommon checks out the common branch r in every repository of the folder. A local branch +// every repository is on only says so. surface is where the user asked. +func (a *App) checkoutCommon(p *project, r core.GitReference, surface actionSurface) { + a.leaveBranches() + if r.Kind == "local" && r.IsCurrent { + a.notifyInfo(a.text.Branch.AlreadyOn(r.ShortName)) + return + } + a.performed("git.workspace.checkout", surface) + a.planCommon(p, commonWrite{operation: core.WorkspaceBranchCheckout, reference: r}) +} + +// beginCreateCommon opens the dialog that creates a branch from the common branch r in every +// repository of the folder. +func (a *App) beginCreateCommon(p *project, r core.GitReference) { a.openCreate(p, r, true) } + +// planCommon reads the references of every repository again, so that the plan starts from where +// they are now, asks Core for the plan of w, and runs it. A checkout first asks each repository +// which local changes it would overwrite; the conflict dialog then lists them all and its choice +// applies to every repository. +func (a *App) planCommon(p *project, w commonWrite) { + brancher, ok := a.kernel.(workspaceBrancher) + if !ok { + return + } + b := &a.branch + b.busy = true + w.repos = p.workspaceRepositories() + kernel := a.kernel + a.background(p, 0, func(ctx context.Context) func(*App) { + plan, blocking, err := planCommonWrite(ctx, kernel, brancher, &w) + return func(a *App) { + b := &a.branch + b.busy = false + if err != nil { + a.notifyError(w.planFailed(a.text.Branch, err.Error())) + a.operationFailed(w.operationName(), err) + return + } + w.plan = plan + if len(plan.Steps) == 0 { + // Every repository is on the branch already. + b.dialog, b.across = branchDialogNone, false + a.notifyInfo(a.text.Branch.AlreadyOn(w.reference.ShortName)) + return + } + if len(blocking) > 0 { + b.dialog, b.target, b.blocking, b.across, b.write = branchDialogConflict, w.reference, blocking, true, w + return + } + a.runCommon(p, w, core.CheckoutPlain) + } + }) +} + +// planCommonWrite asks Core for the plan of w from the references the repositories have now and, +// for a checkout, the paths it would overwrite in each repository it switches, relative to the +// project folder. +func planCommonWrite(ctx context.Context, kernel Kernel, brancher workspaceBrancher, w *commonWrite) (core.WorkspaceBranchPlan, []string, error) { + references, err := readWorkspaceReferences(ctx, kernel, w.repos) + if err != nil { + return core.WorkspaceBranchPlan{}, nil, err + } + planCtx, cancel := context.WithTimeout(ctx, gitTimeout) + plan, err := brancher.GitWorkspaceBranchPlan(planCtx, core.WorkspaceBranchPlanRequest{ + Operation: w.operation, Reference: w.reference.FullName, Name: w.name, Checkout: w.checkout, Repositories: references}) + cancel() + if err != nil || w.operation != core.WorkspaceBranchCheckout { + return plan, nil, err + } + var blocking []string + for _, step := range plan.Steps { + root, err := w.rootOf(step.Repository) + if err != nil { + return plan, nil, err + } + checkCtx, cancel := context.WithTimeout(ctx, gitTimeout) + paths, err := kernel.GitCheckoutPreflight(checkCtx, root, step.Reference) + cancel() + if err != nil { + return plan, nil, err + } + for _, file := range paths { + blocking = append(blocking, path.Join(step.Repository, file)) + } + } + return plan, blocking, nil +} + +// runCommon runs the steps of w's plan in the background, one repository after another, checking +// out in mode, and stops at the first that fails. The statuses and the log are read again after +// it. A failure after some steps ran opens the rollback dialog; one before any leaves the open +// dialog as it is, as the write of one repository does. +func (a *App) runCommon(p *project, w commonWrite, mode core.CheckoutMode) { + b := &a.branch + b.busy = true + if b.fromPopup { + a.showGitConsole("") + } + kernel := a.kernel + a.background(p, 0, func(ctx context.Context) func(*App) { + w := runCommonSteps(ctx, kernel, w, mode) + return func(a *App) { + b := &a.branch + b.busy = false + a.commonWritten(p) + lang := a.language() + switch { + case w.failed == "": + b.dialog, b.across = branchDialogNone, false + a.notifySuccess(w.succeeded(lang)) + case len(w.done) == 0: + a.notifyError(w.failedIn(lang)) + a.operationFailed(w.operationName(), w.err) + default: + a.operationFailed(w.operationName(), w.err) + b.dialog, b.across, b.write = branchDialogRollback, true, w + } + } + }) +} + +// runCommonSteps runs the steps of w's plan in order, each bounded by branchOperationTimeout, and +// returns w with the steps that ran and the one that failed. After a checkout that succeeded +// everywhere it reads the branch the first repository reached. +func runCommonSteps(ctx context.Context, kernel Kernel, w commonWrite, mode core.CheckoutMode) commonWrite { + w.done, w.failed, w.err, w.branch = nil, "", nil, "" + for _, step := range w.plan.Steps { + root, err := w.rootOf(step.Repository) + if err == nil { + stepCtx, cancel := context.WithTimeout(ctx, branchOperationTimeout) + switch w.operation { + case core.WorkspaceBranchCreate: + err = kernel.GitCreateBranch(stepCtx, root, w.name, step.Reference, w.checkout) + default: + err = kernel.GitCheckout(stepCtx, root, step.Reference, mode) + } + cancel() + } + if err != nil { + w.failed, w.err = step.Repository, err + return w + } + w.done = append(w.done, step) + } + if w.operation == core.WorkspaceBranchCheckout && len(w.done) > 0 { + if root, err := w.rootOf(w.done[0].Repository); err == nil { + statusCtx, cancel := context.WithTimeout(ctx, gitTimeout) + if status, err := kernel.GitStatus(core.WithQueryCategory(core.AutomaticRefresh(statusCtx), core.GitQueryReload), root); err == nil { + w.branch = status.Branch + } + cancel() + } + } + return w +} + +// commonWritten reads the statuses of the folder's repositories and the open log again after a +// write across them. +func (a *App) commonWritten(p *project) { + if p.git.isRepository() { + a.reloadGit(p) + } + a.loadNestedRepos(p) + if p.log.started { + a.loadLog(p) + } +} + +// rollbackCommon undoes the steps of the failed action that ran, the last one first, as IDEA's +// Rollback does, and reads the statuses again. A step that nothing can undo stays as it is. +func (a *App) rollbackCommon(p *project) { + b := &a.branch + if b.busy || b.dialog != branchDialogRollback { + return + } + w := b.write + a.performed("git.workspace.rollback", surfaceButton) + b.busy = true + kernel := a.kernel + a.background(p, 0, func(ctx context.Context) func(*App) { + rolled, failed, err := rollbackCommonSteps(ctx, kernel, &w) + return func(a *App) { + b := &a.branch + b.busy = false + b.dialog, b.across = branchDialogNone, false + a.commonWritten(p) + lang := a.language() + if err != nil { + repository := w.names(lang, []string{failed}) + a.notifyError(i18n.SharedFormat(lang, "desktop.branch.rollbackFailed", map[string]string{"repository": repository, "reason": err.Error()})) + a.operationFailed("git_workspace_rollback", err) + return + } + a.notifySuccess(i18n.SharedFormat(lang, "desktop.branch.rolledBack", map[string]string{"repositories": w.names(lang, rolled)})) + } + }) +} + +// rollbackCommonSteps runs the rollback of each step of w that ran, the last step first and each +// step's writes in order, and returns the IDs of the repositories it undid. It stops at the first +// write that fails and returns that repository's ID with the error. +func rollbackCommonSteps(ctx context.Context, kernel Kernel, w *commonWrite) (rolled []string, failed string, err error) { + for i := len(w.done) - 1; i >= 0; i-- { + step := w.done[i] + if step.Rollback == nil { + continue + } + root, err := w.rootOf(step.Repository) + if err != nil { + return rolled, step.Repository, err + } + for _, action := range step.Rollback { + writeCtx, cancel := context.WithTimeout(ctx, branchOperationTimeout) + switch action.Operation { + case core.WorkspaceRollbackCheckout: + err = kernel.GitCheckout(writeCtx, root, action.Reference, core.CheckoutPlain) + case core.WorkspaceRollbackDeleteBranch: + _, err = kernel.GitDeleteBranch(writeCtx, root, action.Reference) + default: + err = fmt.Errorf("unknown rollback operation %q", action.Operation) + } + cancel() + if err != nil { + return rolled, step.Repository, err + } + } + rolled = append(rolled, step.Repository) + } + return rolled, "", nil +} diff --git a/desktop/internal/workbench/branch_common_test.go b/desktop/internal/workbench/branch_common_test.go new file mode 100644 index 0000000000..90a017354c --- /dev/null +++ b/desktop/internal/workbench/branch_common_test.go @@ -0,0 +1,253 @@ +package workbench + +import ( + "context" + "errors" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// refusingKernel is Core's client that refuses every checkout and every new branch in the +// repository whose folder is named refused, as a repository Git cannot switch does. +type refusingKernel struct { + *gitKernel + refused string +} + +// errRefusedByTest is what refusingKernel answers for the refused repository. +var errRefusedByTest = errors.New("refused by the test") + +func (k *refusingKernel) GitCheckout(ctx context.Context, root string, reference core.GitReference, mode core.CheckoutMode) error { + if filepath.Base(root) == k.refused { + return errRefusedByTest + } + return k.gitKernel.GitCheckout(ctx, root, reference, mode) +} + +func (k *refusingKernel) GitCreateBranch(ctx context.Context, root, name string, from core.GitReference, checkout bool) error { + if filepath.Base(root) == k.refused { + return errRefusedByTest + } + return k.gitKernel.GitCreateBranch(ctx, root, name, from, checkout) +} + +// openCommonBranches opens the branch popup of the open folder and waits until Core listed the +// branches every repository has. +func (h *harness) openCommonBranches() *branchState { + h.t.Helper() + h.click(center(h.hitLabeled(h.app.text.Title.BranchMenu))) + b := &h.app.branch + h.settleUntil("the common branches", func() bool { return b.common.loaded }) + if b.common.err != nil { + h.t.Fatalf("reading the common branches: %v", b.common.err) + } + return b +} + +// shortNames are the short names of refs. +func shortNames(refs []core.GitReference) []string { + out := make([]string, len(refs)) + for i, r := range refs { + out[i] = r.ShortName + } + return out +} + +// branchesOf are the local branches of the repository in dir, sorted. +func branchesOf(t *testing.T, dir string) []string { + t.Helper() + return slices.Sorted(slices.Values(strings.Fields(gitRun(t, dir, "branch", "--format=%(refname:short)")))) +} + +// The popup of a folder holding repositories lists, under the repositories, the branches every one +// of them has, as IDEA's Common Local Branches; a checkout there switches every repository. +func TestWorkspaceBranchPopupChecksOutACommonBranchInEveryRepository(t *testing.T) { + parent := newWorkspaceFolder(t, "alpha", "beta") + alpha, beta := filepath.Join(parent, "alpha"), filepath.Join(parent, "beta") + gitRun(t, alpha, "branch", "feature") + gitRun(t, beta, "branch", "feature") + gitRun(t, alpha, "branch", "only-alpha") + h := newHarness(t, &gitKernel{Client: core.NewClient()}) + p := h.openWorkspaceFolder(parent) + b := h.openCommonBranches() + + common := shortNames(b.common.sections[0].refs) + if !slices.Contains(common, "feature") || !slices.Contains(common, "main") || slices.Contains(common, "only-alpha") { + t.Fatalf("common local branches = %v, want feature and main without only-alpha", common) + } + if current := b.common.current(); current.ShortName != "main" { + t.Fatalf("common current branch = %q, want main, which both repositories are on", current.ShortName) + } + lang := h.app.language() + if want := i18n.Shared(lang, "desktop.branch.commonLocal"); !h.shows(want) { + t.Fatalf("the popup does not show %q", want) + } + if h.shows("only-alpha") { + t.Fatal("the popup lists only-alpha, which beta does not have, among the common branches") + } + + h.click(center(h.branchRow("feature"))) + if b.menu != branchRowKey(commonSectionKeys[0], b.common.sections[0].refs[slices.Index(common, "feature")]) { + t.Fatalf("menu %q is open, want the common feature row's", b.menu) + } + h.clickNamed(h.app.text.Branch.Checkout) + for _, dir := range []string{alpha, beta} { + if got := currentBranch(t, dir); got != "feature" { + t.Fatalf("%s is on %q, want feature", filepath.Base(dir), got) + } + } + if want := i18n.SharedFormat(lang, "desktop.branch.commonCheckedOut", map[string]string{"name": "feature"}); h.app.notice != want { + t.Fatalf("notice = %q, want %q", h.app.notice, want) + } + alphaID, betaID := repositoryID(t, p, "alpha"), repositoryID(t, p, "beta") + h.settleUntil("both repositories' new branch", func() bool { + return p.branchOf(alphaID) == "feature" && p.branchOf(betaID) == "feature" + }) +} + +// A checkout of a common branch that fails in a repository after it switched another offers IDEA's +// Rollback, which returns the switched one to the branch it was on. +func TestWorkspaceCommonCheckoutRollsBackAfterAPartialFailure(t *testing.T) { + parent := newWorkspaceFolder(t, "alpha", "beta") + alpha, beta := filepath.Join(parent, "alpha"), filepath.Join(parent, "beta") + gitRun(t, alpha, "branch", "feature") + gitRun(t, beta, "branch", "feature") + h := newHarness(t, &refusingKernel{gitKernel: &gitKernel{Client: core.NewClient()}, refused: "beta"}) + h.openWorkspaceFolder(parent) + b := h.openCommonBranches() + + h.click(center(h.branchRow("feature"))) + h.clickNamed(h.app.text.Branch.Checkout) + if b.dialog != branchDialogRollback || !b.across { + t.Fatalf("after beta refused: dialog %v across %v, want the rollback dialog", b.dialog, b.across) + } + if got := currentBranch(t, alpha); got != "feature" { + t.Fatalf("alpha is on %q, want feature before the rollback", got) + } + if got := currentBranch(t, beta); got != "main" { + t.Fatalf("beta is on %q, want main, where its refused checkout left it", got) + } + lang := h.app.language() + failed := i18n.SharedFormat(lang, "desktop.branch.checkoutFailedIn", map[string]string{ + "name": "feature", "repository": "beta", "reason": errRefusedByTest.Error()}) + if !h.showsWrapped(failed) { + t.Fatalf("the rollback dialog does not say %q", failed) + } + + h.clickNamed(i18n.Shared(lang, "desktop.branch.rollbackButton")) + if got := currentBranch(t, alpha); got != "main" { + t.Fatalf("alpha is on %q after the rollback, want main", got) + } + if b.dialog != branchDialogNone || b.across { + t.Fatalf("after the rollback: dialog %v across %v", b.dialog, b.across) + } + if want := i18n.SharedFormat(lang, "desktop.branch.rolledBack", map[string]string{"repositories": "alpha"}); h.app.notice != want { + t.Fatalf("notice = %q, want %q", h.app.notice, want) + } +} + +// A new branch from a common branch is checked against the branches of every repository and created +// in all of them; when one refuses it, the rollback switches the others back and deletes it there. +func TestWorkspaceCommonNewBranchIsCreatedInEveryRepository(t *testing.T) { + for _, refused := range []string{"", "beta"} { + t.Run("refused="+refused, func(t *testing.T) { + parent := newWorkspaceFolder(t, "alpha", "beta") + alpha, beta := filepath.Join(parent, "alpha"), filepath.Join(parent, "beta") + gitRun(t, alpha, "branch", "only-alpha") + h := newHarness(t, &refusingKernel{gitKernel: &gitKernel{Client: core.NewClient()}, refused: refused}) + h.openWorkspaceFolder(parent) + b := h.openCommonBranches() + text, lang := h.app.text.Branch, h.app.language() + + h.click(center(h.branchRow("main"))) + if _, ok := h.findPageHit(text.Checkout); ok { + t.Fatal("the menu of main, which every repository is on, offers a checkout") + } + h.clickNamed(text.NewBranchFrom("main")) + if b.dialog != branchDialogCreate || !b.across { + t.Fatalf("after New Branch from main: dialog %v across %v", b.dialog, b.across) + } + if want := i18n.SharedFormat(lang, "desktop.branch.createFromInAll", map[string]string{"name": "main"}); !h.showsWrapped(want) { + t.Fatalf("the dialog does not say %q", want) + } + clear := func() { b.name.SetText("") } + h.typeInto(text.BranchName, clear, "only-alpha") + if want := text.NameExists("only-alpha"); !h.shows(want) { + t.Fatalf("the dialog does not say %q for a branch alpha has", want) + } + h.typeInto(text.BranchName, clear, "topic") + h.clickNamed(text.Create) + + if refused == "" { + for _, dir := range []string{alpha, beta} { + if got := currentBranch(t, dir); got != "topic" { + t.Fatalf("%s is on %q, want the new topic", filepath.Base(dir), got) + } + } + if want := i18n.SharedFormat(lang, "desktop.branch.commonCreated", map[string]string{"name": "topic"}); h.app.notice != want { + t.Fatalf("notice = %q, want %q", h.app.notice, want) + } + return + } + if b.dialog != branchDialogRollback { + t.Fatalf("after beta refused: dialog %v, want the rollback dialog", b.dialog) + } + h.clickNamed(i18n.Shared(lang, "desktop.branch.rollbackButton")) + if got := currentBranch(t, alpha); got != "main" { + t.Fatalf("alpha is on %q after the rollback, want main", got) + } + if got := branchesOf(t, alpha); !slices.Equal(got, []string{"main", "only-alpha"}) { + t.Fatalf("alpha has %v after the rollback, want topic deleted", got) + } + }) + } +} + +// A checkout of a common branch that would overwrite local changes in a repository lists them under +// that repository's ID, and the choice of the conflict dialog applies to every repository. +func TestWorkspaceCommonCheckoutListsTheBlockingChangesOfEveryRepository(t *testing.T) { + parent := newWorkspaceFolder(t, "alpha", "beta") + alpha, beta := filepath.Join(parent, "alpha"), filepath.Join(parent, "beta") + gitRun(t, alpha, "branch", "feature") + // beta's feature changes beta.txt, which beta has modified. + gitRun(t, beta, "stash", "push", "-m", "keep") + gitRun(t, beta, "checkout", "-b", "feature") + if err := os.WriteFile(filepath.Join(beta, "beta.txt"), []byte("feature\n"), 0o600); err != nil { + t.Fatal(err) + } + gitRun(t, beta, "commit", "-am", "feature beta") + gitRun(t, beta, "checkout", "main") + gitRun(t, beta, "stash", "pop") + h := newHarness(t, &gitKernel{Client: core.NewClient()}) + p := h.openWorkspaceFolder(parent) + b := h.openCommonBranches() + + h.click(center(h.branchRow("feature"))) + h.clickNamed(h.app.text.Branch.Checkout) + betaID := repositoryID(t, p, "beta") + if b.dialog != branchDialogConflict || !b.across { + t.Fatalf("dialog %v across %v, want the conflict dialog of the common checkout", b.dialog, b.across) + } + if want := []string{betaID + "/beta.txt"}; !slices.Equal(b.blocking, want) { + t.Fatalf("blocking paths = %v, want %v", b.blocking, want) + } + if got := currentBranch(t, alpha); got != "main" { + t.Fatalf("alpha is on %q, want main while the dialog asks", got) + } + + h.clickNamed(h.app.text.Branch.ForceCheckout) + for _, dir := range []string{alpha, beta} { + if got := currentBranch(t, dir); got != "feature" { + t.Fatalf("%s is on %q, want feature", filepath.Base(dir), got) + } + } + if b.dialog != branchDialogNone || b.across { + t.Fatalf("after the forced checkout: dialog %v across %v", b.dialog, b.across) + } +} diff --git a/desktop/internal/workbench/branch_common_view.go b/desktop/internal/workbench/branch_common_view.go new file mode 100644 index 0000000000..66161c8f2f --- /dev/null +++ b/desktop/internal/workbench/branch_common_view.go @@ -0,0 +1,110 @@ +package workbench + +import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/ui" +) + +// This file declares the common branches of the popup of a project folder with several +// repositories and the rollback dialog of the actions on them; branch_common.go reads them and +// runs the actions. + +// drawCommonBranches declares IDEA's Common Local Branches and Common Remote Branches under the +// repositories of the folder's popup, filtered by query as one repository's sections are. Their +// rows' menus act in every repository. Nothing shows before the first read answered or when no +// branch is common. +func (a *App) drawCommonBranches(c ui.C, p *project, t i18n.BranchMessages, query string) { + b := &a.branch + cb := &b.common + if cb.err != nil && !cb.loading { + ui.Divider(c) + ui.Paragraph(c, t.LoadFailed(cb.err.Error()), 4).Color(a.colors.Subtle).PadX(chromeEdge) + return + } + if !cb.loaded { + return + } + var shown [2][]core.GitReference + listed := false + for i := range cb.sections { + shown[i] = cb.sections[i].refs + if query != "" { + shown[i] = matchingReferences(shown[i], query) + } + listed = listed || len(shown[i]) > 0 + } + if !listed { + return + } + ui.Divider(c) + lang := a.language() + labels := [2]string{i18n.Shared(lang, "desktop.branch.commonLocal"), i18n.Shared(lang, "desktop.branch.commonRemote")} + current := cb.current() + for i, key := range commonSectionKeys { + refs := shown[i] + if len(refs) == 0 { + continue + } + collapsed := query == "" && b.collapsed[key] + if a.drawBranchSection(c, key, labels[i], collapsed, query == "") { + c.After(func() { b.collapsed[key] = !b.collapsed[key] }) + } + switch { + case collapsed: + case query != "": + for _, r := range refs { + a.drawBranchRow(c, p, key, r, r.ShortName, 1, r.FullName == current.FullName) + } + default: + s := &cb.sections[i] + a.drawBranchNodes(c, p, s, key, s.nodes, 1, current) + } + } +} + +// drawCommonBranchRowMenu declares the items of the menu of common branch r: a new branch from it +// and its checkout, both in every repository, in the order IDEA lists them. The local branch every +// repository is on is not checked out again. +func (a *App) drawCommonBranchRowMenu(c ui.C, menu *ui.MenuItems, p *project, r core.GitReference, current bool) { + b, t := &a.branch, a.text.Branch + busy := b.busy || p.log.sync.busy + if menu.Item(t.NewBranchFrom(r.ShortName)).Clicked() { + c.After(func() { a.beginCreateCommon(p, r) }) + } + if !current { + menu.Separator() + if menu.Item(t.Checkout).Disabled(busy).Clicked() { + c.After(func() { a.checkoutCommon(p, r, surfaceMenu) }) + } + } +} + +// drawBranchRollbackDialog declares the dialog of an action on a common branch that failed after +// it ran in some repositories: why it failed, where it ran, which of those a rollback cannot return +// to their branch, and the choice IDEA offers. The focus starts on Don't Roll Back, the first +// control, so Enter changes nothing. +func (a *App) drawBranchRollbackDialog(c ui.C, p *project) { + b := &a.branch + w := &b.write + lang := a.language() + ran, stuck := w.doneIDs() + undoable := len(stuck) < len(ran) + a.branchDialogOf(c, i18n.Shared(lang, "desktop.branch.rollbackTitle"), w.failedIn(lang), func() { + ui.Column(c).FillWidth().Gap(8).Children(func() { + ui.Paragraph(c, i18n.SharedFormat(lang, "desktop.branch.rollbackPrompt", map[string]string{"repositories": w.names(lang, ran)}), 4). + Color(a.colors.Text) + if len(stuck) > 0 { + ui.Paragraph(c, i18n.SharedFormat(lang, "desktop.branch.rollbackImpossible", map[string]string{"repositories": w.names(lang, stuck)}), 3). + FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + } + }) + }, func() { + if ui.Button(c, i18n.Shared(lang, "desktop.branch.keepButton")).Outline().Clicked() { + c.After(a.cancelBranchDialog) + } + if ui.Button(c, i18n.Shared(lang, "desktop.branch.rollbackButton")).Disabled(b.busy || !undoable).Clicked() { + c.After(func() { a.rollbackCommon(p) }) + } + }) +} diff --git a/desktop/internal/workbench/branch_view.go b/desktop/internal/workbench/branch_view.go index 54592da3db..b1e954ba11 100644 --- a/desktop/internal/workbench/branch_view.go +++ b/desktop/internal/workbench/branch_view.go @@ -139,10 +139,11 @@ func (a *App) drawBranchReferences(c ui.C, p *project, t i18n.BranchMessages, qu } // drawWorkspaceBranchPanel declares the popup of a project folder with several repositories, as -// IDEA's: the search field, the commit of the Commit tool window, which spans every repository, and -// a row per repository in Core's order with its color, its name and the branch it is on. A click on -// a row opens the repository's panel beside it with its actions and references; every write there -// acts in that repository alone. +// IDEA's: the search field, the commit of the Commit tool window, which spans every repository, a +// row per repository in Core's order with its color, its name and the branch it is on, and the +// branches every repository has (drawCommonBranches). A click on a repository's row opens its panel +// beside it with its actions and references; every write there acts in that repository alone, and +// every write on a common branch acts in all of them. func (a *App) drawWorkspaceBranchPanel(c ui.C, p *project, t i18n.BranchMessages) { b := &a.branch query := branchQuery(b) @@ -157,6 +158,7 @@ func (a *App) drawWorkspaceBranchPanel(c ui.C, p *project, t i18n.BranchMessages for _, repo := range p.workspaceRepositories() { a.drawWorkspaceBranchRepo(c, p, t, repo, query) } + a.drawCommonBranches(c, p, t, query) }) } @@ -427,7 +429,8 @@ func branchTracking(r core.GitReference) string { // drawBranchRow declares the row of reference r in section key at depth, named label: its // mark, its name, how far it and its upstream are apart, the upstream on the right, and the -// chevron of its menu. A click opens the menu of the row beside it. +// chevron of its menu. A click opens the menu of the row beside it: drawCommonBranchRowMenu for a +// row of a common section, whose actions run in every repository, drawBranchRowMenu otherwise. func (a *App) drawBranchRow(c ui.C, p *project, section string, r core.GitReference, label string, depth int, current bool) { b, t := &a.branch, a.text.Branch rowKey := branchRowKey(section, r) @@ -478,7 +481,11 @@ func (a *App) drawBranchRow(c ui.C, p *project, section string, r core.GitRefere } ui.Menu(c, row, &open, func(menu *ui.MenuItems) { menu.Beside() - a.drawBranchRowMenu(c, menu, p, r, current) + if strings.HasPrefix(section, commonSectionPrefix) { + a.drawCommonBranchRowMenu(c, menu, p, r, current) + } else { + a.drawBranchRowMenu(c, menu, p, r, current) + } }) if !open { b.menu = "" @@ -564,6 +571,8 @@ func (a *App) drawBranchDialog(c ui.C, p *project) { a.drawTagDialog(c, p) case branchDialogTagDelete: a.drawTagDeleteDialog(c, p) + case branchDialogRollback: + a.drawBranchRollbackDialog(c, p) } } @@ -585,6 +594,9 @@ func (a *App) drawBranchNameDialog(c ui.C, p *project) { title, description, confirm := t.RenameTitle, t.RenameFrom(b.target.ShortName), t.RenameButton if creating { title, description, confirm = t.NewBranchTitle, t.CreateFrom(b.target.ShortName), t.Create + if b.across { + description = i18n.SharedFormat(a.language(), "desktop.branch.createFromInAll", map[string]string{"name": b.target.ShortName}) + } } problem := a.branchNameError() name := b.preview.CleanedName diff --git a/desktop/internal/workbench/gitlog.go b/desktop/internal/workbench/gitlog.go index 7024f38231..b91ed23720 100644 --- a/desktop/internal/workbench/gitlog.go +++ b/desktop/internal/workbench/gitlog.go @@ -621,10 +621,17 @@ func (in logProjection) run(ctx context.Context, kernel Kernel, root string, dat if window == nil { window = commits } - graph, err := kernel.GitGraph(ctx, core.GraphRequest{ + request := core.GraphRequest{ Commits: commits, RemoteNames: in.remotes, RepositoryCommits: window, - VisibleHashes: visible, Expanded: in.expanded, CurrentBranch: in.current, - }) + VisibleHashes: visible, Expanded: in.expanded, + } + if in.origins != nil { + // A merged list marks each repository's own current branch, as loadLogRepos does. + request.CheckedOutHeads = true + } else { + request.CurrentBranch = in.current + } + graph, err := kernel.GitGraph(ctx, request) return graph, in.pathFiles, err } diff --git a/desktop/internal/workbench/gitlog_multi.go b/desktop/internal/workbench/gitlog_multi.go index e20f9056a9..ffc347e1a7 100644 --- a/desktop/internal/workbench/gitlog_multi.go +++ b/desktop/internal/workbench/gitlog_multi.go @@ -193,8 +193,11 @@ func (a *App) loadLogRepos(p *project, gen int) { } if err == nil { input := graphInput(commits, origins) + // Each repository's own current branch gets the background, as IDEA reads the branch of + // each commit's root. graph, err = kernel.GitGraph(ctx, core.GraphRequest{ Commits: input, RemoteNames: walkRemotes(walks), RepositoryCommits: input, Expanded: expanded, + CheckedOutHeads: true, }) } return func(a *App) { diff --git a/desktop/internal/workbench/gitlog_multi_test.go b/desktop/internal/workbench/gitlog_multi_test.go index c9d6dde0c2..d57fb76ea0 100644 --- a/desktop/internal/workbench/gitlog_multi_test.go +++ b/desktop/internal/workbench/gitlog_multi_test.go @@ -85,6 +85,13 @@ func TestWorkspaceLogWalksSeveralRepositoriesTogether(t *testing.T) { if !repos[alphaID] || !repos[betaID] || betaRow < 0 { t.Fatalf("the merged rows belong to %v, want alpha and beta", repos) } + // Each repository's checked-out branch has the current-branch background, as in IDEA, not only + // the branch of the repository the log walked first. + for _, row := range p.log.graph.Rows { + if !p.log.currentRows[row.CommitHash] { + t.Fatalf("commit %s of %s has no current-branch background in the merged list", row.CommitHash, p.logCommitRepo(row.CommitHash)) + } + } root, _, hashes := h.app.logMenuTarget(p, betaRow) if filepath.Base(root) != "beta" || len(hashes) != 1 { diff --git a/desktop/internal/workbench/workspace_repositories_visual_test.go b/desktop/internal/workbench/workspace_repositories_visual_test.go index 2f5331613e..e1fa4a106d 100644 --- a/desktop/internal/workbench/workspace_repositories_visual_test.go +++ b/desktop/internal/workbench/workspace_repositories_visual_test.go @@ -18,8 +18,10 @@ import ( // holds three: the branch popup listing them with one's panel open beside its row, the Git log // with the color strip of the repository it walks and each repository's own sections in the // reference pane, the Paths filter's Roots, the repository list behind the name after the filter -// chips, the log of two repositories merged by date, the Commit window's groups, and the Push -// Commits dialog Commit and Push opens on the three repositories. +// chips, the log of two repositories merged by date, the Commit window's groups, the Push Commits +// dialog Commit and Push opens on the three repositories, the branches all three have under the +// repositories of the popup, and the rollback IDEA offers when a checkout of one of them fails in a +// repository after it switched another. func TestVisualWorkspaceRepositories(t *testing.T) { out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") if out == "" { @@ -29,7 +31,7 @@ func TestVisualWorkspaceRepositories(t *testing.T) { t.Fatal(err) } for _, look := range []struct{ theme, language string }{{"dark", "zh-Hans"}, {"light", "en"}} { - for _, scene := range []string{"branch-popup", "git-log", "log-roots", "log-choose", "log-merged", "log-more", "commit-groups", "push-commits"} { + for _, scene := range []string{"branch-popup", "git-log", "log-roots", "log-choose", "log-merged", "log-more", "commit-groups", "push-commits", "branch-common", "branch-rollback"} { t.Run(scene+"-"+look.theme, func(t *testing.T) { // Fixed dates, so the merged log interleaves the two repositories the same way // on every run. @@ -53,12 +55,27 @@ func TestVisualWorkspaceRepositories(t *testing.T) { gitRun(t, frontend, "switch", "-c", "develop") commit(frontend, "Lay out the dashboard", "2026-11-10T14:00:00") commit(frontend, "Tune the dark palette", "2026-11-12T11:20:00") + var kernel Kernel = gitKernel{core.NewClient()} + if scene == "branch-common" || scene == "branch-rollback" { + // develop and feature/login are in all three repositories; frontend is on + // develop, the others on main. + shared := filepath.Join(parent, "shared") + gitRun(t, backend, "branch", "develop") + gitRun(t, shared, "branch", "develop") + gitRun(t, frontend, "branch", "feature/login") + gitRun(t, shared, "branch", "feature/login") + } + if scene == "branch-rollback" { + // shared refuses the checkout, as a repository Git cannot switch does, after + // backend switched. + kernel = &refusingKernel{gitKernel: &gitKernel{core.NewClient()}, refused: "shared"} + } prefs := store.At(t.TempDir()) if err := prefs.Save(settingsFile, settings{Theme: themeChoice(look.theme), Language: look.language, DisableAutoSave: true}); err != nil { t.Fatal(err) } var session *headless.Session - h := newHarnessWithDriver(t, Options{Kernel: gitKernel{core.NewClient()}, Store: prefs, Languages: []string{look.language}}, func(config app.Config) (*app.Driver, func(), error) { + h := newHarnessWithDriver(t, Options{Kernel: kernel, Store: prefs, Languages: []string{look.language}}, func(config app.Config) (*app.Driver, func(), error) { config.Width, config.Height = 1200, 760 var err error session, err = headless.Open(config, nil, headless.Options{}) @@ -73,6 +90,13 @@ func TestVisualWorkspaceRepositories(t *testing.T) { h.click(center(h.hitLabeled(h.app.text.Title.BranchMenu))) label := i18n.SharedFormat(h.app.language(), "desktop.branch.repositoryPanel", map[string]string{"repository": "frontend", "branch": "develop"}) h.click(center(h.popupHit(label))) + case "branch-common", "branch-rollback": + h.openCommonBranches() + if scene == "branch-rollback" { + h.click(center(h.branchRow("develop"))) + h.clickNamed(h.app.text.Branch.Checkout) + h.settleUntil("the rollback dialog", func() bool { return h.app.branch.dialog == branchDialogRollback }) + } case "git-log", "log-roots", "log-choose", "log-merged", "log-more": h.app.layout.gitTab = gitTabLog if !h.app.chrome.isOpen(catalogIndex[itemGit]) { diff --git a/docs/assets/workspace-repositories/README.md b/docs/assets/workspace-repositories/README.md index ad9974d5fa..bdd1fa2ffa 100644 --- a/docs/assets/workspace-repositories/README.md +++ b/docs/assets/workspace-repositories/README.md @@ -6,11 +6,13 @@ | 场景 | 深色中文 | 浅色英文 | | --- | --- | --- | -| 标题栏分支入口:先列出“提交…”,再按 IDEA 的样式逐行列出仓库,每行有颜色方块、仓库名、右侧的当前分支和 ›;点击 frontend 后,面板在这一行旁边展开,列出该仓库的分支操作和“frontend 中的最近分支 / 本地分支 / 远程分支 / 标签”,在面板里新建、检出等操作只作用于 frontend | [截图](workspace-branch-popup-dark.png) | [截图](workspace-branch-popup-light.png) | +| 标题栏分支入口:先列出“提交…”,再按 IDEA 的样式逐行列出仓库,每行有颜色方块、仓库名、右侧的当前分支和 ›;点击 frontend 后,面板在这一行旁边展开,列出该仓库的分支操作和“frontend 中的最近分支 / 本地分支 / 远程分支 / 标签”,在面板里新建、检出等操作只作用于 frontend;仓库列表下方是三个仓库共有的分支(下一行) | [截图](workspace-branch-popup-dark.png) | [截图](workspace-branch-popup-light.png) | +| 标题栏分支入口的共同分支:三个仓库都有 develop、main 和 feature/login,仓库列表下方按 IDEA 的 Common Local Branches 列出“共同本地分支”(feature/login 收在 feature 分组里);三个仓库不在同一分支上,所以没有当前分支标记;仓库没有远程,不显示“共同远程分支”。在这里检出或新建分支会依次作用于每个仓库 | [截图](workspace-branch-common-dark.png) | [截图](workspace-branch-common-light.png) | +| 共同分支只在部分仓库完成:在共同本地分支 develop 上检出,frontend 已在 develop 被跳过,backend 已切换,shared 失败(测试让 shared 拒绝检出);对话框说明在哪个仓库因何失败、已在哪些仓库完成,“不回滚”保持现状,“回滚”让 backend 回到 main。下方 Git 控制台开头的红色 for-each-ref 报错是打开非仓库文件夹时既有的问题,与本场景无关 | [截图](workspace-branch-rollback-dark.png) | [截图](workspace-branch-rollback-light.png) | | Git 日志:文件夹本身不是仓库,Core 选第一个嵌套仓库 backend;提交行最左侧是 backend 的颜色条;筛选栏“路径”之后是仓库名,用仓库颜色显示,带下拉箭头,点击可选择仓库;左侧引用面板每个仓库一个节点,节点下各有自己的“本地 / 远程 / 标签” | [截图](workspace-git-log-dark.png) | [截图](workspace-git-log-light.png) | | 路径筛选器下方的“仓库根目录”:按颜色列出三个仓库并勾选正在查看的一个;勾选或取消勾选即改变日志查看的仓库 | [截图](workspace-log-roots-dark.png) | [截图](workspace-log-roots-light.png) | | 点击筛选栏里的仓库名:弹出同一份仓库列表,可多选 | [截图](workspace-log-choose-dark.png) | [截图](workspace-log-choose-light.png) | -| 勾选 backend 和 frontend:Core 把两个仓库的历史按提交时间混排成一个列表,各仓库内部保持 Git 顺序;每行左侧是所属仓库的颜色条,两个仓库的图互不相连;筛选栏的仓库名变成两个颜色方块和“2 个仓库” | [截图](workspace-log-merged-dark.png) | [截图](workspace-log-merged-light.png) | +| 勾选 backend 和 frontend:Core 把两个仓库的历史按提交时间混排成一个列表,各仓库内部保持 Git 顺序;每行左侧是所属仓库的颜色条,两个仓库的图互不相连;筛选栏的仓库名变成两个颜色方块和“2 个仓库”;backend 的 main 和 frontend 的 develop 各自检出,两个仓库当前分支上的提交都有当前分支底色 | [截图](workspace-log-merged-dark.png) | [截图](workspace-log-merged-light.png) | | Git 日志筛选栏放不下全部视图按钮时:筛选项和仓库名完整保留,放不下的按钮收进末尾的“更多操作”(…)菜单,每项带图标,“显示提交详情”等开关项开启时打勾;全部收进菜单后文本筛选框再缩窄,最后才裁掉筛选项 | [截图](workspace-log-more-dark.png) | [截图](workspace-log-more-light.png) | | 提交窗口:按仓库分组,每组有暂存复选框、颜色、文件数和该仓库当前分支的标签,组内没有单独的提交按钮;顶部复选框按 Core 的计划暂存全部仓库;状态栏统计所有仓库的更改数 | [截图](workspace-commit-groups-dark.png) | [截图](workspace-commit-groups-light.png) | | “提交并推送”提交完成后打开的“推送提交”对话框:左侧每个仓库一行,有勾选框、仓库名和“分支 → origin : 分支”,下面列出待推送的提交;backend 的远程缺最后几次提交,frontend 推送时新建远程分支,shared 没有远程,显示“定义远程”且不能勾选;右侧是选中提交的变更文件;底部是“推送标记(T)”和“当前分支 / 所有”;推送按 Core 的顺序进行,子模块先于记录它的父仓库 | [截图](workspace-push-commits-dark.png) | [截图](workspace-push-commits-light.png) | diff --git a/docs/assets/workspace-repositories/workspace-branch-common-dark.png b/docs/assets/workspace-repositories/workspace-branch-common-dark.png new file mode 100644 index 0000000000..a8a690ba61 Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-branch-common-dark.png differ diff --git a/docs/assets/workspace-repositories/workspace-branch-common-light.png b/docs/assets/workspace-repositories/workspace-branch-common-light.png new file mode 100644 index 0000000000..baa24c087b Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-branch-common-light.png differ diff --git a/docs/assets/workspace-repositories/workspace-branch-popup-dark.png b/docs/assets/workspace-repositories/workspace-branch-popup-dark.png index 6c8e5f8e7c..a6d8863075 100644 Binary files a/docs/assets/workspace-repositories/workspace-branch-popup-dark.png and b/docs/assets/workspace-repositories/workspace-branch-popup-dark.png differ diff --git a/docs/assets/workspace-repositories/workspace-branch-popup-light.png b/docs/assets/workspace-repositories/workspace-branch-popup-light.png index a2e5e74f30..6d49d8958d 100644 Binary files a/docs/assets/workspace-repositories/workspace-branch-popup-light.png and b/docs/assets/workspace-repositories/workspace-branch-popup-light.png differ diff --git a/docs/assets/workspace-repositories/workspace-branch-rollback-dark.png b/docs/assets/workspace-repositories/workspace-branch-rollback-dark.png new file mode 100644 index 0000000000..1e2615c35f Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-branch-rollback-dark.png differ diff --git a/docs/assets/workspace-repositories/workspace-branch-rollback-light.png b/docs/assets/workspace-repositories/workspace-branch-rollback-light.png new file mode 100644 index 0000000000..75d6b64077 Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-branch-rollback-light.png differ diff --git a/docs/assets/workspace-repositories/workspace-log-merged-dark.png b/docs/assets/workspace-repositories/workspace-log-merged-dark.png index 4c25b5eb8f..afad09507d 100644 Binary files a/docs/assets/workspace-repositories/workspace-log-merged-dark.png and b/docs/assets/workspace-repositories/workspace-log-merged-dark.png differ diff --git a/docs/assets/workspace-repositories/workspace-log-merged-light.png b/docs/assets/workspace-repositories/workspace-log-merged-light.png index 38476c12dc..349b3086d4 100644 Binary files a/docs/assets/workspace-repositories/workspace-log-merged-light.png and b/docs/assets/workspace-repositories/workspace-log-merged-light.png differ diff --git a/docs/viva-migration.md b/docs/viva-migration.md index f148e5fdce..ec3b8858b8 100644 --- a/docs/viva-migration.md +++ b/docs/viva-migration.md @@ -302,7 +302,7 @@ | `git-local-changelists` | 本地 ChangeList | 必须迁移 | 实现/实现 | 部分 | changelists.go、changelists_view.go、core/changelists.go;多选/目录批量移动未做 | | `git-metadata-observation` | Git 元数据变化观察与刷新 | 必须迁移 | 实现/实现 | 部分 | `workbench/git_observation.go` | | `git-multi-repository-change-groups` | 多仓库变更折叠分组 | 必须迁移 | 实现/实现 | 部分 | core/workspace.go、nested_repos.go、nested_repos_view.go:提交窗口按 Core 的 GroupWorkspaceChanges 按仓库折叠分组,顶部复选框按 Core 的 StageAll 计划暂存全部仓库,状态栏统计所有仓库的更改数;文件夹本身不是 Git 仓库时同样分组 | -| `git-multi-repository-references` | 多仓库引用面板 | 必须迁移 | 实现/实现 | 部分 | branch_view.go、gitlog_popover_view.go、gitgraph.go:分支入口按 IDEA 样式逐行列出仓库,点一行在旁边展开该仓库的分支面板,写操作只作用于该仓库;Git Log 行左侧是仓库颜色条,路径筛选器下方“仓库根目录”切换日志的仓库(截图见 `docs/assets/workspace-repositories/`);Common Local / Remote Branches、聚合日志、跨仓库 Update / Push 未做 | +| `git-multi-repository-references` | 多仓库引用面板 | 必须迁移 | 实现/实现 | 部分 | branch_view.go、gitlog_popover_view.go、gitgraph.go:分支入口按 IDEA 样式逐行列出仓库,点一行在旁边展开该仓库的分支面板,写操作只作用于该仓库;Git Log 行左侧是仓库颜色条,路径筛选器下方“仓库根目录”切换日志的仓库(截图见 `docs/assets/workspace-repositories/`);仓库列表下方是 Common Local / Remote Branches,检出和新建分支作用于所有仓库,部分仓库失败时可回滚(branch_common.go);勾选多个仓库时日志按提交时间混排(gitlog_multi.go);共同分支上的合并、删除、推送等其他操作和跨仓库 Update / Push 未做 | | `git-rebase-stash` | Rebase 与 Stash | 必须迁移 | 实现/实现 | 部分 | stash.go、stash_view.go:Commit 工具窗口暂存页可查看、应用、弹出、删除与新建 stash;拉取分叉时可选变基(gitsync.go);独立 Rebase(含交互式)未找到 | | `git-repository-discovery` | 仓库自动发现排除隐藏目录与构建缓存 | 必须迁移 | 实现/实现 | 部分 | core/repository_colors.go、gitmetadata/ | | `git-status-colors-idea-alignment` | Windows 默认主题 Git 状态配色与 IDEA 对齐(修改/… | 必须迁移 | 专属/实现 | 部分 | theme.go 新增 GitModified/GitModifiedStaged/GitRenamed/GitAdded/GitFileDeleted/GitUntracked 与 Gutter* 令牌(IDEA expUI 明暗值);commit_view.go、gitlog_details_view.go 统一走 palette.gitStatusColor,删除文件改灰、未跟踪改暖红、暂存修改用浅蓝;documents.go 的 gutter 改用浅色令牌。未做:项目文件树与 Git Log 文件树尚未按状态着色(filetree 缺少状态字段) | diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 67bac14277..121ee16874 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -27,6 +27,15 @@ native_path() { fi } +# Lithe-core-rust branch feat/workspace-common-references at 5c48a67 (#75, merged with main at +# 6f5fbcc, #87 on top of #90 and #89): git.workspaceCommonReferences takes each repository's +# git.references entries unchanged and returns the branches every repository has in that entry +# shape, current when every repository has it checked out, with the upstream they share and ahead +# and behind added up; git.workspaceBranchPlan plans a checkout or a new branch on such a branch +# across the repositories, skipping the ones already on it, with the writes that roll each step +# back; and git.graphProjection checkedOutHeads marks the commits of every repository's +# checked-out branch, refusing currentBranch beside it (#2013). Switch to main's commit once #75 +# is squash-merged. # Lithe-core-rust main at d833d6a, #89 squash-merged (on top of bb4832e, #88): buildProviders 1 # adds runs with entrypoints: true; build.runEntrypointsPlan and build.decodeRunEntrypoints ask a # provider for the entrypoints of one source file, prepareRunPlan takes an entrypoint run without a @@ -214,7 +223,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="d833d6a71dfeaa5eda39d23f6a3a1a9ee29ff9ed" +PINNED_CORE_REVISION="5c48a6727fb0d22713a3f067a6f452edf41fad3a" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index c4ff734a8f..880f3ff2e2 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -754,12 +754,19 @@ "desktop.branch.checkedOut": "Checked out '{name}'", "desktop.branch.checkoutAfter": "Checkout branch after creation", "desktop.branch.checkoutFailed": "Failed to check out: {reason}", + "desktop.branch.checkoutFailedIn": "Failed to check out '{name}' in {repository}: {reason}", "desktop.branch.checkoutRevision": "Checkout Tag or Revision…", + "desktop.branch.commonCheckedOut": "Checked out '{name}' in every repository", + "desktop.branch.commonCreated": "Created branch '{name}' in every repository", + "desktop.branch.commonLocal": "Common Local Branches", + "desktop.branch.commonRemote": "Common Remote Branches", "desktop.branch.conflictHint": "Smart Checkout stashes your changes, switches branch, then restores them. Force Checkout switches and discards them.", "desktop.branch.conflictPrompt": "Your changes to these files conflict with '{name}':", "desktop.branch.conflictTitle": "Local changes would be overwritten", "desktop.branch.createFailed": "Failed to create branch: {reason}", + "desktop.branch.createFailedIn": "Failed to create branch '{name}' in {repository}: {reason}", "desktop.branch.createFrom": "Create from '{name}'.", + "desktop.branch.createFromInAll": "Create from '{name}' in every repository.", "desktop.branch.created": "Created branch '{name}'", "desktop.branch.current": "Current branch", "desktop.branch.deleteFailed": "Failed to delete branch: {reason}", @@ -769,6 +776,7 @@ "desktop.branch.detached": "Checked out '{revision}' in detached HEAD state", "desktop.branch.detachedNote": "The repository will be opened in detached HEAD state.", "desktop.branch.forceCheckout": "Force Checkout", + "desktop.branch.keepButton": "Don't Roll Back", "desktop.branch.loadFailed": "Failed to load branches: {reason}", "desktop.branch.loading": "Loading branches…", "desktop.branch.localIn": "Local Branches in {repository}", @@ -783,9 +791,16 @@ "desktop.branch.renameTitle": "Rename Branch", "desktop.branch.renamed": "Renamed the branch to '{name}'", "desktop.branch.repositoryPanel": "{repository} on {branch}", + "desktop.branch.repositorySeparator": ", ", "desktop.branch.revision": "Tag or revision", "desktop.branch.revisionPrompt": "Enter a tag name, branch name, commit hash, or other Git revision.", "desktop.branch.revisionTitle": "Checkout Tag or Revision", + "desktop.branch.rollbackButton": "Roll Back", + "desktop.branch.rollbackFailed": "Rollback failed in {repository}: {reason}", + "desktop.branch.rollbackImpossible": "{repositories} were on no branch before, so they cannot be rolled back.", + "desktop.branch.rollbackPrompt": "It already succeeded in {repositories}. Roll back to return every repository to the branch it was on.", + "desktop.branch.rollbackTitle": "Completed in Some Repositories Only", + "desktop.branch.rolledBack": "Rolled back {repositories}", "desktop.branch.rowMenu": "{name} actions", "desktop.branch.search": "Search for branches and actions", "desktop.branch.smartCheckout": "Smart Checkout", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 79f0d56398..9e5198f4b8 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -754,12 +754,19 @@ "desktop.branch.checkedOut": "已检出“{name}”", "desktop.branch.checkoutAfter": "创建后检出分支", "desktop.branch.checkoutFailed": "检出失败:{reason}", + "desktop.branch.checkoutFailedIn": "在 {repository} 中检出“{name}”失败:{reason}", "desktop.branch.checkoutRevision": "检出标签或修订版本…", + "desktop.branch.commonCheckedOut": "已在所有仓库检出“{name}”", + "desktop.branch.commonCreated": "已在所有仓库创建分支“{name}”", + "desktop.branch.commonLocal": "共同本地分支", + "desktop.branch.commonRemote": "共同远程分支", "desktop.branch.conflictHint": "智能检出会先贮藏你的更改,切换分支后再恢复。强制检出会直接切换并丢弃这些更改。", "desktop.branch.conflictPrompt": "你对这些文件的更改与“{name}”冲突:", "desktop.branch.conflictTitle": "本地更改将被覆盖", "desktop.branch.createFailed": "创建分支失败:{reason}", + "desktop.branch.createFailedIn": "在 {repository} 中创建分支“{name}”失败:{reason}", "desktop.branch.createFrom": "从“{name}”创建。", + "desktop.branch.createFromInAll": "在所有仓库中从“{name}”创建。", "desktop.branch.created": "已创建分支“{name}”", "desktop.branch.current": "当前分支", "desktop.branch.deleteFailed": "删除分支失败:{reason}", @@ -769,6 +776,7 @@ "desktop.branch.detached": "已检出“{revision}”,处于 detached HEAD 状态", "desktop.branch.detachedNote": "仓库将以 detached HEAD 状态打开。", "desktop.branch.forceCheckout": "强制检出", + "desktop.branch.keepButton": "不回滚", "desktop.branch.loadFailed": "加载分支失败:{reason}", "desktop.branch.loading": "正在加载分支…", "desktop.branch.localIn": "{repository} 中的本地分支", @@ -783,9 +791,16 @@ "desktop.branch.renameTitle": "重命名分支", "desktop.branch.renamed": "分支已重命名为“{name}”", "desktop.branch.repositoryPanel": "{repository},位于 {branch}", + "desktop.branch.repositorySeparator": "、", "desktop.branch.revision": "标签或修订版本", "desktop.branch.revisionPrompt": "输入标签名、分支名、提交 Hash 或其他 Git 修订版本。", "desktop.branch.revisionTitle": "检出标签或修订版本", + "desktop.branch.rollbackButton": "回滚", + "desktop.branch.rollbackFailed": "在 {repository} 中回滚失败:{reason}", + "desktop.branch.rollbackImpossible": "{repositories} 在操作前不在任何分支上,无法回滚。", + "desktop.branch.rollbackPrompt": "已在这些仓库中完成:{repositories}。回滚后,所有仓库会回到原来的分支。", + "desktop.branch.rollbackTitle": "只在部分仓库中完成", + "desktop.branch.rolledBack": "已回滚:{repositories}", "desktop.branch.rowMenu": "{name} 的操作", "desktop.branch.search": "搜索分支和操作", "desktop.branch.smartCheckout": "智能检出", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 8d417679e4..c21db48a12 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -6291,6 +6291,18 @@ "reason": "string" } }, + { + "id": "desktop.branch.checkoutFailedIn", + "description": "Branch popup of a folder with several repositories: a checkout of a common branch failed in one repository", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string", + "repository": "string", + "reason": "string" + } + }, { "id": "desktop.branch.checkoutRevision", "description": "Desktop branch: CheckoutRevision", @@ -6298,6 +6310,40 @@ "desktop" ] }, + { + "id": "desktop.branch.commonCheckedOut", + "description": "Branch popup of a folder with several repositories: every repository was switched to the common branch", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.branch.commonCreated", + "description": "Branch popup of a folder with several repositories: the new branch was created in every repository", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.branch.commonLocal", + "description": "Branch popup of a folder with several repositories: head of the local branches every repository has, as IntelliJ IDEA's Common Local Branches", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.branch.commonRemote", + "description": "Branch popup of a folder with several repositories: head of the remote branches every repository has, as IntelliJ IDEA's Common Remote Branches", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.branch.conflictHint", "description": "Desktop branch: ConflictHint", @@ -6332,6 +6378,18 @@ "reason": "string" } }, + { + "id": "desktop.branch.createFailedIn", + "description": "Branch popup of a folder with several repositories: creating the new branch failed in one repository", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string", + "repository": "string", + "reason": "string" + } + }, { "id": "desktop.branch.createFrom", "description": "Desktop branch: CreateFrom", @@ -6342,6 +6400,16 @@ "name": "string" } }, + { + "id": "desktop.branch.createFromInAll", + "description": "New branch dialog opened on a common branch: the branch is created in every repository of the folder", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, { "id": "desktop.branch.created", "description": "Desktop branch: Created", @@ -6421,6 +6489,13 @@ "desktop" ] }, + { + "id": "desktop.branch.keepButton", + "description": "Rollback dialog of a branch action that succeeded in some repositories only: leaves them as they are", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.branch.loadFailed", "description": "Desktop branch: LoadFailed", @@ -6547,6 +6622,13 @@ "branch": "string" } }, + { + "id": "desktop.branch.repositorySeparator", + "description": "Separator between the repository names a branch message lists", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.branch.revision", "description": "Desktop branch: Revision", @@ -6568,6 +6650,61 @@ "desktop" ] }, + { + "id": "desktop.branch.rollbackButton", + "description": "Rollback dialog of a branch action that succeeded in some repositories only: undoes it there", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.branch.rollbackFailed", + "description": "Rolling back a branch action failed in one repository", + "platforms": [ + "desktop" + ], + "parameters": { + "repository": "string", + "reason": "string" + } + }, + { + "id": "desktop.branch.rollbackImpossible", + "description": "Rollback dialog: the repositories that were on no branch before the action, which a rollback cannot return to", + "platforms": [ + "desktop" + ], + "parameters": { + "repositories": "string" + } + }, + { + "id": "desktop.branch.rollbackPrompt", + "description": "Rollback dialog: the repositories where the branch action already succeeded", + "platforms": [ + "desktop" + ], + "parameters": { + "repositories": "string" + } + }, + { + "id": "desktop.branch.rollbackTitle", + "description": "Title of the dialog of a branch action that succeeded in some repositories only", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.branch.rolledBack", + "description": "Every repository a branch action had changed was rolled back", + "platforms": [ + "desktop" + ], + "parameters": { + "repositories": "string" + } + }, { "id": "desktop.branch.rowMenu", "description": "Desktop branch: RowMenu", diff --git a/shared/platform-feature-matrix/features/git-multi-repository-references.json b/shared/platform-feature-matrix/features/git-multi-repository-references.json index 7b180d581b..b0a0c55e32 100644 --- a/shared/platform-feature-matrix/features/git-multi-repository-references.json +++ b/shared/platform-feature-matrix/features/git-multi-repository-references.json @@ -23,7 +23,11 @@ "desktop/internal/workbench/workspace_repositories_test.go", "docs/assets/workspace-repositories/README.md", "desktop/internal/workbench/gitlog_limits.go", - "desktop/internal/settingswindow/git_log_limits_view.go" + "desktop/internal/settingswindow/git_log_limits_view.go", + "desktop/internal/core/git_workspace_branches.go", + "desktop/internal/workbench/branch_common.go", + "desktop/internal/workbench/branch_common_view.go", + "desktop/internal/workbench/branch_common_test.go" ] }, "windows": { @@ -46,12 +50,16 @@ "desktop/internal/workbench/workspace_repositories_test.go", "docs/assets/workspace-repositories/README.md", "desktop/internal/workbench/gitlog_limits.go", - "desktop/internal/settingswindow/git_log_limits_view.go" + "desktop/internal/settingswindow/git_log_limits_view.go", + "desktop/internal/core/git_workspace_branches.go", + "desktop/internal/workbench/branch_common.go", + "desktop/internal/workbench/branch_common_view.go", + "desktop/internal/workbench/branch_common_test.go" ] }, "owner": "Git", - "verification": "在多仓库工作区打开 Git Log:确认按仓库分组、仓库配色、非活动仓库分组只读,点其它仓库的引用会切换活动仓库且只加载一次,Pull 弹窗可选择远程分支与策略。 Windows 无已保存折叠设置时,单仓库与多仓库的 Tags 默认折叠、Local / Remote 默认展开;手动展开 Tags 后重新打开面板仍保留选择,已有折叠设置继续生效。 Windows 明暗主题中普通本地、远程分支均复用顶部分支按钮的空心 VcsIcon,当前分支勾选、收藏星标、标签与文件夹提示保持可辨认。 macOS 在两个分支名不同的仓库间切换时不得查询旧分支;目标历史读取失败也不能保留旧仓库的提交、分页或文件详情。 Windows Git Log 本地和远程分支右键菜单的拷贝分支名称在删除之前,删除是最后一个操作并单独分组;当前分支无删除入口,执行 Git 写操作时删除仍禁用。 Windows Git Log Tags 标签节点右键菜单最后一组提供 Delete,点击后直接删除活动仓库本地标签,不弹二次确认;失败保留引用和选择,成功后清除被删标签的历史筛选并刷新。非活动仓库及写操作期间禁用;旧工作区/仓库的动作回调不得发起删除,迟到结果不得刷新新仓库或释放新请求状态。 Windows Tags 的 Delete 与分支和提交节点删除复用相同 TrashIcon,明暗主题图标与禁用状态一致。 引用树的 `/` 分组与同级排序(引用先于纯分组,再按自然序,收藏分支及其所在分组优先)由 Core `git.referenceTree` 决定,两端只负责展开、缩进与虚拟化;同一组引用在 macOS 与 Windows 的树结构和顺序一致。 打开本身不是 Git 仓库、内含多个独立仓库的文件夹:标题栏分支入口按 IDEA 样式逐行列出仓库(颜色方块、仓库名、右侧当前分支、›),点一行在其旁边展开该仓库的分支面板,在面板里检出、新建、合并、删除只改变该仓库,其他仓库分支不变;Git Log 提交行左侧显示正在查看仓库的颜色条,路径筛选器下方“仓库根目录”按颜色列出仓库,点击后日志改看该仓库且写操作作用于该仓库。 多仓库 Git Log 引用面板每个仓库节点下各有本地 / 远程 / 标签,点其它仓库的分支即在该仓库查看该分支;筛选按钮后的仓库名可点击,列出全部仓库:点名称只看该仓库,勾选多个仓库时日志按提交时间混排(Core `git.workspaceHistoryMerge`,各仓库保持 Git 的原有顺序,加载更多只在末尾追加),每行颜色条是所属仓库的颜色,提交详情、文件比较和提交右键菜单都作用于该行所属的仓库;取消勾选到只剩一个仓库时回到单仓库日志。 勾选多个仓库混排时,读满多个仓库的上限后日志末尾提示超出可读取范围,不显示加载失败。", - "notes": "Viva:项目文件夹含嵌套仓库时(含文件夹本身不是 Git 仓库),标题栏分支入口按 IDEA 样式逐行列出仓库,颜色来自 Core(repository_colors.go),右侧是 Core 读出的当前分支;点一行在旁边展开该仓库的面板(“<仓库> 中的最近分支 / 本地分支 / 远程分支 / 标签”),面板里的检出、新建、合并、删除等写操作都只作用于该仓库。Git Log 引用面板按仓库分组,提交行左侧有正在查看仓库的颜色条,路径筛选器下方的“仓库根目录”列出各仓库并切换日志遍历的仓库。引用面板每个仓库节点下各有本地 / 远程 / 标签;筛选按钮后的仓库名可点击,勾选多个仓库时日志按提交时间混排,混排顺序与提交键由 Core `git.workspaceHistoryMerge` 决定,仓库的选择由 Core `git.workspaceRepositorySelection` 的 `chosen` 决定。尚未实现:IDEA 的 Common Local / Remote Branches(多个仓库同名分支一起操作),以及跨仓库的 Update / Push。 混排时所有仓库合计最多读取“设置 › 版本控制 › Git 日志”中多个仓库的上限(默认 20000 条),读满后各仓库停在当前位置,日志末尾提示超出可读取范围并可打开该设置。", + "verification": "在多仓库工作区打开 Git Log:确认按仓库分组、仓库配色、非活动仓库分组只读,点其它仓库的引用会切换活动仓库且只加载一次,Pull 弹窗可选择远程分支与策略。 Windows 无已保存折叠设置时,单仓库与多仓库的 Tags 默认折叠、Local / Remote 默认展开;手动展开 Tags 后重新打开面板仍保留选择,已有折叠设置继续生效。 Windows 明暗主题中普通本地、远程分支均复用顶部分支按钮的空心 VcsIcon,当前分支勾选、收藏星标、标签与文件夹提示保持可辨认。 macOS 在两个分支名不同的仓库间切换时不得查询旧分支;目标历史读取失败也不能保留旧仓库的提交、分页或文件详情。 Windows Git Log 本地和远程分支右键菜单的拷贝分支名称在删除之前,删除是最后一个操作并单独分组;当前分支无删除入口,执行 Git 写操作时删除仍禁用。 Windows Git Log Tags 标签节点右键菜单最后一组提供 Delete,点击后直接删除活动仓库本地标签,不弹二次确认;失败保留引用和选择,成功后清除被删标签的历史筛选并刷新。非活动仓库及写操作期间禁用;旧工作区/仓库的动作回调不得发起删除,迟到结果不得刷新新仓库或释放新请求状态。 Windows Tags 的 Delete 与分支和提交节点删除复用相同 TrashIcon,明暗主题图标与禁用状态一致。 引用树的 `/` 分组与同级排序(引用先于纯分组,再按自然序,收藏分支及其所在分组优先)由 Core `git.referenceTree` 决定,两端只负责展开、缩进与虚拟化;同一组引用在 macOS 与 Windows 的树结构和顺序一致。 打开本身不是 Git 仓库、内含多个独立仓库的文件夹:标题栏分支入口按 IDEA 样式逐行列出仓库(颜色方块、仓库名、右侧当前分支、›),点一行在其旁边展开该仓库的分支面板,在面板里检出、新建、合并、删除只改变该仓库,其他仓库分支不变;Git Log 提交行左侧显示正在查看仓库的颜色条,路径筛选器下方“仓库根目录”按颜色列出仓库,点击后日志改看该仓库且写操作作用于该仓库。 多仓库 Git Log 引用面板每个仓库节点下各有本地 / 远程 / 标签,点其它仓库的分支即在该仓库查看该分支;筛选按钮后的仓库名可点击,列出全部仓库:点名称只看该仓库,勾选多个仓库时日志按提交时间混排(Core `git.workspaceHistoryMerge`,各仓库保持 Git 的原有顺序,加载更多只在末尾追加),每行颜色条是所属仓库的颜色,提交详情、文件比较和提交右键菜单都作用于该行所属的仓库;取消勾选到只剩一个仓库时回到单仓库日志。 勾选多个仓库混排时,读满多个仓库的上限后日志末尾提示超出可读取范围,不显示加载失败。 打开内含多个仓库的文件夹:标题栏分支入口在仓库列表下方列出“共同本地分支 / 共同远程分支”(所有仓库都有的同名分支,由 Core `git.workspaceCommonReferences` 计算,所有仓库都在该分支时显示为当前分支),搜索框同样筛选这两节;在共同分支上检出或从它新建分支,会按 Core `git.workspaceBranchPlan` 的顺序依次作用于每个仓库,新分支名与任一仓库已有分支重名时提示已存在;检出会覆盖本地改动时,冲突对话框按“仓库/文件”列出所有仓库的改动,选择对所有仓库生效。某个仓库失败时停止,若已有仓库完成,弹出“只在部分仓库中完成”,点“回滚”让已完成的仓库回到原分支并删除刚创建的分支,点“不回滚”保持现状。勾选多个仓库混排时,每个仓库当前检出分支上的提交都有当前分支底色(Core `git.graphProjection` 的 `checkedOutHeads`)。", + "notes": "Viva:项目文件夹含嵌套仓库时(含文件夹本身不是 Git 仓库),标题栏分支入口按 IDEA 样式逐行列出仓库,颜色来自 Core(repository_colors.go),右侧是 Core 读出的当前分支;点一行在旁边展开该仓库的面板(“<仓库> 中的最近分支 / 本地分支 / 远程分支 / 标签”),面板里的检出、新建、合并、删除等写操作都只作用于该仓库。Git Log 引用面板按仓库分组,提交行左侧有正在查看仓库的颜色条,路径筛选器下方的“仓库根目录”列出各仓库并切换日志遍历的仓库。引用面板每个仓库节点下各有本地 / 远程 / 标签;筛选按钮后的仓库名可点击,勾选多个仓库时日志按提交时间混排,混排顺序与提交键由 Core `git.workspaceHistoryMerge` 决定,仓库的选择由 Core `git.workspaceRepositorySelection` 的 `chosen` 决定。仓库列表下方是 IDEA 的 Common Local / Remote Branches:共同分支由 Core `git.workspaceCommonReferences` 计算,检出与新建分支的逐仓库步骤和回滚动作由 Core `git.workspaceBranchPlan` 给出,桌面端按顺序执行、首个失败即停,并像 IDEA 一样询问是否回滚。尚未实现:共同分支上的合并、变基、删除、推送等其他操作,以及跨仓库的 Update / Push。 混排时所有仓库合计最多读取“设置 › 版本控制 › Git 日志”中多个仓库的上限(默认 20000 条),读满后各仓库停在当前位置,日志末尾提示超出可读取范围并可打开该设置。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {