From 401c542647adbece7c6da5a6b29ce3870fe249db Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Sun, 22 Nov 2026 21:57:30 +0800 Subject: [PATCH] feat(vcs): improve Git workflows (#5174) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Improve OpenIDEA's Git workflows across commit and staging, branch and remote operations, merge and rebase, Git Log and signing, worktrees, stash and shelf, patch application, and clone settings. Adds a one-click stash for tracked changes across Git roots and lets users open a worktree branch's associated GitHub review from its context menu. Cloning now includes submodules by default (Settings › Version Control › Git, can be turned off). Repository entry points added here run in each repository's execution scope, so they use the project's own git executable. --- Cargo.lock | 1 + THIRD_PARTY_LICENSES.md | 3 +- crates/ide-core/src/error.rs | 76 +- crates/ide-core/src/process.rs | 4 + crates/ide-core/src/workflow_settings.rs | 91 +- crates/ide-host/src/environment.rs | 52 +- crates/ide-host/src/formatter.rs | 68 +- crates/ide-host/src/lib.rs | 2 + crates/ide-host/src/mcp/vcs.rs | 9 +- crates/ide-host/src/ops/lsp.rs | 59 + crates/ide-host/src/ops/vcs.rs | 20 +- crates/ide-host/src/ops/vcs/commands.rs | 1886 ++++++++++++-- crates/ide-host/src/ops/vcs/rebase_editor.rs | 62 + crates/ide-host/src/ops/vcs/worktree_setup.rs | 33 + crates/ide-host/src/project.rs | 19 +- crates/ide-host/tests/external_log.rs | 4 +- crates/ide-host/tests/properties.rs | 2 + crates/ide-host/tests/trust_vcs_sweep.rs | 91 +- crates/ide-host/tests/vcs_documents.rs | 35 +- crates/ide-host/tests/vcs_flow.rs | 15 +- crates/ide-host/tests/vcs_roots.rs | 437 +++- crates/ide-host/tests/vcs_shelf_roots.rs | 212 +- crates/ide-host/tests/vcs_worktrees.rs | 195 +- crates/ide-index/src/filter.rs | 23 + crates/ide-index/src/lib.rs | 25 +- crates/ide-language/src/registry.rs | 1 + crates/ide-lsp/src/handler.rs | 8 +- crates/ide-lsp/src/inspect.rs | 63 +- crates/ide-lsp/src/lib.rs | 62 + crates/ide-lsp/src/scope.rs | 40 +- crates/ide-lsp/src/server.rs | 42 +- crates/ide-lsp/src/source_actions.rs | 119 + crates/ide-lsp/tests/mock_server.rs | 150 ++ crates/ide-ssh/src/askpass.rs | 54 +- crates/ide-vcs/Cargo.toml | 1 + crates/ide-vcs/src/blame.rs | 38 +- crates/ide-vcs/src/changelists.rs | 57 +- crates/ide-vcs/src/cherry_pick_plan.rs | 160 ++ crates/ide-vcs/src/cli.rs | 197 +- crates/ide-vcs/src/commit_message.rs | 650 +++++ crates/ide-vcs/src/commit_rewrite.rs | 569 +++++ crates/ide-vcs/src/compare.rs | 39 + crates/ide-vcs/src/conflict_resolution.rs | 241 ++ crates/ide-vcs/src/diff.rs | 194 +- crates/ide-vcs/src/history.rs | 276 ++- crates/ide-vcs/src/ignore.rs | 2 +- crates/ide-vcs/src/incoming.rs | 169 ++ crates/ide-vcs/src/lib.rs | 1009 +++++++- crates/ide-vcs/src/log_index.rs | 2 +- crates/ide-vcs/src/manage.rs | 199 +- crates/ide-vcs/src/ops.rs | 318 ++- crates/ide-vcs/src/patch.rs | 581 ++++- crates/ide-vcs/src/patch/file_diff.rs | 164 ++ crates/ide-vcs/src/patch/mapping.rs | 294 +++ .../ide-vcs/src/patch/mapping/candidates.rs | 247 ++ crates/ide-vcs/src/preserve.rs | 409 +++- crates/ide-vcs/src/push_preview.rs | 489 ++++ crates/ide-vcs/src/push_report.rs | 58 + crates/ide-vcs/src/rebase_editor.rs | 408 ++++ crates/ide-vcs/src/refs.rs | 110 +- crates/ide-vcs/src/remotes.rs | 226 +- crates/ide-vcs/src/repo.rs | 63 +- crates/ide-vcs/src/roots.rs | 159 +- crates/ide-vcs/src/shelf.rs | 675 ++++- crates/ide-vcs/src/signing.rs | 266 ++ crates/ide-vcs/src/staged_text.rs | 253 ++ crates/ide-vcs/src/status.rs | 32 + crates/ide-vcs/src/submodules.rs | 182 ++ crates/ide-vcs/src/worktree_config.rs | 104 + crates/ide-vcs/src/write.rs | 1652 ++++++++++--- crates/ide-vcs/tests/blame_ignore.rs | 50 +- crates/ide-vcs/tests/git_workflows.rs | 2174 ++++++++++++++++- crates/ide-vcs/tests/history_ops.rs | 651 ++++- crates/ide-vcs/tests/log_shape.rs | 2 +- crates/ide-vcs/tests/repo.rs | 1192 ++++++++- crates/ide-vcs/tests/submodule_update.rs | 289 +++ crates/ide-vfs/src/watch.rs | 8 +- crates/ide-workspace/src/settings.rs | 10 +- docs/en/guide/vcs.mdx | 54 +- docs/zh/guide/vcs.mdx | 54 +- e2e/applyPatchLayout.spec.ts | 556 ++++- e2e/branchCompareLayout.spec.ts | 78 +- e2e/branchesPopupExpansion.spec.ts | 151 +- e2e/commit.spec.ts | 1184 +++++++++ e2e/diff-navigation.spec.ts | 65 + e2e/fileHistoryActions.spec.ts | 10 +- e2e/gitCommitMessageLayout.spec.ts | 3 +- e2e/gitLogBranchMenu.spec.ts | 44 +- e2e/gitLogMultiRepoOperations.spec.ts | 253 ++ e2e/gitLogToolbarMenus.spec.ts | 29 + e2e/gitLogUndoCommit.spec.ts | 155 ++ e2e/gitMergeLayout.spec.ts | 22 +- e2e/gitRebaseLayout.spec.ts | 15 +- e2e/gitUnstashLayout.spec.ts | 12 +- e2e/gitWorktreesLayout.spec.ts | 25 +- e2e/gutterChangeLayout.spec.ts | 144 +- e2e/interactiveRebaseLayout.spec.ts | 402 ++- e2e/mergeEditor.spec.ts | 34 +- e2e/newBranch.spec.ts | 77 +- e2e/pullDialogLayout.spec.ts | 8 +- e2e/pushTargetBranch.spec.ts | 20 +- e2e/rollbackDialogLayout.spec.ts | 48 + e2e/settingsFormLayout.spec.ts | 23 + e2e/stagedEditor.spec.ts | 929 +++++++ e2e/updateProject.spec.ts | 11 +- languages/ignore.toml | 2 +- src-tauri/src/menu.rs | 3 + src-tauri/src/remote_dev.rs | 12 +- src-tauri/src/windows.rs | 27 +- src-tauri/tests/commands.snap | 54 +- src/bindings.ts | 951 ++++++- src/editor/api.ts | 11 +- src/editor/core/cm/baseKeymap.ts | 8 +- src/editor/core/controller.ts | 37 +- src/editor/core/customDocuments.test.ts | 30 +- src/editor/core/embeddedDocuments.ts | 2 +- src/editor/core/index.ts | 3 +- src/editor/core/model/attachment.test.ts | 19 + src/editor/core/model/attachment.ts | 53 +- src/editor/core/model/customDocuments.ts | 3 +- src/features/github/data/local.ts | 2 +- src/features/github/runtime.ts | 2 + .../github/timeline/comments/suggestion.ts | 2 +- src/features/github/worktreeReviews.test.ts | 86 + src/features/github/worktreeReviews.ts | 89 + src/features/run/beforeLaunch.ts | 32 +- src/features/run/configurationChecks.ts | 148 ++ src/features/run/index.ts | 4 + src/features/run/store.ts | 84 +- .../__tests__/todoVimStaging.test.tsx | 4 +- .../settings/pages/GitSettings.module.css | 16 + src/features/settings/pages/GitSigningRow.tsx | 263 ++ src/features/settings/pages/vcs.tsx | 121 +- .../settings/pages/workflowControls.tsx | 45 +- src/features/todo/PreviewEditor.test.tsx | 2 + src/features/todo/TodoSettingsPage.module.css | 19 + src/features/todo/TodoSettingsPage.tsx | 156 +- src/features/todo/TodoView.module.css | 31 + src/features/todo/TodoView.tsx | 509 ++-- src/features/todo/highlight.ts | 6 +- src/features/todo/index.ts | 6 +- src/features/todo/model.ts | 143 +- src/features/todo/store.ts | 34 +- src/features/todo/todo.test.ts | 34 +- src/features/vcs/AmendTargetMenu.tsx | 114 + src/features/vcs/ApplyPatch.module.css | 80 +- src/features/vcs/BranchComparisonEditor.tsx | 70 + src/features/vcs/BranchSync.tsx | 58 +- src/features/vcs/BranchWidget.tsx | 193 +- src/features/vcs/CombinedDiff.tsx | 25 +- src/features/vcs/CommitAuthorFields.tsx | 86 + src/features/vcs/CommitCheckSummary.tsx | 59 + src/features/vcs/CommitDialog.tsx | 13 +- .../vcs/CommitMessageDialog.module.css | 45 + src/features/vcs/CommitMessageDialog.tsx | 207 ++ src/features/vcs/CommitOptions.tsx | 165 +- src/features/vcs/CommitView.module.css | 91 +- src/features/vcs/CommitView.tsx | 730 +++--- src/features/vcs/CompareBranches.module.css | 82 +- src/features/vcs/CompareBranches.tsx | 302 +-- src/features/vcs/ConflictsDialog.module.css | 4 + src/features/vcs/DiffEditor.module.css | 43 + src/features/vcs/DiffEditor.tsx | 676 +++-- src/features/vcs/DiffWindow.tsx | 48 +- src/features/vcs/FetchButton.tsx | 17 + src/features/vcs/GitCommandDialog.module.css | 15 - src/features/vcs/GitLog.module.css | 20 +- src/features/vcs/GitLog.tsx | 25 +- src/features/vcs/GitMergeDiff.tsx | 100 +- src/features/vcs/HunkPopup.module.css | 20 +- src/features/vcs/HunkPopup.tsx | 126 +- .../vcs/LocalChangesReviewDialog.module.css | 52 + src/features/vcs/LocalChangesReviewDialog.tsx | 296 +++ src/features/vcs/MergeEditor.module.css | 7 + src/features/vcs/MergeEditor.tsx | 81 +- src/features/vcs/MergeRebaseWidget.tsx | 9 +- src/features/vcs/NewWorktreeDialog.tsx | 505 ++++ src/features/vcs/PushCheckStatus.tsx | 52 + src/features/vcs/PushTagOptions.tsx | 69 + src/features/vcs/RebasePlanChanges.tsx | 91 + src/features/vcs/RebasePlanDialog.tsx | 481 ++++ src/features/vcs/RepoPicker.tsx | 29 + src/features/vcs/RevisionChooser.tsx | 65 +- src/features/vcs/StagedEditor.module.css | 27 + src/features/vcs/StagedEditor.tsx | 359 +++ src/features/vcs/StagingDiff.tsx | 574 +++++ src/features/vcs/StashChanges.tsx | 233 ++ src/features/vcs/StashesPanel.tsx | 154 ++ src/features/vcs/SyncCommitsPopup.module.css | 8 + src/features/vcs/SyncCommitsPopup.tsx | 136 +- src/features/vcs/TargetBranchInput.tsx | 127 +- src/features/vcs/ThreePaneDiff.module.css | 50 + src/features/vcs/ThreePaneDiff.tsx | 240 ++ src/features/vcs/Worktrees.module.css | 18 +- src/features/vcs/WorktreesPanel.tsx | 390 +++ .../vcs/__tests__/annotateRevision.test.ts | 9 +- src/features/vcs/__tests__/blame.test.tsx | 86 +- src/features/vcs/__tests__/branchOps.test.ts | 288 ++- .../vcs/__tests__/branchRebase.test.ts | 155 ++ .../vcs/__tests__/branchWidget.test.tsx | 121 + .../vcs/__tests__/branchesPopupHost.test.tsx | 56 +- .../vcs/__tests__/changelists.test.ts | 9 + .../vcs/__tests__/combinedDiff.test.tsx | 2 +- .../vcs/__tests__/commitChecks.test.ts | 303 ++- .../vcs/__tests__/commitDraft.test.ts | 190 +- .../vcs/__tests__/commitFormat.test.ts | 209 ++ .../vcs/__tests__/commitInclusion.test.ts | 73 +- src/features/vcs/__tests__/commitMode.test.ts | 244 +- .../vcs/__tests__/commonBranchMenu.test.ts | 30 +- .../vcs/__tests__/compareFlow.test.ts | 26 +- .../vcs/__tests__/compareTool.test.tsx | 43 +- src/features/vcs/__tests__/conflicts.test.ts | 9 + .../vcs/__tests__/deleteBranches.test.ts | 185 +- src/features/vcs/__tests__/diffFind.test.tsx | 2 + .../vcs/__tests__/diffNavigation.test.ts | 15 +- .../vcs/__tests__/diffToolbar.test.tsx | 2 + .../__tests__/fileHistoryNavigation.test.ts | 38 + .../vcs/__tests__/folderCompare.test.tsx | 15 + src/features/vcs/__tests__/gitOps.test.ts | 198 +- src/features/vcs/__tests__/historyOps.test.ts | 109 +- src/features/vcs/__tests__/incoming.test.ts | 203 +- .../vcs/__tests__/logBranches.test.tsx | 18 +- .../vcs/__tests__/logDetails.test.tsx | 22 + src/features/vcs/__tests__/logLoading.test.ts | 137 +- src/features/vcs/__tests__/logOptions.test.ts | 14 +- src/features/vcs/__tests__/logPanes.test.tsx | 18 + .../vcs/__tests__/logUiFeatures.test.tsx | 47 +- .../vcs/__tests__/mergeCompletion.test.ts | 158 ++ .../vcs/__tests__/mergeDialogRepo.test.tsx | 168 +- .../vcs/__tests__/multiPushTarget.test.tsx | 309 ++- .../vcs/__tests__/multiRepoRollback.test.ts | 415 +++- .../vcs/__tests__/multiRootStashes.test.tsx | 158 +- .../vcs/__tests__/operationNotices.test.ts | 49 +- .../vcs/__tests__/pluginCommit.test.ts | 136 +- .../vcs/__tests__/postCommitChecks.test.tsx | 108 + .../vcs/__tests__/projectSwitch.test.ts | 4 +- .../vcs/__tests__/promptDialog.test.tsx | 2 +- .../vcs/__tests__/pullDialogRepo.test.tsx | 171 +- .../vcs/__tests__/pushRejected.test.ts | 215 +- src/features/vcs/__tests__/pushTarget.test.ts | 88 - .../vcs/__tests__/rebaseDialogRepo.test.tsx | 95 +- .../vcs/__tests__/remoteResults.test.ts | 210 +- .../vcs/__tests__/repoBranches.test.ts | 7 +- .../vcs/__tests__/repoScopedSync.test.ts | 108 +- src/features/vcs/__tests__/rollback.test.ts | 63 +- .../vcs/__tests__/rollbackAction.test.ts | 7 +- src/features/vcs/__tests__/shelf.test.tsx | 18 +- .../vcs/__tests__/show-diff-chain.test.ts | 17 +- .../vcs/__tests__/singlePush.test.tsx | 584 ++++- .../__tests__/smartCheckoutDialog.test.tsx | 75 + .../vcs/__tests__/stagingArea.test.tsx | 99 +- .../vcs/__tests__/stagingRange.test.ts | 56 + .../vcs/__tests__/stashDialogRepo.test.tsx | 49 +- src/features/vcs/__tests__/stashDiff.test.ts | 105 + .../vcs/__tests__/syncCommits.test.ts | 15 + .../vcs/__tests__/syncCommitsPopup.test.tsx | 50 +- .../vcs/__tests__/targetBranchInput.test.tsx | 49 +- .../vcs/__tests__/unstashConflicts.test.ts | 117 +- .../vcs/__tests__/unstashViewDrop.test.tsx | 191 +- .../vcs/__tests__/updateBranches.test.ts | 78 +- src/features/vcs/__tests__/workflow.test.ts | 43 +- .../vcs/__tests__/worktreeInclude.test.tsx | 168 ++ .../vcs/__tests__/worktreesPanel.test.tsx | 95 +- src/features/vcs/actions.tsx | 637 ++++- src/features/vcs/activeRepository.ts | 73 + src/features/vcs/allInOneDiff.ts | 4 +- src/features/vcs/amendPreview.ts | 51 + src/features/vcs/amendTargets.ts | 52 + src/features/vcs/annotateRevisionProvider.ts | 2 +- src/features/vcs/applyCommitChecks.tsx | 125 + src/features/vcs/blame.ts | 132 +- src/features/vcs/branchMenu.ts | 325 ++- src/features/vcs/branchOps.ts | 1604 +++++++++--- src/features/vcs/branchRebase.ts | 241 ++ src/features/vcs/branchSyncState.ts | 29 + src/features/vcs/branches.ts | 53 +- src/features/vcs/changeOps.tsx | 887 +++++-- src/features/vcs/changelists.ts | 118 +- src/features/vcs/changelistsUi.tsx | 6 +- src/features/vcs/changes.ts | 56 +- src/features/vcs/cm.ts | 128 +- src/features/vcs/commitAnalysis.ts | 181 ++ src/features/vcs/commitCheckRegistry.ts | 12 +- src/features/vcs/commitChecks.tsx | 662 ++--- src/features/vcs/commitContents.ts | 158 ++ src/features/vcs/commitIdentity.tsx | 18 +- src/features/vcs/commitSelection.ts | 192 +- src/features/vcs/commitStore.ts | 636 +++-- src/features/vcs/commitTests.ts | 101 + src/features/vcs/commitTodo.tsx | 263 ++ src/features/vcs/commitUi.ts | 87 +- src/features/vcs/common.module.css | 122 +- src/features/vcs/compare.tsx | 17 + src/features/vcs/comparePaths.ts | 8 +- src/features/vcs/compareTool.tsx | 14 +- src/features/vcs/conflicts.ts | 9 + src/features/vcs/conflictsUi.tsx | 408 +++- src/features/vcs/dialogs.tsx | 56 +- src/features/vcs/diffControls.ts | 94 +- src/features/vcs/diffDialog.tsx | 50 +- src/features/vcs/diffInput.ts | 95 +- src/features/vcs/diffNavigation.ts | 6 +- src/features/vcs/diffOptions.ts | 35 +- src/features/vcs/diffRangeView.ts | 61 + src/features/vcs/diffViewer.ts | 13 +- src/features/vcs/gitDiffEntries.ts | 85 + src/features/vcs/gitIdentity.ts | 19 + src/features/vcs/gitMenuDialogs.tsx | 1401 +++++------ src/features/vcs/gutter.ts | 271 +- src/features/vcs/historyActions.tsx | 130 +- src/features/vcs/hunkInclusion.ts | 163 +- src/features/vcs/ignoredFiles.ts | 58 + src/features/vcs/incoming.ts | 137 +- src/features/vcs/incomingRequest.ts | 41 + src/features/vcs/index.ts | 81 +- src/features/vcs/inlineBlame.ts | 4 + src/features/vcs/log/BranchesPanel.tsx | 133 +- src/features/vcs/log/CommitDetails.tsx | 22 +- src/features/vcs/log/CommitList.tsx | 25 +- src/features/vcs/log/CommitMessage.tsx | 25 +- src/features/vcs/log/CommitRow.tsx | 8 +- src/features/vcs/log/FilterBar.tsx | 81 +- src/features/vcs/log/commitMenu.ts | 191 +- src/features/vcs/logChanges.ts | 74 +- src/features/vcs/logDetails.ts | 20 +- src/features/vcs/logPaneActions.ts | 108 +- src/features/vcs/logStore.ts | 248 +- src/features/vcs/mergeCompletion.ts | 114 + src/features/vcs/openWorktree.ts | 3 +- src/features/vcs/operations.tsx | 578 ++++- src/features/vcs/ops.ts | 606 ++++- src/features/vcs/partialCommitProjection.ts | 60 + src/features/vcs/patchDiff.tsx | 202 ++ src/features/vcs/patches.tsx | 880 ++++++- src/features/vcs/postCommitChecks.tsx | 250 ++ src/features/vcs/pushHistory.ts | 48 + src/features/vcs/pushInspection.tsx | 245 ++ src/features/vcs/pushReport.ts | 70 + src/features/vcs/pushTarget.ts | 66 +- src/features/vcs/rebase.tsx | 612 +++-- src/features/vcs/rebaseEditor.tsx | 156 ++ src/features/vcs/rebasePlan.ts | 362 ++- src/features/vcs/remoteUi.tsx | 1396 ++++++++--- src/features/vcs/repoBranches.ts | 24 +- src/features/vcs/rootSync.ts | 24 +- src/features/vcs/settingsUi.ts | 10 +- src/features/vcs/shelf.tsx | 36 +- src/features/vcs/stagedDocument.ts | 391 +++ src/features/vcs/staging.ts | 116 +- src/features/vcs/stagingDiffEdits.ts | 30 + src/features/vcs/stagingRange.ts | 92 + src/features/vcs/stagingVersions.ts | 41 + src/features/vcs/stashDiff.ts | 78 + src/features/vcs/store.switch.test.ts | 28 +- src/features/vcs/store.ts | 100 +- src/features/vcs/submoduleRollback.ts | 55 + src/features/vcs/syncCommits.ts | 28 +- src/features/vcs/unifiedCommitLines.ts | 170 ++ src/features/vcs/worktreeInclude.ts | 159 ++ src/features/vcs/worktreeReviews.ts | 57 + src/features/vcs/worktrees.test.ts | 12 + src/features/vcs/worktrees.ts | 70 +- src/platform/clientSettings.ts | 3 + src/platform/keymaps/eclipse-macos.ts | 3 + src/platform/keymaps/eclipse-windows.ts | 2 + src/platform/keymaps/eclipse.test.ts | 2 + src/platform/keymaps/intellij-macos.ts | 6 + src/platform/keymaps/intellij-windows.ts | 6 + src/platform/keymaps/vscode-macos.ts | 6 + src/platform/locales/en.json | 2 + src/platform/locales/text/en.json | 647 ++++- src/platform/locales/text/es.json | 32 +- src/platform/locales/text/fr.json | 28 +- src/platform/locales/text/ko.json | 32 +- src/platform/locales/text/pl.json | 26 +- src/platform/locales/text/pt.json | 29 +- src/platform/locales/text/tr.json | 30 +- src/platform/locales/text/zh-TW.json | 32 +- src/platform/locales/text/zh.json | 636 ++++- src/platform/locales/zh.json | 2 + src/platform/remote.ts | 2 +- src/platform/todo.ts | 206 ++ src/platform/todoFilterSelection.ts | 50 + src/platform/workflowSettings.test.ts | 48 + src/platform/workflowSettings.ts | 45 +- src/ui/Menu.tsx | 5 +- src/ui/Select.tsx | 70 +- src/ui/expui/vcs/cherryPick.svg | 5 + src/ui/expui/vcs/cherryPick_dark.svg | 5 + src/ui/expui/vcs/patch.svg | 5 + src/ui/expui/vcs/patch_dark.svg | 5 + src/ui/icons.tsx | 4 +- src/workbench/contributions.ts | 46 +- src/workbench/todoFilterMenu.ts | 29 + src/workbench/todoReview.ts | 36 + 395 files changed, 53877 insertions(+), 7437 deletions(-) create mode 100644 crates/ide-host/src/ops/vcs/rebase_editor.rs create mode 100644 crates/ide-host/src/ops/vcs/worktree_setup.rs create mode 100644 crates/ide-lsp/src/source_actions.rs create mode 100644 crates/ide-vcs/src/cherry_pick_plan.rs create mode 100644 crates/ide-vcs/src/commit_message.rs create mode 100644 crates/ide-vcs/src/commit_rewrite.rs create mode 100644 crates/ide-vcs/src/conflict_resolution.rs create mode 100644 crates/ide-vcs/src/incoming.rs create mode 100644 crates/ide-vcs/src/patch/file_diff.rs create mode 100644 crates/ide-vcs/src/patch/mapping.rs create mode 100644 crates/ide-vcs/src/patch/mapping/candidates.rs create mode 100644 crates/ide-vcs/src/push_preview.rs create mode 100644 crates/ide-vcs/src/push_report.rs create mode 100644 crates/ide-vcs/src/rebase_editor.rs create mode 100644 crates/ide-vcs/src/signing.rs create mode 100644 crates/ide-vcs/src/staged_text.rs create mode 100644 crates/ide-vcs/src/submodules.rs create mode 100644 crates/ide-vcs/src/worktree_config.rs create mode 100644 crates/ide-vcs/tests/submodule_update.rs create mode 100644 e2e/gitLogMultiRepoOperations.spec.ts create mode 100644 e2e/gitLogUndoCommit.spec.ts create mode 100644 e2e/stagedEditor.spec.ts create mode 100644 src/features/github/worktreeReviews.test.ts create mode 100644 src/features/github/worktreeReviews.ts create mode 100644 src/features/run/configurationChecks.ts create mode 100644 src/features/settings/pages/GitSigningRow.tsx create mode 100644 src/features/vcs/AmendTargetMenu.tsx create mode 100644 src/features/vcs/BranchComparisonEditor.tsx create mode 100644 src/features/vcs/CommitAuthorFields.tsx create mode 100644 src/features/vcs/CommitCheckSummary.tsx create mode 100644 src/features/vcs/CommitMessageDialog.tsx create mode 100644 src/features/vcs/FetchButton.tsx create mode 100644 src/features/vcs/LocalChangesReviewDialog.module.css create mode 100644 src/features/vcs/LocalChangesReviewDialog.tsx create mode 100644 src/features/vcs/NewWorktreeDialog.tsx create mode 100644 src/features/vcs/PushCheckStatus.tsx create mode 100644 src/features/vcs/PushTagOptions.tsx create mode 100644 src/features/vcs/RebasePlanChanges.tsx create mode 100644 src/features/vcs/RebasePlanDialog.tsx create mode 100644 src/features/vcs/RepoPicker.tsx create mode 100644 src/features/vcs/StagedEditor.module.css create mode 100644 src/features/vcs/StagedEditor.tsx create mode 100644 src/features/vcs/StagingDiff.tsx create mode 100644 src/features/vcs/StashChanges.tsx create mode 100644 src/features/vcs/StashesPanel.tsx create mode 100644 src/features/vcs/ThreePaneDiff.module.css create mode 100644 src/features/vcs/ThreePaneDiff.tsx create mode 100644 src/features/vcs/WorktreesPanel.tsx create mode 100644 src/features/vcs/__tests__/branchRebase.test.ts create mode 100644 src/features/vcs/__tests__/branchWidget.test.tsx create mode 100644 src/features/vcs/__tests__/commitFormat.test.ts create mode 100644 src/features/vcs/__tests__/mergeCompletion.test.ts create mode 100644 src/features/vcs/__tests__/postCommitChecks.test.tsx delete mode 100644 src/features/vcs/__tests__/pushTarget.test.ts create mode 100644 src/features/vcs/__tests__/smartCheckoutDialog.test.tsx create mode 100644 src/features/vcs/__tests__/stagingRange.test.ts create mode 100644 src/features/vcs/__tests__/stashDiff.test.ts create mode 100644 src/features/vcs/__tests__/worktreeInclude.test.tsx create mode 100644 src/features/vcs/activeRepository.ts create mode 100644 src/features/vcs/amendPreview.ts create mode 100644 src/features/vcs/amendTargets.ts create mode 100644 src/features/vcs/applyCommitChecks.tsx create mode 100644 src/features/vcs/branchRebase.ts create mode 100644 src/features/vcs/branchSyncState.ts create mode 100644 src/features/vcs/commitAnalysis.ts create mode 100644 src/features/vcs/commitContents.ts create mode 100644 src/features/vcs/commitTests.ts create mode 100644 src/features/vcs/commitTodo.tsx create mode 100644 src/features/vcs/diffRangeView.ts create mode 100644 src/features/vcs/gitDiffEntries.ts create mode 100644 src/features/vcs/gitIdentity.ts create mode 100644 src/features/vcs/ignoredFiles.ts create mode 100644 src/features/vcs/incomingRequest.ts create mode 100644 src/features/vcs/mergeCompletion.ts create mode 100644 src/features/vcs/partialCommitProjection.ts create mode 100644 src/features/vcs/patchDiff.tsx create mode 100644 src/features/vcs/postCommitChecks.tsx create mode 100644 src/features/vcs/pushHistory.ts create mode 100644 src/features/vcs/pushInspection.tsx create mode 100644 src/features/vcs/pushReport.ts create mode 100644 src/features/vcs/rebaseEditor.tsx create mode 100644 src/features/vcs/stagedDocument.ts create mode 100644 src/features/vcs/stagingDiffEdits.ts create mode 100644 src/features/vcs/stagingRange.ts create mode 100644 src/features/vcs/stagingVersions.ts create mode 100644 src/features/vcs/stashDiff.ts create mode 100644 src/features/vcs/submoduleRollback.ts create mode 100644 src/features/vcs/unifiedCommitLines.ts create mode 100644 src/features/vcs/worktreeInclude.ts create mode 100644 src/features/vcs/worktreeReviews.ts create mode 100644 src/platform/todo.ts create mode 100644 src/platform/todoFilterSelection.ts create mode 100644 src/ui/expui/vcs/cherryPick.svg create mode 100644 src/ui/expui/vcs/cherryPick_dark.svg create mode 100644 src/ui/expui/vcs/patch.svg create mode 100644 src/ui/expui/vcs/patch_dark.svg create mode 100644 src/workbench/todoFilterMenu.ts create mode 100644 src/workbench/todoReview.ts diff --git a/Cargo.lock b/Cargo.lock index 755e40ba5..45753db2e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5012,6 +5012,7 @@ dependencies = [ "ide-core", "ignore", "libc", + "notify", "redb", "regex-lite", "serde", diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index 2b262263a..129af27b4 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -35,7 +35,8 @@ icon set, copied unmodified (some renamed) from JetBrains' open-source repositor → `maven/`); `plugins/gradle` (`icons/expui/gradle` → `toolwindows/gradle`, `icons/expui/gradleLoadChanges` → `build/gradleLoadChanges`, `icons/expui/gradle`, `icons/gradleSubproject` → `gradle/`); - `platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`). + `platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`); + `platform/dvcs-impl` (`icons/new/cherryPick` → `vcs/cherryPick`). Copyright 2000-2026 JetBrains s.r.o. and contributors. Apache License 2.0 (below). - [intellij-plugins](https://github.com/JetBrains/intellij-plugins) (each plugin carries its own licence): `protobuf/protoeditor-core` (`newui/protoFile` → diff --git a/crates/ide-core/src/error.rs b/crates/ide-core/src/error.rs index f78cf37f7..d7770cdf5 100644 --- a/crates/ide-core/src/error.rs +++ b/crates/ide-core/src/error.rs @@ -20,7 +20,72 @@ pub struct IdeError { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(tag = "type", rename_all = "camelCase")] pub enum ErrorData { - Tool { tool: String, missing: bool }, + Tool { + tool: String, + missing: bool, + }, + /// A non-fast-forward push from the current branch to its configured upstream. + PushRejected { + source: String, + upstream: String, + divergence: Option>, + /// Other refs may already have been published in the same push. + #[specta(optional)] + report: Option>, + }, + /// Git updated some refs before a later ref or push URL failed. + PushPartiallyApplied { + report: Box, + }, + /// A conflicted history replay left an amend commit ready to keep separately. + AmendConflict { + commit: String, + }, +} + +/// Git's reported result for each destination ref. A remote with several push URLs can +/// report more than one result for the same ref. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +pub struct PushReport { + pub remote: Option, + pub refs: Vec, +} + +impl PushReport { + pub fn new(remote: Option) -> Self { + Self { remote, refs: Vec::new() } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +pub struct PushRefResult { + pub reference: String, + pub status: PushRefStatus, + /// The number of commits between the tips Git reports for a fast-forward. + pub commits: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum PushRefStatus { + FastForward, + Forced, + Created, + UpToDate, + Deleted, +} + +/// The two tips shown in the rejected-push dialog. A retry must use this lease +/// even if a fetch advances the remote-tracking branch while the dialog is open. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PushDivergence { + pub source: String, + pub remote: String, + pub target: String, + pub local_tip: String, + pub remote_tip: String, + pub remote_commits: u32, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] @@ -115,4 +180,13 @@ mod tests { serde_json::json!({"kind":"unavailable","message":"no server","data":null}) ); } + + #[test] + fn older_tracked_push_rejections_need_no_report() { + let data: ErrorData = serde_json::from_str( + r#"{"type":"pushRejected","source":"main","upstream":"origin/main","divergence":null}"#, + ) + .unwrap(); + assert!(matches!(data, ErrorData::PushRejected { report: None, .. })); + } } diff --git a/crates/ide-core/src/process.rs b/crates/ide-core/src/process.rs index 3b0e031be..39089e7b7 100644 --- a/crates/ide-core/src/process.rs +++ b/crates/ide-core/src/process.rs @@ -5,6 +5,10 @@ use std::path::Path; #[cfg(windows)] use std::process::Stdio; use std::process::{Child, Command}; + +pub const ASKPASS_PORT_ENV: &str = "OPENIDEA_ASKPASS_PORT"; +/// The IDE's askpass helper may answer with saved credentials only. +pub const ASKPASS_SILENT_ENV: &str = "OPENIDEA_ASKPASS_SILENT"; use std::sync::{Arc, RwLock}; use std::time::Duration; diff --git a/crates/ide-core/src/workflow_settings.rs b/crates/ide-core/src/workflow_settings.rs index c8b691f1e..a7ec7814c 100644 --- a/crates/ide-core/src/workflow_settings.rs +++ b/crates/ide-core/src/workflow_settings.rs @@ -11,6 +11,7 @@ use std::collections::BTreeMap; pub struct VcsSettings { /// Colour folders that contain changed files (project tree, tabs). pub show_dirty_directories: bool, + pub create_changelists_automatically: bool, /// Diffs the user opens show in an editor tab; off, in a separate window. pub diff_as_editor_tab: bool, /// Stop file history (Show History) after `history_limit` commits. @@ -57,6 +58,7 @@ impl Default for VcsSettings { Self { // IDEA's VcsConfiguration.SHOW_DIRTY_RECURSIVELY is off by default. show_dirty_directories: false, + create_changelists_automatically: false, diff_as_editor_tab: true, limit_history: true, history_limit: 1000, @@ -70,9 +72,66 @@ impl Default for VcsSettings { } } +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum EmptyCherryPickAction { + #[default] + Skip, + CreateEmpty, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum StashDiffTarget { + #[default] + Local, + Parent, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum GitSaveChangesPolicy { + #[default] + Shelve, + Stash, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum FetchTagsMode { + #[default] + Auto, + Sync, + Always, + Never, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum GitAnnotateMovement { + #[default] + None, + WithinFile, + AcrossFiles, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(default, rename_all = "camelCase")] +pub struct GitAnnotateSettings { + pub ignore_whitespace: bool, + pub movement: GitAnnotateMovement, +} + +impl Default for GitAnnotateSettings { + fn default() -> Self { + Self { ignore_whitespace: true, movement: GitAnnotateMovement::None } + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(default, rename_all = "camelCase")] pub struct GitSettings { + pub annotate: GitAnnotateSettings, /// Show blame after the current editor line. pub inline_blame: bool, /// A click (or Enter / Space) on the inline blame label opens its commit; off, the @@ -83,20 +142,29 @@ pub struct GitSettings { pub sync_branch_operations: bool, /// Path to the git executable; empty = auto-detect. pub executable: String, + /// Clone all submodules along with the root repository. + pub clone_submodules: bool, /// Default of Update Project: `merge` | `rebase`. pub update_method: String, + /// Where Git operations keep local changes temporarily. + pub save_changes_policy: GitSaveChangesPolicy, /// Push rejected (non-fast-forward): update the branch and push again. pub auto_update_on_push_rejected: bool, pub warn_crlf: bool, pub warn_detached_head: bool, - /// Background check for incoming commits: `auto` | `always` | `never`. + /// Background check for incoming commits: `auto` | `always` | `check` | `never`. pub incoming_check: String, /// Minutes between background checks for incoming commits. pub incoming_check_interval: u32, + /// How an explicit fetch or project update handles remote tags. + pub fetch_tags_mode: FetchTagsMode, /// Branch name globs, `;`/`,`-separated; force push to them is prohibited. pub protected_branches: String, /// Initial state of Commit Options › Sign-off Commit. pub sign_off: bool, + /// Add Git's origin line when cherry-picking commits from protected remote branches. + pub add_cherry_pick_origin: bool, + pub empty_cherry_pick: EmptyCherryPickAction, /// Ask before committing files larger than `large_file_mb`. pub warn_large_files: bool, pub large_file_mb: u32, @@ -108,6 +176,8 @@ pub struct GitSettings { pub push_dialog_only_protected: bool, /// Stashes and shelves share one tab. pub combine_stash_and_shelf: bool, + /// What the stash browser compares its saved files against. + pub stash_diff_target: StashDiffTarget, /// The non-modal Commit tool window works on the index: Staged / Unstaged groups, /// stage and unstage instead of inclusion checkboxes, and no change lists. pub staging_area: bool, @@ -119,25 +189,32 @@ pub struct GitSettings { impl Default for GitSettings { fn default() -> Self { Self { + annotate: GitAnnotateSettings::default(), inline_blame: false, inline_blame_clickable: true, show_branch_in_project_view: false, sync_branch_operations: true, executable: String::new(), + clone_submodules: true, update_method: "merge".into(), + save_changes_policy: GitSaveChangesPolicy::default(), auto_update_on_push_rejected: false, warn_crlf: true, warn_detached_head: true, incoming_check: "auto".into(), incoming_check_interval: 15, + fetch_tags_mode: FetchTagsMode::Auto, protected_branches: "master; main".into(), sign_off: false, + add_cherry_pick_origin: true, + empty_cherry_pick: EmptyCherryPickAction::Skip, warn_large_files: true, large_file_mb: 50, warn_bad_file_names: true, show_push_dialog: true, push_dialog_only_protected: false, combine_stash_and_shelf: false, + stash_diff_target: StashDiffTarget::default(), staging_area: false, cli_status: false, } @@ -152,9 +229,11 @@ pub struct CommitSettings { /// window and a Commit dialog. pub non_modal: bool, pub include_changes_by_default: bool, + pub commit_all_when_nothing_staged: bool, /// Start with an empty message instead of the last one / the changelist's. pub clear_initial_message: bool, pub analyze_code: bool, + pub postpone_slow_checks: bool, pub check_todo: bool, pub reformat: bool, pub optimize_imports: bool, @@ -192,8 +271,10 @@ impl Default for CommitSettings { Self { non_modal: true, include_changes_by_default: true, + commit_all_when_nothing_staged: true, clear_initial_message: false, analyze_code: true, + postpone_slow_checks: true, check_todo: true, reformat: false, optimize_imports: false, @@ -622,6 +703,14 @@ impl Default for AgentSecuritySettings { mod tests { use super::*; + #[test] + fn clone_submodules_defaults_on_and_can_be_disabled() { + let missing: GitSettings = serde_json::from_str("{}").unwrap(); + let off: GitSettings = serde_json::from_str(r#"{"cloneSubmodules":false}"#).unwrap(); + assert!(missing.clone_submodules); + assert!(!off.clone_submodules); + } + #[test] fn git_settings_without_sync_key_execute_on_all_repositories() { let missing: GitSettings = serde_json::from_str("{}").unwrap(); diff --git a/crates/ide-host/src/environment.rs b/crates/ide-host/src/environment.rs index 246e9a3e2..c3f650eaf 100644 --- a/crates/ide-host/src/environment.rs +++ b/crates/ide-host/src/environment.rs @@ -21,7 +21,7 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::time::Duration; +use std::time::{Duration, Instant}; type Changes = Vec<(OsString, Option)>; @@ -355,20 +355,34 @@ fn run_post_start(cmd: &LifecycleCommand, root: &Path, sink: &SharedSink, cancel /// Runs `argv` in `root` with the children's environment, its stdout and stderr line by line /// to `on_line`; `Err` says how it failed. fn run_one(argv: &[String], root: &Path, cancel: &CancellationToken, on_line: &dyn Fn(String)) -> Result<(), String> { + let (program, args) = argv.split_first().ok_or("empty command")?; + let mut command = Command::new(program); + command.args(args); + run_command(command, root, cancel, None, on_line) +} + +pub(crate) fn run_command( + mut command: Command, + root: &Path, + cancel: &CancellationToken, + timeout: Option, + mut on_line: impl FnMut(String), +) -> Result<(), String> { if cancel.is_cancelled() { return Err("cancelled".into()); } - let (program, args) = argv.split_first().ok_or("empty command")?; - let mut child = ide_core::process::prepare(&mut Command::new(program)) - .args(args) + let program = command.get_program().to_string_lossy().into_owned(); + command .current_dir(root) .envs(ide_core::process::shell_env()) .stdin(Stdio::null()) .stdout(Stdio::piped()) - .stderr(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = ide_core::process::prepare(ide_core::process::own_group(&mut command)) .spawn() .map_err(|e| format!("cannot start {program}: {e}"))?; - let (tx, rx) = std::sync::mpsc::channel::(); + let started = Instant::now(); + let (tx, rx) = std::sync::mpsc::sync_channel::(64); let pipes: [Option>; 2] = [ child.stdout.take().map(|p| Box::new(p) as Box), child.stderr.take().map(|p| Box::new(p) as Box), @@ -386,29 +400,31 @@ fn run_one(argv: &[String], root: &Path, cancel: &CancellationToken, on_line: &d } drop(tx); let status = loop { + if cancel.is_cancelled() { + ide_core::process::kill_tree(&mut child); + return Err("cancelled".into()); + } + if timeout.is_some_and(|duration| started.elapsed() >= duration) { + ide_core::process::kill_tree(&mut child); + return Err("timed out".into()); + } match rx.recv_timeout(Duration::from_millis(50)) { Ok(line) => on_line(line), Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} - Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break child.wait(), - } - if cancel.is_cancelled() { - let _ = child.kill(); - let _ = child.wait(); - return Err("cancelled".into()); + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => std::thread::sleep(Duration::from_millis(50)), } // A process it started in the background may keep the pipes open: the command is done. - if let Ok(Some(status)) = child.try_wait() { - let deadline = std::time::Instant::now() + Duration::from_secs(1); + if let Some(status) = child.try_wait().map_err(|e| e.to_string())? { + let deadline = Instant::now() + Duration::from_secs(1); while let Ok(line) = rx.recv_timeout(Duration::from_millis(100)) { on_line(line); - if std::time::Instant::now() > deadline { + if Instant::now() > deadline { break; } } - break Ok(status); + break status; } - } - .map_err(|e| e.to_string())?; + }; match status.code() { Some(0) => Ok(()), Some(code) => Err(format!("exited with code {code}")), diff --git a/crates/ide-host/src/formatter.rs b/crates/ide-host/src/formatter.rs index 8485b6ed7..921b1dd1a 100644 --- a/crates/ide-host/src/formatter.rs +++ b/crates/ide-host/src/formatter.rs @@ -3,11 +3,11 @@ use crate::Host; use ide_core::event::NotifyLevel; use ide_core::settings::{BIOME_LANGUAGES, ExternalFormatter, LanguagesSettings, Settings}; -use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, Pos, Range, TextEdit}; +use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, IpcPath, LanguageId, Pos, Range, TextEdit}; use ide_language::{LanguageConfig, PhpAlignment, Syntax}; use ide_lsp::types::FormatOptions; use ide_tools::{Tools, formatter}; -use std::path::Path; +use std::path::{Path, PathBuf}; const OXFMT_CONFIGS: [&str; 4] = [".oxfmtrc.json", ".oxfmtrc.jsonc", "oxfmt.config.ts", "oxfmt.config.mts"]; /// A Biome configuration, or Biome installed as a project dependency (it then uses its defaults). @@ -173,10 +173,58 @@ pub async fn format( ) -> IdeResult> { let project = host.project(window)?; let snap = project.documents.snapshot(doc)?; + let source = FormatSource { + path: snap.path, + language: snap.language, + text: snap.text, + doc: Some(doc), + version: snap.version, + read_only: snap.read_only, + }; + format_source(host, window, &project, source, range, options).await +} + +/// Format a separate snapshot using the file's language, settings and formatter. +pub async fn format_text( + host: &Host, + window: &str, + path: PathBuf, + text: String, + options: FormatOptions, +) -> IdeResult> { + let project = host.project(window)?; + if !path.is_absolute() || path.file_name().is_none() { + return Err(IdeError::invalid("formatting requires a file path")); + } + if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD { + return Ok(Vec::new()); + } + let language = project.documents.language_of(&path, text.lines().next()).language; + let source = FormatSource { path: path.into(), language, text, doc: None, version: 0, read_only: false }; + format_source(host, window, &project, source, None, options).await +} + +struct FormatSource { + path: IpcPath, + language: LanguageId, + text: String, + doc: Option, + version: u32, + read_only: bool, +} + +async fn format_source( + host: &Host, + window: &str, + project: &crate::Project, + snap: FormatSource, + range: Option, + options: FormatOptions, +) -> IdeResult> { let settings = project.settings.effective(); let alignment = php_alignment(&settings, &snap.language); let original = alignment.any().then(|| (snap.language.clone(), snap.text.clone())); - let Some(edits) = provider_edits(host, window, &project, snap, settings, range, options).await? else { + let Some(edits) = provider_edits(host, window, project, snap, settings, range, options).await? else { return Ok(Vec::new()); }; let Some((language, text)) = original else { @@ -257,12 +305,12 @@ async fn provider_edits( host: &Host, window: &str, project: &crate::Project, - snap: ide_workspace::documents::DocumentInfo, + snap: FormatSource, settings: Settings, range: Option, options: FormatOptions, ) -> IdeResult>> { - let doc = snap.id; + let doc = snap.doc; let language = project.languages.get(&snap.language); if options.tool.is_none() && let Some(id) = settings.languages.plugin_formatters.get(snap.language.as_str()).filter(|s| !s.is_empty()) @@ -329,7 +377,10 @@ async fn provider_edits( if let Some(tool) = selected && options.tool.is_none() && !settings.languages.formatter(tool).prefer - && project.lsp.can_format(doc).await? + && match doc { + Some(doc) => project.lsp.can_format(doc).await?, + None => project.lsp.can_format_text(&snap.path, &snap.language).await, + } { selected = None; } @@ -337,7 +388,10 @@ async fn provider_edits( if options.on_save && !settings.editor.format_on_save { return Ok(None); } - let edits = project.lsp.format(doc, range, options).await?; + let edits = match doc { + Some(doc) => project.lsp.format(doc, range, options).await?, + None => project.lsp.format_text(&snap.path, &snap.language, &snap.text, options).await?, + }; let text = snap.text; return tokio::task::spawn_blocking(move || Some(minimal_edits(&text, edits))) .await diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 39221365a..527f19a1e 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -92,6 +92,7 @@ pub struct Host { /// The window that owns each open heap snapshot; its project's close closes them. pub(crate) heap_windows: Mutex>, pub(crate) heap_requests: ops::heap::HeapRequests, + pub(crate) rebase_editors: Arc, /// SSH connections of Settings › SSH Configurations. pub ssh: Arc, /// SFTP deployment, remote file editing and runs on run targets. @@ -190,6 +191,7 @@ impl Host { heap: Arc::new(ide_heap::HeapRegistry::new(ide_heap::snapshots_root(&local_data_dir))), heap_windows: Mutex::default(), heap_requests: Default::default(), + rebase_editors: Default::default(), languages, syntax, config_dir, diff --git a/crates/ide-host/src/mcp/vcs.rs b/crates/ide-host/src/mcp/vcs.rs index 49e56f574..8d20b8ce7 100644 --- a/crates/ide-host/src/mcp/vcs.rs +++ b/crates/ide-host/src/mcp/vcs.rs @@ -102,9 +102,7 @@ This is useful to detect all repositories in a multi-repository project. In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached), `headCommit` and a merge, \ rebase or cherry-pick in progress (`operationInProgress`).", |call| async move { - let host = call.host(); - let window = call.window.clone(); - let roots = call.host.blocking(move || crate::ops::vcs::vcs_roots(&host, &window)).await?; + let roots = crate::ops::vcs::vcs_roots(&call.host(), &call.window).await?; let list: Vec = roots .into_iter() .map(|r| { @@ -257,10 +255,7 @@ By default all Git repositories are returned.", let include_ignored = call.flag("includeIgnored", false)?; let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?; let host = call.host(); - let h = host.clone(); - let w = call.window.clone(); - let repos: Vec<(PathBuf, Option)> = host - .blocking(move || crate::ops::vcs::vcs_roots(&h, &w)) + let repos: Vec<(PathBuf, Option)> = crate::ops::vcs::vcs_roots(&host, &call.window) .await? .into_iter() .map(|r| (r.root.into_path_buf(), r.head)) diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs index d830d103d..d1c05f624 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -1606,6 +1606,62 @@ pub async fn lsp_format( crate::formatter::format(host, window, doc, range, options).await } +#[command(trust = trusted)] +pub async fn lsp_format_text( + host: &Host, + window: &str, + path: std::path::PathBuf, + text: String, + options: FormatOptions, +) -> IdeResult> { + crate::formatter::format_text(host, window, path, text, options).await +} + +#[command(trust = trusted)] +pub async fn lsp_source_action_text( + host: &Host, + window: &str, + path: std::path::PathBuf, + text: String, + kind: String, + request: RequestId, +) -> IdeResult> { + let project = host.project(window)?; + if !path.is_absolute() || path.file_name().is_none() { + return Err(IdeError::invalid("a text snapshot requires a file path")); + } + if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD { + return Ok(Vec::new()); + } + let language = project.documents.language_of(&path, text.lines().next()).language; + let cancel = host.begin_project_read_request(window, request); + let result = project.lsp.source_action_text(&path, &language, &text, &kind, &cancel).await; + host.end_request(request); + result +} + +#[command(trust = trusted)] +pub async fn lsp_snapshot_diagnostics( + host: &Host, + window: &str, + path: std::path::PathBuf, + text: String, + request: RequestId, +) -> IdeResult> { + let project = host.project(window)?; + if !path.is_absolute() || path.file_name().is_none() { + return Err(IdeError::invalid("a text snapshot requires a file path")); + } + if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD { + return Ok(Vec::new()); + } + let language = project.documents.language_of(&path, text.lines().next()).language; + let cancel = host.begin_project_read_request(window, request); + let result = project.lsp.snapshot_diagnostics(&path, &language, &text, &cancel).await; + host.end_request(request); + result +} + #[command(trust = trusted)] pub async fn lsp_inlay_hints(host: &Host, window: &str, doc: DocId, range: Range) -> IdeResult> { let lsp = host.project(window)?.lsp.clone(); @@ -2808,6 +2864,9 @@ ide_command::domain!( lsp_extract_interface, lsp_extract_interface_info, lsp_format, + lsp_format_text, + lsp_snapshot_diagnostics, + lsp_source_action_text, lsp_goto, lsp_goto_implementation, lsp_hierarchy_members, diff --git a/crates/ide-host/src/ops/vcs.rs b/crates/ide-host/src/ops/vcs.rs index 8b9d340c4..0f6e6b827 100644 --- a/crates/ide-host/src/ops/vcs.rs +++ b/crates/ide-host/src/ops/vcs.rs @@ -22,6 +22,21 @@ pub async fn vcs_status(host: &Host, window: &str) -> IdeResult> .await } +#[command(trust = always)] +pub async fn vcs_ignored_files(host: &Host, window: &str) -> IdeResult> { + let project = host.project(window)?; + host.blocking(move || { + let settings = project.settings.effective(); + let repos = project.repos(); + let ignored = settings.ignored_names(); + for repo in repos.all() { + repo.set_ignored_names(ignored.clone()); + } + repos.ignored_files() + }) + .await +} + /// Changes of `paths` only: the dirty-scope refresh after a watcher batch. #[command(trust = always)] pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec) -> IdeResult> { @@ -43,7 +58,10 @@ pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec>, @@ -153,18 +159,61 @@ pub struct VcsRoot { pub branch_root: ide_core::IpcPath, /// Merge / rebase / cherry-pick / revert in progress. pub operation: Option, + /// The current rebase uses Git's interactive mode. + #[serde(default)] + #[specta(optional)] + pub interactive_rebase: bool, /// Current branch; `None` when HEAD is detached (or unreadable). pub head: Option, /// HEAD commit; `None` before the first commit. pub head_commit: Option, + /// The history ends at a shallow boundary rather than at the initial commit. + #[serde(default)] + pub shallow: bool, + /// Remote availability is unknown in Restricted Mode or when config cannot be read. + #[serde(default)] + #[specta(optional)] + pub has_remotes: Option, + /// Conflicts staged during the current operation that can be reopened. + #[serde(default)] + pub resolved_conflicts: Vec, } #[derive(Clone, Serialize, Deserialize, Type)] #[serde(tag = "op", rename_all = "camelCase")] pub enum RemoteOp { - Fetch, + Fetch { + /// The incoming-commit poll keeps Git's tag handling and uses saved credentials only. + #[serde(default)] + #[specta(optional)] + background: bool, + #[serde(default)] + #[specta(optional)] + report: bool, + #[serde(default, rename = "skipRemotes")] + #[specta(optional)] + skip_remotes: Vec, + }, + FetchRemote { + remote: String, + #[serde(default)] + #[specta(optional)] + report: bool, + }, + FetchPushTarget { + selection: PushSelection, + }, + Unshallow, Pull { rebase: bool, + #[serde(default, rename = "expectedBranch")] + expected_branch: Option, + }, + UpdateProjectBranch { + rebase: bool, + }, + UpdateSubmodule { + parent: PathBuf, }, /// Update Project › Reset to the Remote Branch. ResetToUpstream, @@ -181,6 +230,20 @@ pub enum RemoteOp { #[serde(default)] no_verify: bool, }, + PushSelected { + selection: PushSelection, + force_with_lease: bool, + set_upstream: bool, + tags: Option, + no_verify: bool, + #[serde(default)] + inspected: Option, + }, + ForcePushRejected { + divergence: PushDivergence, + tags: Option, + no_verify: bool, + }, /// Deletes a remote branch; `branch` is the remote-tracking name (`origin/feature`). DeleteBranch { branch: String, @@ -214,15 +277,26 @@ pub enum RemoteOp { tag: String, remote: String, }, + DeleteTagOnRemotes { + deleted: DeletedTag, + }, /// Pull dialog: `branches` of `remote` (none = the configured merge branch). PullFrom { remote: String, branches: Vec, - rebase: bool, + /// Explicit rebase or merge. Null uses Git's configured pull behavior. + rebase: Option, options: MergeOptions, }, } +#[derive(Serialize, Deserialize, Type)] +#[serde(untagged)] +pub enum RemoteOpReport { + Push(PushReport), + Fetch(FetchReport), +} + #[derive(Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct GitExecutableInfo { @@ -239,15 +313,33 @@ pub struct GitExecutableInfo { pub enum GitOperation { /// Continue the merge / rebase / cherry-pick / revert in progress. Continue, + ContinueReviewedApply { + checkpoint: String, + message: String, + #[serde(default)] + options: ApplyCommitOptions, + }, + FinishMerge { + branch: Option, + head: String, + target: String, + }, /// Stage and Retry: stage the changes of tracked files, then continue. StageAndContinue, - Abort, + Abort { + #[serde(default)] + expected: Option, + #[serde(default, rename = "expectedRebase", skip_serializing_if = "Option::is_none")] + expected_rebase: Option, + }, Skip, - /// Commits oldest first; `record_origin` adds "(cherry picked from commit …)". + /// Commits oldest first; add the origin for all commits or the specified subset. CherryPick { commits: Vec, #[serde(default, rename = "recordOrigin")] record_origin: bool, + #[serde(default, rename = "recordOriginFor")] + record_origin_for: Vec, }, /// Commits newest first. Revert { @@ -262,6 +354,36 @@ pub enum GitOperation { base: Option, entries: Vec, }, + CheckoutRebase { + plan: CheckoutRebasePlan, + #[serde(rename = "shelfBatch")] + shelf_batch: Option, + }, + RebaseBranch { + plan: BranchRebasePlan, + #[serde(rename = "shelfBatch")] + shelf_batch: Option, + }, + DropCommitChanges { + commit: String, + #[serde(rename = "expectedHead")] + expected_head: HistoryTip, + paths: Vec, + }, +} + +#[derive(Clone, Serialize, Deserialize, Type)] +#[serde(untagged)] +pub enum GitOperationResult { + Rewritten(RewrittenCommit), + Rebased { + rebased: HistoryTip, + }, + EmptyCherryPicks { + #[serde(rename = "emptyCherryPicks")] + empty_cherry_picks: u32, + action: EmptyCherryPickAction, + }, } /// Runs `f` once per repository with the `paths` that belong to it. @@ -291,24 +413,20 @@ fn per_backend( per_repo(project, paths, recorded, |r, paths| f(r as &dyn Backend, paths)) } -/// A shelf is one patch for one owning repository. Validate the whole selection before reverting files. -fn shelf_repository(project: &Project, paths: &[PathBuf]) -> IdeResult { - let repos = project.repos(); - let root = paths - .first() - .and_then(|p| repos.for_path(p)) - .map(|r| r.root()) - .ok_or_else(|| ide_core::IdeError::invalid("select files in a git repository to shelve"))?; - if paths.iter().any(|p| repos.for_path(p).map(|r| r.root()) != Some(root)) { - return Err(ide_core::IdeError::invalid("select files from a single git repository to shelve")); - } - Ok(root.to_path_buf()) -} - async fn blocking(f: impl FnOnce() -> IdeResult + Send + 'static) -> IdeResult { tokio::task::spawn_blocking(f).await.map_err(|e| ide_core::IdeError::internal(e.to_string()))? } +fn with_shelf_batch(project: &Project, batch: Option, operation: impl FnOnce() -> T) -> T { + let Some(batch) = batch.and_then(|id| uuid::Uuid::parse_str(&id).ok()) else { return operation() }; + let repos = project.repos(); + let Some(base) = project.root.ancestors().find(|base| repos.all().iter().all(|repo| repo.root().starts_with(base))) + else { + return operation(); + }; + ide_vcs::shelf::ShelfBatch::new(batch.to_string(), base.to_path_buf()).run(operation) +} + // ---- patches ---- #[derive(Clone, Serialize, Deserialize, Type)] @@ -316,8 +434,65 @@ async fn blocking(f: impl FnOnce() -> IdeResult + Send + ' pub enum PatchSource { /// Local changes of these files (absolute paths). Changes { paths: Vec, reverse: bool }, + /// Changes selected on either side of the index in the staging tree. + Staging { entries: Vec, reverse: bool }, /// Changes made by these commits (oldest first). Commits { commits: Vec, reverse: bool }, + /// Selected files between two revisions, including both paths of a rename. + Revisions { before: String, after: String, paths: Vec }, +} + +fn patch_export_base(project: &Project, base: PathBuf) -> IdeResult { + let base = if base.is_absolute() { base } else { project.root.join(base) }; + dunce::canonicalize(base) + .ok() + .filter(|base| base.is_dir()) + .ok_or_else(|| ide_core::IdeError::invalid("Choose an existing base directory")) +} + +fn export_patch(patch: String, root: &Path, base: Option<&Path>) -> IdeResult { + match base { + Some(base) => rebase_patch(&patch, root, "", base), + None => Ok(patch), + } +} + +fn create_staging_patch( + project: &Project, + entries: Vec, + reverse: bool, + base: Option<&Path>, +) -> IdeResult { + let repos = project.repos(); + let mut groups = BTreeMap::<_, Vec<_>>::new(); + for entry in entries { + let repo = repos.for_path(&entry.path.0).ok_or_else(|| ide_core::IdeError::invalid("no files selected"))?; + groups.entry(repo.root().to_path_buf()).or_default().push(entry); + } + let common = if base.is_none() && groups.len() > 1 { + Some( + project + .root + .ancestors() + .find(|base| groups.keys().all(|root| root.starts_with(base))) + .ok_or_else(|| ide_core::IdeError::invalid("The selected repositories have no common directory"))?, + ) + } else { + None + }; + let mut patch = String::new(); + for (root, entries) in groups { + let prefix = common + .and_then(|base| root.strip_prefix(base).ok()) + .filter(|relative| !relative.as_os_str().is_empty()) + .map(|relative| format!("{}/", ide_core::ipc_path::to_ipc(relative))) + .unwrap_or_default(); + patch.push_str(&project.with_repo_at(Some(&root), |r| { + let patch = r.create_staging_patch(&entries, reverse, &prefix)?; + export_patch(patch, r.root(), base) + })?); + } + Ok(patch) } // ---- shelf (`.openidea/shelf`) and change lists (`.openidea/changelists.json`) ---- @@ -343,35 +518,53 @@ pub async fn vcs_detected_roots(host: &Host, window: &str) -> IdeResult IdeResult> { - let repos = host.project(window)?.repos(); - let primary = repos.primary().map(|r| r.root().to_path_buf()); - let mut all: Vec<&std::sync::Arc> = repos.all().iter().collect(); - all.sort_by_key(|r| Some(r.root()) != primary.as_deref()); - let roots: Vec<_> = all.into_iter().map(|repo| (repo, repo.metadata_dirs().ok())).collect(); - let mut branch_roots = std::collections::HashMap::new(); - for (repo, dirs) in &roots { - if let Some([git_dir, common_dir]) = dirs { - let first = branch_roots.entry(common_dir).or_insert(repo.root()); - if git_dir == common_dir { - *first = repo.root(); +pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult> { + let project = host.project(window)?; + let repos = project.repos(); + let trusted = project.is_trusted(); + blocking(move || { + let primary = repos.primary().map(|r| r.root().to_path_buf()); + let mut all: Vec<_> = repos.all().iter().collect(); + all.sort_by_key(|r| Some(r.root()) != primary.as_deref()); + let roots: Vec<_> = all.into_iter().map(|repo| (repo, repo.metadata_dirs().ok())).collect(); + let mut branch_roots = std::collections::HashMap::new(); + for (repo, dirs) in &roots { + if let Some([git_dir, common_dir]) = dirs { + let first = branch_roots.entry(common_dir).or_insert(repo.root()); + if git_dir == common_dir { + *first = repo.root(); + } } } - } - Ok(roots - .iter() - .map(|(r, dirs)| { - let (head, head_commit) = r.head().unwrap_or_default(); - let branch_root = dirs.as_ref().and_then(|[_, common_dir]| branch_roots.get(common_dir)); - VcsRoot { - root: r.root().into(), - branch_root: branch_root.copied().unwrap_or_else(|| r.root()).into(), - operation: r.operation().ok().flatten(), - head, - head_commit, - } - }) - .collect()) + Ok(roots + .iter() + .map(|(r, dirs)| { + let branch_root = dirs.as_ref().and_then(|[_, common_dir]| branch_roots.get(common_dir)); + let (head, head_commit) = r.head().unwrap_or_default(); + let operation = r.operation().ok().flatten(); + let interactive_rebase = operation.as_deref() == Some("rebase") && r.is_interactive_rebase(); + let resolved_conflicts = operation + .as_ref() + .and_then(|_| r.resolved_conflicts().ok()) + .unwrap_or_default() + .into_iter() + .map(Into::into) + .collect(); + VcsRoot { + root: r.root().into(), + branch_root: branch_root.copied().unwrap_or_else(|| r.root()).into(), + operation, + interactive_rebase, + head, + head_commit, + shallow: r.is_shallow().unwrap_or(false), + has_remotes: trusted.then(|| r.has_remotes().ok()).flatten(), + resolved_conflicts, + } + }) + .collect()) + }) + .await } #[command(trust = always)] @@ -380,6 +573,21 @@ pub async fn vcs_branch_info(host: &Host, window: &str, repo: Option) - blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.branch_info())).await } +#[command(trust = trusted)] +pub async fn vcs_check_incoming( + host: &Host, + window: &str, + repo: PathBuf, + request: RequestId, +) -> IdeResult { + host.require_trust(window)?; + let project = host.project(window)?; + let cancel = host.begin_project_request(window, request); + let result = blocking(move || project.with_repo_at(Some(&repo), |r| r.check_incoming_refs(&cancel))).await; + host.end_request(request); + result +} + /// Gutter change markers for a file, computed against its current (unsaved) text. #[command(trust = always)] pub async fn vcs_line_hunks(host: &Host, window: &str, path: PathBuf) -> IdeResult> { @@ -391,6 +599,29 @@ pub async fn vcs_line_hunks(host: &Host, window: &str, path: PathBuf) -> IdeResu .await } +#[command(trust = always)] +pub async fn vcs_staging_line_hunks( + host: &Host, + window: &str, + path: PathBuf, + head_path: Option, +) -> IdeResult> { + let project = host.project(window)?; + blocking(move || { + let text = project.text_of(&path)?; + project.with_repo_of(&path, |repo| { + repo.staging_line_hunks( + &path, + head_path.as_deref(), + &text, + ide_vfs::READ_ONLY_THRESHOLD as usize, + |path, bytes| project.staged_file_encoding(path, bytes), + ) + }) + }) + .await +} + #[command(trust = always)] pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option) -> IdeResult> { let project = host.project(window).ok(); @@ -431,6 +662,40 @@ pub async fn vcs_file_mode(host: &Host, window: &str, path: PathBuf, rev: Option .await } +#[derive(Serialize, Deserialize, Type)] +pub struct DiffEntryRequest { + pub path: IpcPath, + pub rev: String, +} + +#[command(trust = always)] +pub async fn vcs_diff_entries( + host: &Host, + window: &str, + entries: Vec, +) -> IdeResult>> { + let project = host.project(window).ok(); + let external = host.external_logs.read().get(host.owner_window(window)).cloned().unwrap_or_default(); + blocking(move || { + Ok(entries + .into_iter() + .map(|DiffEntryRequest { path: IpcPath(path), rev }| { + if let Some(project) = &project { + return project.with_log_repo_of(&path, |repo| repo.diff_entry_at(&path, &rev)).ok().flatten(); + } + external + .iter() + .filter(|repo| path.starts_with(repo.root()) && path != repo.root()) + .max_by_key(|repo| repo.root().components().count())? + .diff_entry_at(&path, &rev) + .ok() + .flatten() + }) + .collect()) + }) + .await +} + #[command(trust = always)] pub async fn vcs_blame( host: &Host, @@ -443,8 +708,15 @@ pub async fn vcs_blame( // An explicit text wins (merge view annotates its side panes, not the worktree). blocking(move || { let text = text.or_else(|| project.documents.text_of(&path)); - project.with_backend_of(&path, |r| { - r.blame(&path, text.as_deref(), revision.as_deref(), project.vcs_encoding(&path, revision.as_deref())?) + project.with_backend_of(&path, |backend| { + let encoding = project.vcs_encoding(&path, revision.as_deref())?; + let text = text.as_deref(); + let revision = revision.as_deref(); + if let Some(repo) = backend.as_git() { + repo.blame_with_options(&path, text, revision, encoding, project.settings.effective().vcs.git.annotate) + } else { + backend.blame(&path, text, revision, encoding) + } }) }) .await @@ -493,6 +765,24 @@ pub async fn vcs_log(host: &Host, window: &str, repo: Option, query: Lo result } +#[command(trust = always)] +pub async fn vcs_not_cherry_picked( + host: &Host, + window: &str, + repo: Option, + source: String, + target: String, + request: RequestId, +) -> IdeResult>> { + let project = LogAccess::new(host, window, repo.as_deref()); + let cancel = host.begin_project_read_request(window, request); + let result = + blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.not_cherry_picked(&source, &target, &cancel))) + .await; + host.end_request(request); + result +} + #[command(trust = always)] pub async fn vcs_log_refs( host: &Host, @@ -559,6 +849,19 @@ pub async fn vcs_log_details_batch( result } +/// Clears cached verification results before refreshing the Git Log. +#[command(trust = always)] +pub async fn vcs_invalidate_log_signatures(host: &Host, window: &str, repo: PathBuf) -> IdeResult<()> { + let project = LogAccess::new(host, window, Some(&repo)); + blocking(move || { + project.with_log_repo_at(Some(&repo), |repo| { + repo.invalidate_log_signatures(); + Ok(()) + }) + }) + .await +} + #[command(trust = always)] pub async fn vcs_revision_children( host: &Host, @@ -593,6 +896,60 @@ pub async fn vcs_commit_files( blocking(move || project.with_log_backend_at(repo.as_deref(), |r| r.commit_files(&commit))).await } +#[command(trust = trusted)] +pub async fn vcs_preview_partial_commit(host: &Host, window: &str, file: PartialCommitFile) -> IdeResult { + let project = host.project(window)?; + blocking(move || { + let path = &file.path.0; + let encoding = project.vcs_encoding(path, None)?; + project.with_repo_of(path, |repo| repo.preview_partial_commit(&file, encoding)) + }) + .await +} + +#[command(trust = trusted)] +pub async fn vcs_commit_crlf_paths( + host: &Host, + window: &str, + repo: PathBuf, + paths: Vec, + options: CommitOptions, + request: RequestId, +) -> IdeResult> { + let project = host.project(window)?; + let cancel = host.begin_project_read_request(window, request); + let result = blocking(move || { + project.with_repo_at(Some(&repo), |r| { + r.commit_crlf_paths(&paths, &options, &|path| project.vcs_encoding(path, None), &cancel) + }) + }) + .await; + host.end_request(request); + result +} + +#[command(trust = trusted)] +pub async fn vcs_commit_large_files( + host: &Host, + window: &str, + repo: PathBuf, + paths: Vec, + options: CommitOptions, + limit: u64, + request: RequestId, +) -> IdeResult> { + let project = host.project(window)?; + let cancel = host.begin_project_read_request(window, request); + let result = blocking(move || { + project.with_repo_at(Some(&repo), |r| { + r.commit_large_files(&paths, &options, limit, &|path| project.vcs_encoding(path, None), &cancel) + }) + }) + .await; + host.end_request(request); + result +} + /// Combined changes of several commits, `commits` oldest first. #[command(trust = always)] pub async fn vcs_commits_changes( @@ -605,6 +962,23 @@ pub async fn vcs_commits_changes( blocking(move || project.with_log_backend_at(repo.as_deref(), |r| r.commits_changes(&commits))).await } +#[command(trust = always)] +pub async fn vcs_commit_selection_changes( + host: &Host, + window: &str, + repo: Option, + commits: Vec, + request: RequestId, +) -> IdeResult> { + let project = LogAccess::new(host, window, repo.as_deref()); + let cancel = host.begin_project_read_request(window, request); + let result = + blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.commit_selection_changes(&commits, &cancel))) + .await; + host.end_request(request); + result +} + #[command(trust = always)] pub async fn vcs_branches(host: &Host, window: &str, repo: Option) -> IdeResult> { let project = LogAccess::new(host, window, repo.as_deref()); @@ -624,6 +998,12 @@ pub async fn vcs_stage(host: &Host, window: &str, paths: Vec) -> IdeRes blocking(move || per_backend(&project, &paths, None, |r, paths| r.stage(paths))).await } +#[command(trust = trusted)] +pub async fn vcs_stage_without_content(host: &Host, window: &str, paths: Vec) -> IdeResult<()> { + let project = host.project(window)?; + blocking(move || per_repo(&project, &paths, None, Repo::stage_without_content)).await +} + #[command(trust = trusted)] pub async fn vcs_ignore_blame_revision(host: &Host, window: &str, path: PathBuf, commit: String) -> IdeResult<()> { // Adds `commit` to annotate's ignore list in `path`'s repository (the file `blame.ignoreRevsFile` @@ -687,6 +1067,55 @@ pub async fn vcs_stage_patch(host: &Host, window: &str, patch: String) -> IdeRes blocking(move || project.with_repo(|r| r.stage_patch(&patch, &|path| project.vcs_encoding(path, Some(":0"))))).await } +#[command(trust = trusted)] +pub async fn vcs_stage_formatted_text( + host: &Host, + window: &str, + path: PathBuf, + before: String, + after: String, +) -> IdeResult<()> { + let project = host.project(window)?; + blocking(move || { + let encoding = project.vcs_encoding(&path, Some(":0"))?; + project.with_repo_of(&path, |r| r.stage_formatted_text(&path, &before, &after, encoding)) + }) + .await +} + +#[command(trust = trusted)] +pub async fn vcs_staged_text(host: &Host, window: &str, path: PathBuf) -> IdeResult> { + let project = host.project(window)?; + blocking(move || { + project.with_repo_of(&path, |repo| { + repo.staged_text(&path, ide_vfs::READ_ONLY_THRESHOLD as usize, |bytes| { + project.staged_file_encoding(&path, bytes) + }) + }) + }) + .await +} + +#[command(trust = trusted)] +pub async fn vcs_save_staged_text( + host: &Host, + window: &str, + path: PathBuf, + version: String, + text: String, +) -> IdeResult { + if text.len() as u64 > ide_vfs::READ_ONLY_THRESHOLD { + return Err(ide_core::IdeError::invalid("File is too large")); + } + let project = host.project(window)?; + blocking(move || { + project.with_repo_of(&path, |repo| { + repo.save_staged_text(&path, &version, &text, |bytes| project.staged_file_encoding(&path, bytes)) + }) + }) + .await +} + #[command(trust = trusted)] pub async fn vcs_discard(host: &Host, window: &str, paths: Vec) -> IdeResult<()> { host.require_trust(window)?; @@ -694,6 +1123,33 @@ pub async fn vcs_discard(host: &Host, window: &str, paths: Vec) -> IdeR blocking(move || per_backend(&project, &paths, Some("Rollback"), |r, paths| r.discard(paths))).await } +#[command(trust = trusted)] +pub async fn vcs_restore_unstaged(host: &Host, window: &str, paths: Vec) -> IdeResult<()> { + let project = host.project(window)?; + blocking(move || per_repo(&project, &paths, Some("Rollback"), Repo::restore_unstaged)).await +} + +#[command(trust = trusted)] +pub async fn vcs_rollback_submodules( + host: &Host, + window: &str, + paths: Vec, + source: SubmoduleRollbackSource, + restore_checkout: bool, +) -> IdeResult<()> { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || { + per_repo(&project, &paths, Some("Rollback"), |repo, paths| { + for path in paths { + repo.rollback_submodule(path, source, restore_checkout)?; + } + Ok(()) + }) + }) + .await +} + #[command(trust = trusted)] pub async fn vcs_commit( host: &Host, @@ -713,6 +1169,14 @@ pub async fn vcs_commit( .await } +/// Keeps the prepared amend commit after a conflicting history replay. +#[command(trust = trusted)] +pub async fn vcs_keep_amend_commit(host: &Host, window: &str, repo: PathBuf, commit: String) -> IdeResult { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || project.with_repo_recorded(Some(&repo), None, |r| r.keep_amend_commit(&commit))).await +} + #[command(trust = trusted)] pub async fn vcs_checkout( host: &Host, @@ -721,18 +1185,51 @@ pub async fn vcs_checkout( branch: String, create: bool, options: Option, + shelf_batch: Option, ) -> IdeResult { host.require_trust(window)?; let project = host.project(window)?; let options = options.unwrap_or_default(); blocking(move || { - project - .with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| r.checkout_with(&branch, create, &options)) + with_shelf_batch(&project, shelf_batch, || { + project.with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| { + r.checkout_with(&branch, create, &options) + }) + }) }) .await } +#[command(trust = trusted)] +pub async fn vcs_checkout_affected_files( + host: &Host, + window: &str, + repositories: Vec, + branch: String, +) -> IdeResult)>> { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || Ok(affected_repo_files(&project, repositories, |r| r.checkout_affected_files(&branch)))).await +} + +fn affected_repo_files( + project: &Project, + repositories: Vec, + inspect: impl Fn(&Repo) -> IdeResult>, +) -> Vec<(ide_core::IpcPath, Vec)> { + let mut affected = Vec::new(); + for root in repositories { + match project.with_repo_at(Some(&root), &inspect) { + Ok(files) if !files.is_empty() => affected.push((root, files)), + Ok(_) => {} + Err(error) => tracing::debug!("local changes preview: {}", error.message), + } + } + affected +} + /// New Branch: creates `name` at `start` (HEAD when absent), optionally checking it out. +#[allow(clippy::too_many_arguments)] #[command(trust = trusted)] pub async fn vcs_create_branch( host: &Host, @@ -742,13 +1239,45 @@ pub async fn vcs_create_branch( start: Option, checkout: bool, overwrite: Option, -) -> IdeResult<()> { + expected_tip: Option, + options: Option, + shelf_batch: Option, +) -> IdeResult { host.require_trust(window)?; let project = host.project(window)?; let recorded = checkout.then_some("Git checkout"); + let options = checkout.then(|| options.unwrap_or_default()); + blocking(move || { + with_shelf_batch(&project, shelf_batch, || { + project.with_repo_recorded(repo.as_deref(), recorded, |r| { + r.create_branch_with( + &name, + start.as_deref(), + options.as_ref(), + overwrite.unwrap_or(false), + expected_tip.as_deref(), + ) + }) + }) + }) + .await +} + +#[command(trust = trusted)] +pub async fn vcs_undo_branch_creation( + host: &Host, + window: &str, + repo: Option, + name: String, + created: BranchCreation, + previous_head: Option, +) -> IdeResult<()> { + host.require_trust(window)?; + let project = host.project(window)?; + let recorded = previous_head.is_some().then_some("Git rollback"); blocking(move || { project.with_repo_recorded(repo.as_deref(), recorded, |r| { - r.create_branch_with_overwrite(&name, start.as_deref(), checkout, overwrite.unwrap_or(false)) + r.undo_branch_creation(&name, &created, previous_head.as_ref()) }) }) .await @@ -778,6 +1307,24 @@ pub async fn vcs_reword( blocking(move || project.with_repo_at(repo.as_deref(), |r| r.reword(&commit, &message))).await } +#[command(trust = trusted)] +pub async fn vcs_extract_commit_changes( + host: &Host, + window: &str, + repo: Option, + commit: String, + expected_head: HistoryTip, + paths: Vec, + message: String, +) -> IdeResult { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || { + project.with_repo_at(repo.as_deref(), |r| r.extract_commit_changes(&commit, &expected_head, &paths, &message)) + }) + .await +} + /// Undo of a history rewrite (Edit Commit Message, Drop, Squash). #[command(trust = trusted)] pub async fn vcs_restore_head( @@ -786,10 +1333,22 @@ pub async fn vcs_restore_head( repo: Option, before: String, after: String, + branch: Option, + checkout: Option, ) -> IdeResult<()> { host.require_trust(window)?; let project = host.project(window)?; - blocking(move || project.with_repo_at(repo.as_deref(), |r| r.restore_head(&before, &after))).await + blocking(move || { + let recorded = branch.is_some().then_some("Git rollback"); + project.with_repo_recorded(repo.as_deref(), recorded, |r| match checkout { + Some(checkout) => { + let branch = branch.ok_or_else(|| ide_core::IdeError::invalid("The rebased branch is required"))?; + r.restore_rebase_checkout(&before, &after, &branch, &checkout) + } + None => r.restore_head_on_branch(&before, &after, branch.as_deref()), + }) + }) + .await } #[command(trust = trusted)] @@ -804,6 +1363,38 @@ pub async fn vcs_delete_branch( blocking(move || project.with_repo_at(repo.as_deref(), |r| r.delete_branch_restorable(&branch))).await } +/// Deletes a local tracking branch the user selected along with its remote branch. +#[command(trust = trusted)] +pub async fn vcs_delete_tracking_branch( + host: &Host, + window: &str, + repo: Option, + branch: String, + expected_tip: String, + expected_upstream: String, +) -> IdeResult { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || { + project.with_repo_at(repo.as_deref(), |r| r.delete_tracking_branch(&branch, &expected_tip, &expected_upstream)) + }) + .await +} + +/// Deletes a branch offered for cleanup by a successful merge. +#[command(trust = trusted)] +pub async fn vcs_delete_merged_branch( + host: &Host, + window: &str, + repo: PathBuf, + branch: String, + expected_tip: String, +) -> IdeResult { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || project.with_repo_at(Some(&repo), |r| r.delete_merged_branch(&branch, &expected_tip))).await +} + /// Tag › Delete: the result is what "Restore" needs. #[command(trust = trusted)] pub async fn vcs_delete_tag(host: &Host, window: &str, repo: Option, name: String) -> IdeResult { @@ -848,17 +1439,84 @@ pub async fn vcs_rename_branch( } #[command(trust = trusted)] -pub async fn vcs_merge(host: &Host, window: &str, repo: Option, branch: String) -> IdeResult<()> { +pub async fn vcs_merge( + host: &Host, + window: &str, + repo: Option, + branch: String, + shelf_batch: Option, + smart: bool, +) -> IdeResult { host.require_trust(window)?; let project = host.project(window)?; - blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git merge"), |r| r.merge(&branch))).await + blocking(move || { + with_shelf_batch(&project, shelf_batch, || { + project.with_repo_recorded(repo.as_deref(), Some("Git merge"), |r| { + r.merge_attempt(&[branch], &MergeOptions::default(), smart) + }) + }) + }) + .await } #[command(trust = trusted)] -pub async fn vcs_rebase(host: &Host, window: &str, repo: Option, onto: String) -> IdeResult<()> { +pub async fn vcs_merge_affected_files( + host: &Host, + window: &str, + repositories: Vec, + branch: String, +) -> IdeResult)>> { host.require_trust(window)?; let project = host.project(window)?; - blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git rebase"), |r| r.rebase(&onto))).await + blocking(move || Ok(affected_repo_files(&project, repositories, |r| r.merge_affected_files(&branch)))).await +} + +#[command(trust = trusted)] +pub async fn vcs_rebase( + host: &Host, + window: &str, + repo: Option, + onto: String, + shelf_batch: Option, +) -> IdeResult<()> { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || { + with_shelf_batch(&project, shelf_batch, || { + project.with_repo_recorded(repo.as_deref(), Some("Git rebase"), |r| r.rebase(&onto)) + }) + }) + .await +} + +/// Restores the batch's ready repositories. A repository with an operation in progress keeps its Shelf. +#[command(trust = trusted)] +pub async fn vcs_finish_shelf_batch( + host: &Host, + window: &str, + batch: String, + repositories: Vec>, +) -> IdeResult<()> { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || { + let mut errors = Vec::new(); + for repo in repositories { + if let Err(error) = project + .with_repo_recorded(repo.as_deref(), Some("Restore shelved changes"), |r| r.finish_shelf_batch(&batch)) + { + errors.push(error); + } + } + match errors.len() { + 0 => Ok(()), + 1 => Err(errors.remove(0)), + _ => Err(ide_core::IdeError::invalid( + errors.into_iter().map(|error| error.message).collect::>().join("\n"), + )), + } + }) + .await } #[command(trust = trusted)] @@ -892,30 +1550,119 @@ pub async fn vcs_stash_apply( host: &Host, window: &str, repo: Option, - index: u32, + stash: Stash, pop: bool, reinstate_index: bool, branch: Option, -) -> IdeResult<()> { +) -> IdeResult { host.require_trust(window)?; let project = host.project(window)?; blocking(move || { - project.with_repo_recorded(repo.as_deref(), Some("Git unstash"), |r| match branch.as_deref() { - Some(name) => r.stash_branch(index, name), - None => r.stash_apply(index, pop, reinstate_index), + project.with_repo_recorded(repo.as_deref(), Some("Git unstash"), |r| { + r.unstash_selected(&stash, pop, reinstate_index, branch.as_deref()) }) }) .await } #[command(trust = trusted)] -pub async fn vcs_stash_drop(host: &Host, window: &str, repo: Option, index: u32) -> IdeResult<()> { +pub async fn vcs_stash_drop(host: &Host, window: &str, repo: Option, stash: Stash) -> IdeResult { host.require_trust(window)?; let project = host.project(window)?; - blocking(move || project.with_repo_at(repo.as_deref(), |r| r.stash_drop(index))).await + blocking(move || project.with_repo_at(repo.as_deref(), |r| r.drop_selected_stash(&stash))).await +} + +#[command(trust = trusted)] +pub async fn vcs_stash_clear(host: &Host, window: &str, repo: Option) -> IdeResult<()> { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || project.with_repo_at(repo.as_deref(), Repo::stash_clear)).await +} + +/// Chooses the destination of a local branch or the current HEAD. +#[command(trust = always)] +pub async fn vcs_default_push_target( + host: &Host, + window: &str, + repo: Option, + branch: Option, +) -> IdeResult> { + let project = host.project(window)?; + blocking(move || project.with_repo_at(repo.as_deref(), |r| r.default_push_target(branch.as_deref()))).await +} + +/// Chooses the source branch and configured destination for a single Git Log commit. +#[command(trust = always)] +pub async fn vcs_commit_push_target( + host: &Host, + window: &str, + repo: Option, + request: RequestId, + revision: String, +) -> IdeResult { + let project = host.project(window)?; + let cancel = host.begin_project_read_request(window, request); + let result = + blocking(move || project.with_repo_at(repo.as_deref(), |r| r.commit_push_target(&revision, &cancel))).await; + host.end_request(request); + result +} + +/// Resolves the push source and the configured destination for each remote. +#[command(trust = always)] +pub async fn vcs_push_target_choices( + host: &Host, + window: &str, + repo: Option, + request: RequestId, + branch: Option, + revision: Option, +) -> IdeResult { + let project = host.project(window)?; + let cancel = host.begin_project_read_request(window, request); + let result = blocking(move || { + project + .with_repo_at(repo.as_deref(), |r| r.push_target_choices(branch.as_deref(), revision.as_deref(), &cancel)) + }) + .await; + host.end_request(request); + result +} + +/// Reads the selected push target without prompting for remote credentials. +#[command(trust = trusted)] +pub async fn vcs_inspect_push( + host: &Host, + window: &str, + repo: Option, + request: RequestId, + selection: PushSelection, + live: bool, +) -> IdeResult { + host.require_trust(window)?; + let project = host.project(window)?; + let cancel = host.begin_project_request(window, request); + let result = + blocking(move || project.with_repo_at(repo.as_deref(), |r| r.inspect_push(&selection, live, &cancel))).await; + host.end_request(request); + result } /// Network operation; progress lines stream through `on_output`. Cancellable. +#[command(trust = always)] +pub async fn vcs_project_update_plan( + host: &Host, + window: &str, + roots: Vec>, +) -> IdeResult> { + let project = host.project(window)?; + blocking(move || { + project.refresh_repositories(); + project.repos().project_update_plan(&roots) + }) + .await +} + #[command(trust = trusted)] pub async fn vcs_remote( host: &Host, @@ -924,58 +1671,113 @@ pub async fn vcs_remote( request: RequestId, op: RemoteOp, on_output: Channel, -) -> IdeResult<()> { + shelf_batch: Option, +) -> IdeResult> { host.require_trust(window)?; let project = host.project(window)?; - let cancel = host.begin_request(request); + let tags_mode = project.settings.effective().vcs.git.fetch_tags_mode; + let cancel = host.begin_project_request(window, request); let result = tokio::task::spawn_blocking(move || { let out = |line: String| { let _ = on_output.send(line); }; - let recorded = matches!(op, RemoteOp::Pull { .. } | RemoteOp::PullFrom { .. } | RemoteOp::ResetToUpstream) - .then_some("Git pull"); - project.with_repo_recorded(repo.as_deref(), recorded, |r| match op { - RemoteOp::Fetch => r.fetch(&cancel, &out), - RemoteOp::Pull { rebase } => r.pull(rebase, &cancel, &out), - RemoteOp::ResetToUpstream => r.reset_to_upstream(&cancel, &out), - RemoteOp::Push { force_with_lease, set_upstream, tags, force, no_verify } => { - r.push_with(PushOptions { force_with_lease, force, set_upstream, tags, no_verify }, &cancel, &out) - } - RemoteOp::DeleteBranch { branch } => r.delete_remote_branch(&branch, &cancel, &out), - RemoteOp::PushBranch { - branch, - revision, - force_with_lease, - target, - remote, - force, - set_upstream, - no_verify, - } => r.push_branch_to( - &branch, - PushBranchOptions { - revision: revision.as_deref(), - target: target.as_deref(), - remote: remote.as_deref(), + let recorded = match op { + RemoteOp::Pull { .. } + | RemoteOp::PullFrom { .. } + | RemoteOp::UpdateProjectBranch { .. } + | RemoteOp::ResetToUpstream => Some("Git pull"), + RemoteOp::UpdateSubmodule { .. } => Some("Git submodule update"), + _ => None, + }; + with_shelf_batch(&project, shelf_batch, || { + project.with_repo_recorded(repo.as_deref(), recorded, |r| match op { + RemoteOp::Fetch { background: true, report, skip_remotes } => { + let fetched = r.fetch_in_background(&skip_remotes, &cancel, &out)?; + if report { + Ok(Some(RemoteOpReport::Fetch(fetched))) + } else { + fetched.remotes.into_iter().find_map(|result| result.error).map_or(Ok(None), Err) + } + } + RemoteOp::Fetch { report: true, .. } => { + r.fetch_report(None, tags_mode, &cancel, &out).map(|report| Some(RemoteOpReport::Fetch(report))) + } + RemoteOp::FetchRemote { remote, report: true } => r + .fetch_report(Some(&remote), tags_mode, &cancel, &out) + .map(|report| Some(RemoteOpReport::Fetch(report))), + RemoteOp::Fetch { .. } => r.fetch_with_tags(None, tags_mode, &cancel, &out).map(|()| None), + RemoteOp::FetchRemote { remote, .. } => { + r.fetch_with_tags(Some(&remote), tags_mode, &cancel, &out).map(|()| None) + } + RemoteOp::FetchPushTarget { selection } => { + r.fetch_push_target(&selection, &cancel, &out).map(|()| None) + } + RemoteOp::Unshallow => r.unshallow_with_tags(tags_mode, &cancel, &out).map(|()| None), + RemoteOp::Pull { rebase, expected_branch } => r + .pull_checked_branch_with_tags(rebase, expected_branch.as_deref(), tags_mode, &cancel, &out) + .map(|()| None), + RemoteOp::UpdateProjectBranch { rebase } => { + r.pull_for_project_update(rebase, tags_mode, &cancel, &out).map(|()| None) + } + RemoteOp::UpdateSubmodule { parent } => project.with_repo_at(Some(&parent), |parent| { + r.update_from_superproject(parent, &cancel, &out).map(|()| None) + }), + RemoteOp::ResetToUpstream => r.reset_to_upstream_with_tags(tags_mode, &cancel, &out).map(|()| None), + RemoteOp::Push { force_with_lease, set_upstream, tags, force, no_verify } => r + .push_with(PushOptions { force_with_lease, force, set_upstream, tags, no_verify }, &cancel, &out) + .map(|report| Some(RemoteOpReport::Push(report))), + RemoteOp::PushSelected { selection, inspected, force_with_lease, set_upstream, tags, no_verify } => { + let options = PushOptions { force_with_lease, set_upstream, tags, no_verify, ..Default::default() }; + r.push_selected(&selection, inspected.as_ref(), options, &cancel, &out) + .map(|report| Some(RemoteOpReport::Push(report))) + } + RemoteOp::ForcePushRejected { divergence, tags, no_verify } => r + .force_push_rejected(&divergence, tags, no_verify, &cancel, &out) + .map(|report| Some(RemoteOpReport::Push(report))), + RemoteOp::DeleteBranch { branch } => r.delete_remote_branch(&branch, &cancel, &out).map(|()| None), + RemoteOp::PushBranch { + branch, + revision, force_with_lease, + target, + remote, force, set_upstream, no_verify, - }, - &cancel, - &out, - ), - RemoteOp::PushTag { tag, remote } => r.push_tag(&tag, &remote, &cancel, &out), - RemoteOp::DeleteRemoteTag { tag, remote } => r.delete_remote_tag(&tag, &remote, &cancel, &out), - RemoteOp::PullFrom { remote, branches, rebase, options } => { - r.pull_from(&remote, &branches, rebase, &options, &cancel, &out) - } + } => r + .push_branch_to( + &branch, + PushBranchOptions { + revision: revision.as_deref(), + target: target.as_deref(), + remote: remote.as_deref(), + force_with_lease, + force, + set_upstream, + no_verify, + }, + &cancel, + &out, + ) + .map(|report| Some(RemoteOpReport::Push(report))), + RemoteOp::PushTag { tag, remote } => { + r.push_tag(&tag, &remote, &cancel, &out).map(|report| Some(RemoteOpReport::Push(report))) + } + RemoteOp::DeleteRemoteTag { tag, remote } => { + r.delete_remote_tag(&tag, &remote, &cancel, &out).map(|()| None) + } + RemoteOp::DeleteTagOnRemotes { deleted } => { + r.delete_tag_on_remotes(&deleted, &cancel, &out).map(|()| None) + } + RemoteOp::PullFrom { remote, branches, rebase, options } => { + r.pull_from(&remote, &branches, rebase, &options, &cancel, &out).map(|()| None) + } + }) }) }) - .await - .map_err(|e| ide_core::IdeError::internal(e.to_string()))?; + .await; host.end_request(request); - result + result.map_err(|e| ide_core::IdeError::internal(e.to_string()))? } /// Branches › Update Selected: fast-forwards local `branches` to their upstreams, one @@ -988,15 +1790,21 @@ pub async fn vcs_update_branches( request: RequestId, branches: Vec, on_output: Channel, + shelf_batch: Option, ) -> IdeResult> { host.require_trust(window)?; let project = host.project(window)?; + let tags_mode = project.settings.effective().vcs.git.fetch_tags_mode; let cancel = host.begin_request(request); let result = tokio::task::spawn_blocking(move || { let out = |line: String| { let _ = on_output.send(line); }; - project.with_repo_recorded(repo.as_deref(), Some("Git pull"), |r| r.update_branches(&branches, &cancel, &out)) + with_shelf_batch(&project, shelf_batch, || { + project.with_repo_recorded(repo.as_deref(), Some("Git pull"), |r| { + r.update_branches_with_tags(&branches, tags_mode, &cancel, &out) + }) + }) }) .await .map_err(|e| ide_core::IdeError::internal(e.to_string()))?; @@ -1012,6 +1820,31 @@ pub async fn vcs_conflict_versions(host: &Host, window: &str, path: PathBuf) -> .await } +#[command(trust = trusted)] +pub async fn vcs_accept_conflict_side( + host: &Host, + window: &str, + paths: Vec, + side: ide_vcs::ConflictSide, +) -> IdeResult<()> { + host.require_trust(window)?; + let project = host.project(window)?; + let label = match side { + ide_vcs::ConflictSide::Ours => "Accept yours", + ide_vcs::ConflictSide::Theirs => "Accept theirs", + }; + blocking(move || per_repo(&project, &paths, Some(label), |repo, paths| repo.accept_conflict_side(paths, side))) + .await +} + +#[command(trust = trusted)] +pub async fn vcs_revert_resolved(host: &Host, window: &str, paths: Vec) -> IdeResult<()> { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || per_repo(&project, &paths, Some("Revert resolved conflicts"), Repo::revert_resolved_conflicts)) + .await +} + #[command(trust = always)] pub async fn vcs_diff_text(host: &Host, window: &str, path: PathBuf, staged: bool) -> IdeResult { let project = host.project(window)?; @@ -1053,9 +1886,11 @@ pub async fn vcs_clone( depth: Option, on_output: Channel, ) -> IdeResult<()> { + let settings = host.global_settings.effective(); + let recurse_submodules = settings.vcs.git.clone_submodules; let cancel = host.begin_request(request); let result = tokio::task::spawn_blocking(move || { - ide_vcs::clone(&url, &dest, depth, &cancel, &|line| { + ide_vcs::clone(&url, &dest, depth, recurse_submodules, &cancel, &|line| { let _ = on_output.send(line); }) }) @@ -1111,6 +1946,124 @@ pub async fn vcs_config_get( blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.config_get(&key))).await } +#[command(trust = always)] +pub async fn vcs_config_get_bool( + host: &Host, + window: &str, + repo: Option, + key: String, +) -> IdeResult> { + let project = LogAccess::new(host, window, repo.as_deref()); + blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.config_get_bool(&key))).await +} + +/// The effective signing settings for one registered Git repository. +#[command(trust = always)] +pub async fn vcs_signing_config(host: &Host, window: &str, repo: PathBuf) -> IdeResult { + let project = host.project(window)?; + blocking(move || project.with_repo_at(Some(&repo), Repo::signing_config)).await +} + +/// Lists OpenPGP key metadata using the signer Git uses for this repository. +#[command(trust = trusted)] +pub async fn vcs_gpg_signing_keys( + host: &Host, + window: &str, + repo: PathBuf, + request: RequestId, +) -> IdeResult> { + host.require_trust(window)?; + let project = host.project(window)?; + let cancel = host.begin_project_request(window, request); + let result = blocking(move || project.with_repo_at(Some(&repo), |repo| repo.gpg_signing_keys(&cancel))).await; + host.end_request(request); + result +} + +/// Updates the selected repository's Git config. +#[command(trust = trusted)] +pub async fn vcs_edit_signing(host: &Host, window: &str, repo: PathBuf, edit: GitSigningEdit) -> IdeResult<()> { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || { + project.with_repo_at(Some(&repo), |repo| repo.edit_signing(edit))?; + project.sink.emit(ide_core::IdeEvent::VcsChanged { root: project.root.clone().into() }); + Ok(()) + }) + .await +} + +/// Streams Git's prepared commit message and template for the selected worktree. +#[command(trust = always)] +pub async fn vcs_watch_commit_messages( + host: &Host, + window: &str, + repo: Option, + request: RequestId, + on_messages: Channel, +) -> IdeResult<()> { + let project = host.project(window)?; + let cancel = host.begin_project_read_request(window, request); + let result = watch_commit_messages(project, repo, cancel, on_messages).await; + host.end_request(request); + result +} + +async fn watch_commit_messages( + project: std::sync::Arc, + repo: Option, + cancel: ide_core::CancellationToken, + on_messages: Channel, +) -> IdeResult<()> { + let (changed, mut events) = tokio::sync::mpsc::channel(1); + let mut watch = { + let project = project.clone(); + let repo = repo.clone(); + let cancel = cancel.clone(); + blocking(move || { + project.with_repo_at(repo.as_deref(), |repo| { + repo.watch_commit_messages(&cancel, move || { + let _ = changed.try_send(()); + }) + }) + }) + .await? + }; + let mut last = None; + loop { + if cancel.is_cancelled() { + return Ok(()); + } + let (returned, message) = { + let project = project.clone(); + let repo = repo.clone(); + let cancel = cancel.clone(); + blocking(move || { + let message = project.with_repo_at(repo.as_deref(), |r| r.commit_messages(&mut watch, &cancel)); + Ok((watch, message)) + }) + .await? + }; + watch = returned; + if let Ok(message) = message + && last.as_ref() != Some(&message) + { + on_messages.send(message.clone())?; + last = Some(message); + } + tokio::select! { + _ = cancel.cancelled() => return Ok(()), + _ = events.recv() => {} + } + // Git and editors can emit several events for a single atomic save. + tokio::select! { + _ = cancel.cancelled() => return Ok(()), + _ = tokio::time::sleep(std::time::Duration::from_millis(150)) => {} + } + let _ = events.try_recv(); + } +} + /// Git User Name Is Not Defined: sets `user.name` / `user.email` for commits in the /// repository, or globally. #[command(trust = trusted)] @@ -1127,6 +2080,46 @@ pub async fn vcs_set_user_identity( blocking(move || project.with_repo_at(repo.as_deref(), |r| r.set_user_identity(&name, &email, global))).await } +#[command(trust = always)] +pub async fn vcs_review_apply_commit( + host: &Host, + window: &str, + repo: Option, + request: RequestId, +) -> IdeResult> { + let project = host.project(window)?; + let cancel = host.begin_project_read_request(window, request); + let result = blocking(move || project.with_repo_at(repo.as_deref(), |r| r.review_apply_commit(&cancel))).await; + host.end_request(request); + result +} + +#[command(trust = trusted)] +pub async fn vcs_format_apply_commit( + host: &Host, + window: &str, + repo: Option, + checkpoint: String, + edits: Vec, + request: RequestId, +) -> IdeResult { + if edits.iter().any(|edit| edit.text.len() as u64 > ide_vfs::READ_ONLY_THRESHOLD) { + return Err(ide_core::IdeError::invalid("File is too large")); + } + let project = host.project(window)?; + let cancel = host.begin_project_read_request(window, request); + let result = blocking(move || { + project.with_repo_at(repo.as_deref(), |r| { + r.format_reviewed_apply(&checkpoint, &edits, &cancel, |path, bytes| { + project.staged_file_encoding(path, bytes) + }) + }) + }) + .await; + host.end_request(request); + result +} + /// Local history operation that may take a while (hooks, large checkouts); git's /// output streams through `on_output`. Cancellable. #[command(trust = trusted)] @@ -1137,34 +2130,83 @@ pub async fn vcs_operation( request: RequestId, op: GitOperation, on_output: Channel, -) -> IdeResult<()> { +) -> IdeResult> { host.require_trust(window)?; let project = host.project(window)?; + let empty_action = host.global_settings.effective().vcs.git.empty_cherry_pick; let cancel = host.begin_request(request); let result = tokio::task::spawn_blocking(move || { let out = |line: String| { let _ = on_output.send(line); }; + let empty_result = |count| { + (count > 0) + .then_some(GitOperationResult::EmptyCherryPicks { empty_cherry_picks: count, action: empty_action }) + }; + let shelf_batch = match &op { + GitOperation::RebaseBranch { shelf_batch, .. } | GitOperation::CheckoutRebase { shelf_batch, .. } => { + shelf_batch.clone() + } + _ => None, + }; let recorded = match &op { GitOperation::CherryPick { .. } => Some("Git cherry-pick"), GitOperation::Revert { .. } => Some("Git revert"), GitOperation::Reset { .. } => Some("Git reset"), - GitOperation::InteractiveRebase { .. } => Some("Git rebase"), + GitOperation::InteractiveRebase { .. } + | GitOperation::CheckoutRebase { .. } + | GitOperation::RebaseBranch { .. } => Some("Git rebase"), + GitOperation::DropCommitChanges { .. } => Some("Git drop selected changes"), _ => None, }; - project.with_repo_recorded(repo.as_deref(), recorded, |r| match op { - GitOperation::Continue => r.continue_operation(&cancel, &out), - GitOperation::StageAndContinue => r.stage_and_continue(&cancel, &out), - GitOperation::Abort => r.abort_operation(&cancel, &out), - GitOperation::Skip => r.skip_operation(&cancel, &out), - GitOperation::CherryPick { commits, record_origin } => { - r.cherry_pick_with(&commits, record_origin, &cancel, &out) - } - GitOperation::Revert { commits } => r.revert(&commits, &cancel, &out), - GitOperation::Reset { commit, mode } => r.reset(&commit, mode, &cancel, &out), - GitOperation::InteractiveRebase { base, entries } => { - r.interactive_rebase(base.as_deref(), &entries, &cancel, &out) - } + with_shelf_batch(&project, shelf_batch, || { + project.with_repo_recorded(repo.as_deref(), recorded, |r| { + let result = match op { + GitOperation::Continue | GitOperation::StageAndContinue => { + let stage = matches!(op, GitOperation::StageAndContinue); + return r.continue_operation_with(stage, empty_action, &cancel, &out).map(empty_result); + } + GitOperation::ContinueReviewedApply { checkpoint, message, options } => { + return r + .continue_reviewed_apply(&checkpoint, &message, &options, empty_action, &cancel, &out) + .map(empty_result); + } + GitOperation::FinishMerge { branch, head, target } => { + r.finish_merge(branch.as_deref(), &head, &target, &cancel, &out) + } + GitOperation::Abort { expected, expected_rebase } => { + check_rebase_state(r, expected_rebase.as_ref())?; + r.abort_expected_operation(expected.as_deref(), &cancel, &out) + } + GitOperation::Skip => return r.skip_operation_with(empty_action, &cancel, &out).map(empty_result), + GitOperation::CherryPick { commits, record_origin, record_origin_for } => { + let options = + CherryPickOptions { record_origin, record_origin_for: &record_origin_for, empty_action }; + return r.cherry_pick_with_options(&commits, options, &cancel, &out).map(empty_result); + } + GitOperation::Revert { commits } => r.revert(&commits, &cancel, &out), + GitOperation::Reset { commit, mode } => r.reset(&commit, mode, &cancel, &out), + GitOperation::InteractiveRebase { base, entries } => { + r.interactive_rebase(base.as_deref(), &entries, &cancel, &out) + } + GitOperation::CheckoutRebase { plan, .. } => { + return r + .checkout_rebase(&plan, &cancel, &out) + .map(|rebased| Some(GitOperationResult::Rebased { rebased })); + } + GitOperation::RebaseBranch { plan, .. } => { + return r + .rebase_branch(&plan, &cancel, &out) + .map(|rebased| Some(GitOperationResult::Rebased { rebased })); + } + GitOperation::DropCommitChanges { commit, expected_head, paths } => { + return r + .drop_commit_changes(&commit, &expected_head, &paths, &cancel, &out) + .map(|rewrite| Some(GitOperationResult::Rewritten(rewrite))); + } + }; + result.map(|()| None) + }) }) }) .await @@ -1203,32 +2245,103 @@ pub async fn vcs_merge_with( repo: Option, branches: Vec, options: MergeOptions, -) -> IdeResult<()> { +) -> IdeResult { host.require_trust(window)?; let project = host.project(window)?; blocking(move || { - project.with_repo_recorded(repo.as_deref(), Some("Git merge"), |r| r.merge_with(&branches, &options)) + project.with_repo_recorded(repo.as_deref(), Some("Git merge"), |r| r.merge_attempt(&branches, &options, false)) }) .await } -/// Rebase dialog: rebases the current branch onto `upstream` (or `--onto`). +/// Rebase dialog: rebases a branch onto an upstream, or replays it from the root. #[command(trust = trusted)] pub async fn vcs_rebase_with( host: &Host, window: &str, repo: Option, - upstream: String, + upstream: Option, options: RebaseOptions, ) -> IdeResult<()> { host.require_trust(window)?; let project = host.project(window)?; blocking(move || { - project.with_repo_recorded(repo.as_deref(), Some("Git rebase"), |r| r.rebase_with(&upstream, &options)) + project + .with_repo_recorded(repo.as_deref(), Some("Git rebase"), |r| r.rebase_with(upstream.as_deref(), &options)) }) .await } +#[allow(clippy::too_many_arguments)] +#[command(trust = trusted)] +pub async fn vcs_rebase_with_editor( + host: &Host, + window: &str, + repo: Option, + operation: RebaseEditorOperation, + request: RequestId, + on_output: Channel, + on_edit: Channel, + expected_rebase: Option, +) -> IdeResult> { + host.require_trust(window)?; + let project = host.project(window)?; + let cancel = host.begin_project_request(window, request); + let editors = host.rebase_editors.clone(); + let window = window.to_owned(); + let result = blocking(move || { + let index = std::cell::Cell::new(0); + let edit = |edit| { + let next = index.get() + 1; + index.set(next); + editors.wait(&window, request, RebaseEditorPrompt { index: next, edit }, &on_edit, &cancel) + }; + let out = |line| { + let _ = on_output.send(line); + }; + project.with_repo_recorded(repo.as_deref(), Some("Git rebase"), |r| { + check_rebase_state(r, expected_rebase.as_ref())?; + r.rebase_editor_operation(operation, &cancel, &out, &edit)?; + if expected_rebase.is_none() || r.operation()?.is_some() { + return Ok(None); + } + let (branch, tip) = r.head()?; + Ok(tip.map(|commit| HistoryTip { branch, commit })) + }) + }) + .await; + host.end_request(request); + result +} + +fn check_rebase_state(repo: &Repo, expected: Option<&RebaseState>) -> IdeResult<()> { + if let Some(expected) = expected + && repo.branch_info()?.rebase.as_ref() != Some(expected) + { + return Err(ide_core::IdeError::invalid("The rebase changed before it could be resumed or aborted")); + } + Ok(()) +} + +#[command(trust = trusted)] +pub fn vcs_rebase_editor_reply( + host: &Host, + window: &str, + request: RequestId, + index: u32, + reply: Option, +) -> IdeResult<()> { + host.require_trust(window)?; + host.rebase_editors.reply(window, request, index, reply) +} + +/// Whether a revision resolves to an existing Git commit. +#[command(trust = always)] +pub async fn vcs_has_commit(host: &Host, window: &str, repo: Option, revision: String) -> IdeResult { + let project = host.project(window)?; + blocking(move || project.with_repo_at(repo.as_deref(), |r| Ok(r.has_commit(&revision)))).await +} + #[command(trust = always)] pub async fn vcs_remotes(host: &Host, window: &str, repo: Option) -> IdeResult> { let project = LogAccess::new(host, window, repo.as_deref()); @@ -1249,7 +2362,13 @@ pub async fn vcs_remotes(host: &Host, window: &str, repo: Option) -> Id pub async fn vcs_edit_remote(host: &Host, window: &str, repo: Option, edit: RemoteEdit) -> IdeResult<()> { host.require_trust(window)?; let project = host.project(window)?; - blocking(move || project.with_repo_at(repo.as_deref(), |r| r.edit_remote(&edit))).await + blocking(move || { + project.with_repo_at(repo.as_deref(), |r| r.edit_remote(&edit))?; + // A linked worktree may share config from outside the project's watched tree. + project.sink.emit(ide_core::IdeEvent::VcsChanged { root: project.root.clone().into() }); + Ok(()) + }) + .await } #[command(trust = always)] @@ -1258,6 +2377,65 @@ pub async fn vcs_worktrees(host: &Host, window: &str, repo: Option) -> blocking(move || project.with_repo_at(repo.as_deref(), |r| r.worktrees())).await } +#[derive(Clone, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct WorktreeInclude { + pub path: ide_core::IpcPath, + pub exists: bool, +} + +#[command(trust = always)] +pub async fn vcs_worktree_include(host: &Host, window: &str, repo: Option) -> IdeResult { + let project = host.project(window)?; + blocking(move || { + project.with_repo_at(repo.as_deref(), |r| { + let (path, exists) = r.worktree_include()?; + Ok(WorktreeInclude { path: path.into(), exists }) + }) + }) + .await +} + +#[command(trust = trusted)] +pub async fn vcs_set_worktree_locked( + host: &Host, + window: &str, + repo: Option, + path: PathBuf, + locked: bool, +) -> IdeResult<()> { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || project.with_repo_recorded(repo.as_deref(), None, |r| r.set_worktree_locked(&path, locked))).await +} + +#[command(trust = trusted)] +pub async fn vcs_prune_worktrees(host: &Host, window: &str, repo: Option) -> IdeResult<()> { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || { + let result = project.with_repo_recorded(repo.as_deref(), None, |r| r.prune_worktrees()); + project.refresh_repositories(); + result + }) + .await +} + +#[derive(Debug, Clone, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct WorktreeSetup { + pub script: PathBuf, + pub request: RequestId, +} + +#[derive(Debug, Clone, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct WorktreeCreation { + pub copy_warning: Option, + pub setup_warning: Option, +} + +#[allow(clippy::too_many_arguments)] #[command(trust = trusted)] pub async fn vcs_add_worktree( host: &Host, @@ -1266,19 +2444,43 @@ pub async fn vcs_add_worktree( path: PathBuf, commitish: String, new_branch: Option, -) -> IdeResult<()> { + copy_config: Option, + setup: Option, +) -> IdeResult { host.require_trust(window)?; let project = host.project(window)?; - blocking(move || { - let result = project - .with_repo_recorded(repo.as_deref(), None, |r| r.add_worktree(&path, &commitish, new_branch.as_deref())); + let request = setup.as_ref().map(|setup| setup.request); + let cancel = request.map(|id| host.begin_project_request(window, id)); + let outcome = blocking(move || { + if let Some(setup) = &setup + && (!setup.script.is_absolute() || !setup.script.is_file()) + { + return Err(ide_core::IdeError::invalid("Choose an absolute path to an existing setup script")); + } + let result = project.with_repo_recorded(repo.as_deref(), None, |r| { + r.add_worktree(&path, &commitish, new_branch.as_deref())?; + // Setup warnings report partial success without offering to repeat checkout. + let copy_warning = if copy_config == Some(true) { + r.copy_worktree_config(&path).err().map(|error| error.to_string()) + } else { + None + }; + let setup_warning = setup + .zip(cancel) + .and_then(|(setup, cancel)| super::worktree_setup::run(&setup.script, &r.root().join(path), &cancel)); + Ok(WorktreeCreation { copy_warning, setup_warning }) + }); // A worktree below the project is a new repository: rescan so its files // join the status and gutter queries (the watcher picks the gitfile up // too, but only as a debounced event later). project.refresh_repositories(); result }) - .await + .await; + if let Some(request) = request { + host.end_request(request); + } + outcome } #[command(trust = trusted)] @@ -1419,16 +2621,40 @@ pub async fn vcs_create_patch( window: &str, repo: Option, source: PatchSource, + base: Option, ) -> IdeResult { let project = host.project(window)?; blocking(move || { - project.with_repo_at(repo.as_deref(), |r| match source { + let base = base.map(|base| patch_export_base(&project, base)).transpose()?; + let base = base.as_deref(); + match source { PatchSource::Changes { paths, reverse } => { let paths: Vec = paths.into_iter().map(Into::into).collect(); - r.create_patch(&paths, reverse) + if repo.is_some() || base.is_none() { + return project.with_repo_at(repo.as_deref(), |r| { + export_patch(r.create_patch(&paths, reverse)?, r.root(), base) + }); + } + let groups = project.repos().group(&paths); + if groups.is_empty() || groups.iter().map(|(_, paths)| paths.len()).sum::() != paths.len() { + return Err(ide_core::IdeError::invalid("The selected files must belong to Git repositories")); + } + let mut patch = String::new(); + for (repo, paths) in groups { + patch.push_str(&project.with_repo_at(Some(repo.root()), |r| { + export_patch(r.create_patch(&paths, reverse)?, r.root(), base) + })?); + } + Ok(patch) } - PatchSource::Commits { commits, reverse } => r.create_commits_patch(&commits, reverse), - }) + PatchSource::Staging { entries, reverse } => create_staging_patch(&project, entries, reverse, base), + PatchSource::Commits { commits, reverse } => project.with_repo_at(repo.as_deref(), |r| { + export_patch(r.create_commits_patch(&commits, reverse)?, r.root(), base) + }), + PatchSource::Revisions { before, after, paths } => project.with_repo_at(repo.as_deref(), |r| { + export_patch(r.create_revisions_patch(&before, &after, &paths)?, r.root(), base) + }), + } }) .await } @@ -1453,15 +2679,152 @@ pub async fn vcs_pending_patch( .await } +#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum PatchTarget { + Project, + Repository, +} + +#[derive(Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PatchPreview { + pub files: Vec, + pub base: Option, + pub placements: Option>, + pub directory_matches: Vec, + pub automatic_mappings: Vec, +} + +fn mapped_patch( + project: &Project, + repo: Option<&Path>, + base: Option<&Path>, + patch: &str, + paths: Option<&[String]>, + mappings: &[PatchPathMapping], +) -> IdeResult { + if base.is_some_and(|base| !base.is_absolute() || !project.root.starts_with(base)) { + return Err(ide_core::IdeError::invalid("The patch base is outside the project")); + } + MappedPatch::new(&project.repos(), repo, base, patch, paths, mappings) +} + #[command(trust = trusted)] pub async fn vcs_patch_preview( host: &Host, window: &str, repo: Option, patch: String, -) -> IdeResult> { + target: Option, + mappings: Option>, +) -> IdeResult { let project = host.project(window)?; - blocking(move || project.with_repo_at(repo.as_deref(), |r| r.patch_preview(&patch))).await + blocking(move || { + let repos = project.repos(); + let plan = if target != Some(PatchTarget::Repository) && (repos.all().len() > 1 || target.is_some()) { + ProjectPatch::discover(&repos, &project.root, &patch, target.is_none())? + } else { + None + }; + let base = plan + .as_ref() + .map(|plan| plan.base.as_path()) + .or_else(|| (target == Some(PatchTarget::Project)).then_some(project.root.as_path())); + let default = match repo.as_deref() { + Some(root) => repos.at_root(root), + None => repos.primary(), + } + .ok_or_else(|| ide_core::IdeError::unavailable("The patch repository is not in the project"))?; + let overrides = mappings.as_deref().unwrap_or(&[]); + let (directory_matches, automatic_mappings) = discover_patch_directories( + &repos, + PatchDirectoryScope { + repo: default, + base, + only_repository: target == Some(PatchTarget::Repository), + automatic: target.is_none() && !project.index.status().indexing, + }, + &patch, + overrides, + |names| project.index.files_with_names(names), + |names| project.index.directories_with_names(names), + )?; + if mappings.is_some() || !automatic_mappings.is_empty() || (plan.is_none() && base.is_some()) { + let effective: Vec<_> = overrides.iter().chain(&automatic_mappings).cloned().collect(); + let mut mapped = mapped_patch(&project, repo.as_deref(), base, &patch, None, &effective)?; + for group in &mapped.groups { + project.with_repo_at(Some(&group.group.root), |r| group.preview(r, &mut mapped.files))?; + } + return Ok(PatchPreview { + files: mapped.files, + base: base.map(Into::into), + placements: Some(mapped.placements), + directory_matches, + automatic_mappings, + }); + } + if let Some(plan) = plan { + let mut files = Vec::new(); + for group in plan.groups { + files.extend(project.with_repo_at(Some(&group.root), |r| group.preview(r))?); + } + return Ok(PatchPreview { + files, + base: Some(plan.base.into()), + placements: None, + directory_matches, + automatic_mappings, + }); + } + let files = project.with_repo_at(repo.as_deref(), |r| r.patch_preview(&patch))?; + Ok(PatchPreview { files, base: None, placements: None, directory_matches, automatic_mappings }) + }) + .await +} + +#[command(trust = trusted)] +pub async fn vcs_patch_file_diff( + host: &Host, + window: &str, + repo: Option, + base: Option, + patch: String, + path: String, + mappings: Option>, +) -> IdeResult { + let project = host.project(window)?; + blocking(move || { + let encoding = |path: &Path, bytes: &[u8]| project.staged_file_encoding(path, bytes); + if let Some(mappings) = mappings { + let plan = mapped_patch( + &project, + repo.as_deref(), + base.as_deref(), + &patch, + Some(std::slice::from_ref(&path)), + &mappings, + )?; + plan.require_destinations()?; + let group = + plan.groups.first().ok_or_else(|| ide_core::IdeError::invalid("The patch file has no repository"))?; + return project.with_repo_at(Some(&group.group.root), |r| group.file_diff(r, &encoding)); + } + if let Some(base) = base { + let plan = ProjectPatch::at_base( + &project.repos(), + &project.root, + &base, + &patch, + Some(std::slice::from_ref(&path)), + )?; + let group = + plan.groups.first().ok_or_else(|| ide_core::IdeError::invalid("The patch file has no repository"))?; + return project.with_repo_at(Some(&group.root), |r| group.file_diff(r, &path, &encoding)); + } + project.with_repo_at(repo.as_deref(), |r| r.patch_file_diff(&patch, &path, &encoding)) + }) + .await } #[command(trust = trusted)] @@ -1470,10 +2833,96 @@ pub async fn vcs_apply_patch( window: &str, repo: Option, patch: String, + paths: Option>, ) -> IdeResult { host.require_trust(window)?; let project = host.project(window)?; - blocking(move || project.with_repo_recorded(repo.as_deref(), None, |r| r.apply_patch(&patch))).await + blocking(move || { + project.with_repo_recorded(repo.as_deref(), None, |r| match paths { + Some(paths) => r.apply_selected_patch(&patch, &paths), + None => r.apply_patch(&patch), + }) + }) + .await +} + +#[derive(Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ProjectPatchFailure { + pub root: IpcPath, + pub error: ide_core::IdeError, +} + +#[derive(Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ProjectPatchOutcome { + pub outcome: ApplyOutcome, + pub conflicted_repositories: Vec, + pub failures: Vec, +} + +fn apply_patch_groups( + project: &Project, + groups: Vec, + root: impl Fn(&T) -> &Path, + apply: impl Fn(&T, &Repo) -> IdeResult, +) -> IdeResult { + project.with_disk_sync(|| { + let mut outcome = ApplyOutcome::default(); + let mut conflicted_repositories = Vec::new(); + let mut failures = Vec::new(); + for group in groups { + let root = root(&group); + match project.with_repo_at(Some(root), |repo| apply(&group, repo)) { + Ok(result) => { + if !result.conflicts.is_empty() { + conflicted_repositories.push(root.into()); + } + outcome.applied.extend(result.applied); + outcome.conflicts.extend(result.conflicts); + } + Err(error) => failures.push(ProjectPatchFailure { root: root.into(), error }), + } + } + Ok(ProjectPatchOutcome { outcome, conflicted_repositories, failures }) + }) +} + +#[command(trust = trusted)] +pub async fn vcs_apply_project_patch( + host: &Host, + window: &str, + base: PathBuf, + patch: String, + paths: Option>, +) -> IdeResult { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || { + let plan = ProjectPatch::at_base(&project.repos(), &project.root, &base, &patch, paths.as_deref())?; + apply_patch_groups(&project, plan.groups, |group| &group.root, |group, repo| group.apply(repo)) + }) + .await +} + +#[command(trust = trusted)] +pub async fn vcs_apply_mapped_patch( + host: &Host, + window: &str, + repo: Option, + base: Option, + patch: String, + paths: Option>, + mappings: Vec, +) -> IdeResult { + host.require_trust(window)?; + let project = host.project(window)?; + blocking(move || { + let plan = mapped_patch(&project, repo.as_deref(), base.as_deref(), &patch, paths.as_deref(), &mappings)?; + plan.require_destinations()?; + apply_patch_groups(&project, plan.groups, |group| &group.group.root, |group, repo| group.apply(repo)) + }) + .await } /// Shelve Changes: saves the changes of `paths` as a patch on the shelf and reverts them. @@ -1482,9 +2931,32 @@ pub async fn vcs_shelve(host: &Host, window: &str, name: String, paths: Vec() != paths.len() { + return Err(ide_core::IdeError::invalid("select files in a git repository to shelve")); + } + let shelf = shelf_dir(&project.root); + if let [(repo, selected)] = groups.as_slice() { + keep_private(&project.root); + return project + .with_repo_recorded(Some(repo.root()), Some("Shelve"), |r| r.shelve(&shelf, &name, selected)); + } + let base = project + .root + .ancestors() + .find(|base| groups.iter().all(|(repo, _)| repo.root().starts_with(base))) + .ok_or_else(|| ide_core::IdeError::invalid("The shelf repositories have no common directory"))?; + let captures = groups + .iter() + .map(|(repo, selected)| { + project.with_repo_at(Some(repo.root()), |r| ide_vcs::shelf::ShelfCapture::capture(r, base, selected)) + }) + .collect::>>()?; + let entry = ide_vcs::shelf::save_combined(&shelf, base, &name, &captures)?; + for capture in &captures { + project.with_repo_recorded(Some(capture.repository()), Some("Shelve"), |r| capture.revert(r))?; + } + Ok(entry) }) .await } @@ -1518,10 +2990,22 @@ pub async fn vcs_unshelve( host.require_trust(window)?; let project = host.project(window)?; blocking(move || { - let repo = ide_vcs::shelf::repository(&shelf_dir(&project.root), &id)?; - project.with_repo_recorded(repo.as_deref(), Some("Unshelve"), |r| { - ide_vcs::shelf::unshelve_path(r, &shelf_dir(&project.root), &id, remove, path.as_deref()) - }) + let shelf = shelf_dir(&project.root); + let selections = ide_vcs::shelf::selections(&shelf, &id, path.as_deref())?; + for selection in &selections { + project.with_repo_at(selection.repo.as_deref(), |_| Ok(()))?; + } + let mut result = ApplyOutcome { applied: Vec::new(), conflicts: Vec::new() }; + for selection in &selections { + let outcome = + project.with_repo_recorded(selection.repo.as_deref(), Some("Unshelve"), |r| selection.apply(r))?; + if remove && outcome.conflicts.is_empty() { + ide_vcs::shelf::delete_paths(&shelf, &id, &outcome.applied)?; + } + result.applied.extend(outcome.applied); + result.conflicts.extend(outcome.conflicts); + } + Ok(result) }) .await } @@ -1539,17 +3023,39 @@ pub async fn vcs_shelf_rename(host: &Host, window: &str, id: String, name: Strin } #[command(trust = always)] -pub async fn vcs_shelf_patch(host: &Host, window: &str, id: String, path: Option) -> IdeResult { +pub async fn vcs_shelf_patch( + host: &Host, + window: &str, + id: String, + path: Option, + base: Option, +) -> IdeResult { let project = host.project(window)?; - blocking(move || ide_vcs::shelf::selected_patch(&shelf_dir(&project.root), &id, path.as_deref())).await + blocking(move || { + let shelf = shelf_dir(&project.root); + let Some(base) = base else { return ide_vcs::shelf::selected_patch(&shelf, &id, path.as_deref()) }; + let base = patch_export_base(&project, base)?; + let repos = project.repos(); + let fallback = repos.primary().map_or(project.root.as_path(), |repo| repo.root()); + let mut patch = String::new(); + for selection in ide_vcs::shelf::selections(&shelf, &id, path.as_deref())? { + patch.push_str(&selection.export(fallback, &base)?); + } + Ok(patch) + }) + .await } #[command(trust = trusted)] pub async fn vcs_shelf_diff(host: &Host, window: &str, id: String) -> IdeResult> { let project = host.project(window)?; blocking(move || { - let repo = ide_vcs::shelf::repository(&shelf_dir(&project.root), &id)?; - project.with_repo_at(repo.as_deref(), |r| ide_vcs::shelf::diff_files(r, &shelf_dir(&project.root), &id)) + let shelf = shelf_dir(&project.root); + let mut files = Vec::new(); + for selection in ide_vcs::shelf::selections(&shelf, &id, None)? { + files.extend(project.with_repo_at(selection.repo.as_deref(), |r| selection.diff_files(r))?); + } + Ok(files) }) .await } @@ -1592,14 +3098,28 @@ pub fn vcs_changelists_save(host: &Host, window: &str, changelists: ChangelistSt /// Create Patch › Save to file. #[command(trust = always)] -pub async fn vcs_write_patch(host: &Host, window: &str, path: PathBuf, patch: String) -> IdeResult<()> { +pub async fn vcs_write_patch( + host: &Host, + window: &str, + path: PathBuf, + patch: String, + encoding: Option, +) -> IdeResult<()> { let project = host.project(window).ok(); blocking(move || { let write = || { + let bytes = match encoding.as_deref() { + Some(encoding) => ide_vfs::encode( + &patch, + encoding, + matches!(encoding.trim().to_ascii_lowercase().as_str(), "utf-16" | "utf-16le" | "utf-16be"), + )?, + None => patch.into_bytes(), + }; if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; } - std::fs::write(&path, patch)?; + ide_vfs::write_atomic_strict(&path, &bytes)?; Ok(()) }; match project { @@ -1610,31 +3130,68 @@ pub async fn vcs_write_patch(host: &Host, window: &str, path: PathBuf, patch: St .await } +/// Reads a patch without normalizing its hunk line endings. +#[command(trust = always)] +pub async fn vcs_read_patch(host: &Host, window: &str, path: PathBuf) -> IdeResult { + let project = host.project(window).ok(); + blocking(move || { + if let Some(project) = project { + if let Some(doc) = project.documents.by_path(&path) + && project.documents.is_dirty(doc)? + { + return Ok(project.documents.text_snapshot(doc)?.text); + } + return Ok(project.documents.load_file(&path)?.text); + } + Ok(ide_vfs::load_text(&path)?.text) + }) + .await +} + ide_command::domain!( vcs_commands: vcs_add_to_ignore, vcs_add_worktree, vcs_apply_patch, + vcs_apply_project_patch, + vcs_apply_mapped_patch, vcs_blame, vcs_block_history, vcs_branch_info, + vcs_check_incoming, vcs_branches, vcs_changelists_load, vcs_changelists_save, vcs_checkout, + vcs_checkout_affected_files, vcs_clone, vcs_commit, + vcs_keep_amend_commit, + vcs_commit_crlf_paths, vcs_commit_files, + vcs_commit_large_files, + vcs_preview_partial_commit, vcs_commits_changes, + vcs_commit_selection_changes, vcs_compare_paths, vcs_compare_scope, vcs_config_get, + vcs_config_get_bool, + vcs_signing_config, + vcs_gpg_signing_keys, + vcs_edit_signing, + vcs_watch_commit_messages, vcs_set_user_identity, vcs_conflict_versions, + vcs_accept_conflict_side, + vcs_revert_resolved, vcs_create_branch, + vcs_undo_branch_creation, vcs_create_patch, vcs_create_tag, vcs_delete_branch, + vcs_delete_tracking_branch, + vcs_delete_merged_branch, vcs_delete_tag, vcs_detected_git, vcs_diff_hunks, @@ -1642,31 +3199,48 @@ ide_command::domain!( vcs_diff_revisions, vcs_diff_text, vcs_diff_with_worktree, + vcs_finish_shelf_batch, vcs_discard, vcs_edit_remote, vcs_file_at, vcs_file_mode, + vcs_diff_entries, vcs_git_version, vcs_has_hook, vcs_ignore_blame_revision, vcs_init, vcs_line_hunks, + vcs_staging_line_hunks, vcs_log, vcs_log_details, vcs_log_details_batch, + vcs_invalidate_log_signatures, vcs_log_refs, vcs_log_users, vcs_merge, + vcs_merge_affected_files, vcs_merge_base, vcs_merge_with, vcs_move_worktree, + vcs_not_cherry_picked, vcs_open_external_log, + vcs_review_apply_commit, + vcs_format_apply_commit, vcs_operation, vcs_patch_preview, + vcs_patch_file_diff, vcs_pending_patch, vcs_rebase, vcs_rebase_with, + vcs_rebase_with_editor, + vcs_rebase_editor_reply, + vcs_has_commit, vcs_remote, + vcs_default_push_target, + vcs_commit_push_target, + vcs_project_update_plan, + vcs_push_target_choices, + vcs_inspect_push, vcs_update_branches, vcs_remotes, vcs_remove_worktree, @@ -1677,6 +3251,7 @@ ide_command::domain!( vcs_revision_children, vcs_revision_files, vcs_reword, + vcs_extract_commit_changes, vcs_roots, vcs_detected_roots, vcs_shelf_delete, @@ -1687,16 +3262,27 @@ ide_command::domain!( vcs_shelve, vcs_shelves, vcs_stage, + vcs_stage_without_content, + vcs_stage_formatted_text, + vcs_staged_text, + vcs_save_staged_text, vcs_stage_hunks, vcs_stage_patch, vcs_stash_apply, vcs_stash_drop, + vcs_stash_clear, vcs_stash_push, vcs_stashes, vcs_tags, vcs_undo_commit, vcs_unshelve, vcs_unstage, + vcs_restore_unstaged, + vcs_rollback_submodules, + vcs_worktree_include, vcs_worktrees, + vcs_set_worktree_locked, + vcs_prune_worktrees, vcs_write_patch, + vcs_read_patch, ); diff --git a/crates/ide-host/src/ops/vcs/rebase_editor.rs b/crates/ide-host/src/ops/vcs/rebase_editor.rs new file mode 100644 index 000000000..4dfe9df1b --- /dev/null +++ b/crates/ide-host/src/ops/vcs/rebase_editor.rs @@ -0,0 +1,62 @@ +use crate::ops::Channel; +use ide_core::{CancellationToken, IdeError, IdeResult, RequestId}; +use ide_vcs::{RebaseEdit, RebaseEditorReply}; +use parking_lot::Mutex; +use serde::Serialize; +use specta::Type; +use std::collections::HashMap; +use std::sync::mpsc; +use std::time::Duration; + +#[derive(Serialize, Type)] +pub struct RebaseEditorPrompt { + pub index: u32, + pub edit: RebaseEdit, +} + +type EditorKey = (String, RequestId, u32); + +#[derive(Default)] +pub(crate) struct RebaseEditors { + pending: Mutex>>>, +} + +impl RebaseEditors { + pub fn wait( + &self, + window: &str, + request: RequestId, + prompt: RebaseEditorPrompt, + channel: &Channel, + cancel: &CancellationToken, + ) -> Option { + let key = (window.to_owned(), request, prompt.index); + let (send, recv) = mpsc::channel(); + self.pending.lock().insert(key.clone(), send); + let result = (|| { + channel.send(prompt).ok()?; + while !cancel.is_cancelled() { + match recv.recv_timeout(Duration::from_millis(100)) { + Ok(reply) => return reply, + Err(mpsc::RecvTimeoutError::Timeout) => continue, + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + } + None + })(); + self.pending.lock().remove(&key); + result + } + + pub fn reply( + &self, + window: &str, + request: RequestId, + index: u32, + reply: Option, + ) -> IdeResult<()> { + let expired = || IdeError::invalid("The Git editor request is no longer active."); + let send = self.pending.lock().remove(&(window.to_owned(), request, index)).ok_or_else(expired)?; + send.send(reply).map_err(|_| expired()) + } +} diff --git a/crates/ide-host/src/ops/vcs/worktree_setup.rs b/crates/ide-host/src/ops/vcs/worktree_setup.rs new file mode 100644 index 000000000..c673d8ef8 --- /dev/null +++ b/crates/ide-host/src/ops/vcs/worktree_setup.rs @@ -0,0 +1,33 @@ +use ide_core::CancellationToken; +use std::collections::VecDeque; +use std::path::Path; +use std::process::Command; +use std::time::Duration; + +pub(super) fn run(script: &Path, worktree: &Path, cancel: &CancellationToken) -> Option { + let mut tail = VecDeque::new(); + let on_line = |line: String| { + if tail.len() == 12 { + tail.pop_front(); + } + tail.push_back(line.chars().take(500).collect::()); + }; + let mut command = script_command(script); + command.arg(worktree); + let result = crate::environment::run_command(command, worktree, cancel, Some(Duration::from_secs(300)), on_line); + if cancel.is_cancelled() { + return None; + } + result.err().map(|error| std::iter::once(error).chain(tail).collect::>().join("\n")) +} + +fn script_command(script: &Path) -> Command { + #[cfg(windows)] + if script.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("ps1")) { + let windows = std::env::var_os("SystemRoot").unwrap_or_else(|| r"C:\Windows".into()); + let mut command = Command::new(Path::new(&windows).join(r"System32\WindowsPowerShell\v1.0\powershell.exe")); + command.args(["-NoProfile", "-NonInteractive", "-File"]).arg(script); + return command; + } + Command::new(script) +} diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index aff7ff725..944d09832 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -1180,6 +1180,11 @@ impl Project { let settings = self.settings.effective(); repo.set_ignored_names(settings.ignored_names()); repo.set_cli_status(settings.vcs.git.cli_status); + repo.set_automatic_shelf( + (settings.vcs.git.save_changes_policy == ide_core::workflow_settings::GitSaveChangesPolicy::Shelve) + .then(|| ide_core::project_dir::path(&self.root, "shelf")), + (!settings.vcs.git.staging_area).then(|| self.root.clone()), + ); f(repo) } @@ -1450,12 +1455,22 @@ impl Project { /// Use the open document's selected encoding, or the same detection/settings as opening it. pub fn vcs_encoding(&self, path: &Path, rev: Option<&str>) -> IdeResult { let charset = self.file_encoding(path, rev)?; + Ok(self.vcs_text_encoding(path, charset)) + } + + pub fn staged_file_encoding(&self, path: &Path, bytes: &[u8]) -> ide_vcs::TextEncoding { + let defaults = self.documents.file_defaults(); + let charset = ide_vfs::detect_encoding(bytes, defaults.fallback_for(path)); + self.vcs_text_encoding(path, charset) + } + + fn vcs_text_encoding(&self, path: &Path, charset: &'static encoding_rs::Encoding) -> ide_vcs::TextEncoding { let encoding = ide_vcs::TextEncoding::from(charset); - Ok(if self.documents.native_to_ascii_for(path) { + if self.documents.native_to_ascii_for(path) { encoding.with_ascii_conversion(ide_vfs::decode_properties_escapes, ide_vfs::encode_properties_ascii) } else { encoding - }) + } } fn file_encoding(&self, path: &Path, rev: Option<&str>) -> IdeResult<&'static encoding_rs::Encoding> { diff --git a/crates/ide-host/tests/external_log.rs b/crates/ide-host/tests/external_log.rs index 7800b1c16..023d96d61 100644 --- a/crates/ide-host/tests/external_log.rs +++ b/crates/ide-host/tests/external_log.rs @@ -113,8 +113,8 @@ async fn external_history_is_readable_and_never_becomes_a_write_target() { Some("historical content\n") ); assert!(project.repos().at_root(&external).is_none()); - assert!(vcs::vcs_checkout(&host, "main", Some(external.clone()), first.clone(), false, None).await.is_err()); - assert!(vcs::vcs_apply_patch(&host, "main", Some(external.clone()), String::new()).await.is_err()); + assert!(vcs::vcs_checkout(&host, "main", Some(external.clone()), first.clone(), false, None, None).await.is_err()); + assert!(vcs::vcs_apply_patch(&host, "main", Some(external.clone()), String::new(), None).await.is_err()); assert_eq!(git(&external, &["rev-parse", "HEAD"]), head); assert!(!deleted.exists()); host.close_project("main"); diff --git a/crates/ide-host/tests/properties.rs b/crates/ide-host/tests/properties.rs index 296b0825d..4f9c6da28 100644 --- a/crates/ide-host/tests/properties.rs +++ b/crates/ide-host/tests/properties.rs @@ -140,7 +140,9 @@ async fn properties_search_git_and_document_coordinates_agree() { let selected = &hunks[0]; let options = ide_vcs::CommitOptions { partial: vec![ide_vcs::PartialCommitFile { + prepared: None, path: path.clone().into(), + line_hunks: vec![], hunks: vec![ide_vcs::HunkRange { start: selected.start, lines: selected.lines, diff --git a/crates/ide-host/tests/trust_vcs_sweep.rs b/crates/ide-host/tests/trust_vcs_sweep.rs index 72612b67e..36f1bcf34 100644 --- a/crates/ide-host/tests/trust_vcs_sweep.rs +++ b/crates/ide-host/tests/trust_vcs_sweep.rs @@ -11,7 +11,7 @@ use std::process::{Command, Stdio}; use std::sync::Arc; /// Allowed in Restricted Mode and not swept: none of them starts git for the project. -const NOT_THE_PROJECT_REPOSITORY: [&str; 7] = [ +const NOT_THE_PROJECT_REPOSITORY: [&str; 8] = [ "vcs_clone", // clones a URL the user gives into a new folder "vcs_diff_hunks", // compares two texts "vcs_detected_git", // looks for the git executable @@ -19,6 +19,7 @@ const NOT_THE_PROJECT_REPOSITORY: [&str; 7] = [ "vcs_shelf_patch", "vcs_changelists_load", "vcs_write_patch", // writes a patch the UI already holds + "vcs_read_patch", // reads patch text without running Git ]; fn git(root: &Path, args: &[&str]) -> String { @@ -165,25 +166,30 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() { ($command, $what, Box::pin(async { $call.await.is_ok() }) as Pin + '_>>) }; } - macro_rules! sync { - ($command:literal, $what:literal, $call:expr) => { - ($command, $what, Box::pin(async { $call.is_ok() }) as Pin + '_>>) - }; - } let calls: Vec = vec![ call!("vcs_status", "", ops::vcs::vcs_status(host, w)), + call!("vcs_ignored_files", "", ops::vcs::vcs_ignored_files(host, w)), call!("vcs_status_paths", "", ops::vcs::vcs_status_paths(host, w, vec![file.clone()])), - sync!("vcs_roots", "", vcs::vcs_roots(host, w)), + call!("vcs_roots", "", vcs::vcs_roots(host, w)), + call!("vcs_project_update_plan", "", vcs::vcs_project_update_plan(host, w, vec![root()])), call!("vcs_detected_roots", "", vcs::vcs_detected_roots(host, w)), call!("vcs_branch_info", "", vcs::vcs_branch_info(host, w, root())), call!("vcs_line_hunks", "", vcs::vcs_line_hunks(host, w, file.clone())), + call!("vcs_staging_line_hunks", "", vcs::vcs_staging_line_hunks(host, w, file.clone(), None)), call!("vcs_file_at", "", vcs::vcs_file_at(host, w, file.clone(), None)), + call!( + "vcs_diff_entries", + "", + vcs::vcs_diff_entries(host, w, vec![vcs::DiffEntryRequest { path: file.clone().into(), rev: "WT".into() }]) + ), call!("vcs_blame", "", vcs::vcs_blame(host, w, file.clone(), None, None)), call!("vcs_block_history", "", vcs::vcs_block_history(host, w, RequestId(1), file.clone(), None, (0, 1))), call!("vcs_log", "", vcs::vcs_log(host, w, root(), Default::default())), call!("vcs_log_refs", "", vcs::vcs_log_refs(host, w, root())), call!("vcs_log_users", "", vcs::vcs_log_users(host, w, root())), call!("vcs_log_details", "", vcs::vcs_log_details(host, w, root(), project.head.clone())), + call!("vcs_invalidate_log_signatures", "", vcs::vcs_invalidate_log_signatures(host, w, project.root.clone())), + call!("vcs_signing_config", "", vcs::vcs_signing_config(host, w, project.root.clone())), call!( "vcs_log_details_batch", "", @@ -214,9 +220,26 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() { call!("vcs_conflict_versions", "", vcs::vcs_conflict_versions(host, w, file.clone())), call!("vcs_diff_text", "", vcs::vcs_diff_text(host, w, file.clone(), false)), call!("vcs_config_get", "", vcs::vcs_config_get(host, w, root(), "user.name".into())), + call!("vcs_config_get_bool", "", vcs::vcs_config_get_bool(host, w, root(), "log.showSignature".into())), + call!("vcs_watch_commit_messages", "", async { + let request = RequestId(30); + let (send, mut messages) = tokio::sync::mpsc::channel(1); + let channel = ops::Channel::new(move |message| { + let _ = send.try_send(message); + }); + let watch = vcs::vcs_watch_commit_messages(host, w, root(), request, channel); + let stop = async { + let initial = tokio::time::timeout(std::time::Duration::from_secs(10), messages.recv()).await; + host.cancel_request(request); + assert!(matches!(initial, Ok(Some(_))), "missing initial commit messages"); + }; + let (result, ()) = tokio::join!(watch, stop); + result + }), call!("vcs_tags", "", vcs::vcs_tags(host, w, root())), call!("vcs_remotes", "", vcs::vcs_remotes(host, w, root())), call!("vcs_worktrees", "", vcs::vcs_worktrees(host, w, root())), + call!("vcs_worktree_include", "", vcs::vcs_worktree_include(host, w, root())), call!("vcs_diff_with_worktree", "", vcs::vcs_diff_with_worktree(host, w, root(), "HEAD".into())), call!("vcs_compare_scope", "", vcs::vcs_compare_scope(host, w, vec![project.root.clone()])), call!( @@ -235,6 +258,28 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() { vcs::vcs_diff_numstat(host, w, root(), project.first.clone(), project.head.clone(), Vec::new()) ), call!("vcs_merge_base", "", vcs::vcs_merge_base(host, w, root(), project.first.clone(), project.head.clone())), + call!("vcs_has_commit", "", vcs::vcs_has_commit(host, w, root(), project.head.clone())), + call!( + "vcs_not_cherry_picked", + "", + vcs::vcs_not_cherry_picked(host, w, root(), project.head.clone(), project.first.clone(), RequestId(4)) + ), + call!( + "vcs_commit_selection_changes", + "", + vcs::vcs_commit_selection_changes(host, w, root(), vec![project.head.clone()], RequestId(5)) + ), + call!("vcs_default_push_target", "", vcs::vcs_default_push_target(host, w, root(), None)), + call!( + "vcs_commit_push_target", + "", + vcs::vcs_commit_push_target(host, w, root(), RequestId(6), project.head.clone()) + ), + call!( + "vcs_push_target_choices", + "commit", + vcs::vcs_push_target_choices(host, w, root(), RequestId(7), None, Some(project.head.clone())) + ), call!("vcs_has_hook", "", vcs::vcs_has_hook(host, w, root(), "pre-push".into())), // A worktree outside the project, opened for its history only. call!("vcs_open_external_log", "", vcs::vcs_open_external_log(host, w, external.root.clone())), @@ -248,6 +293,38 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() { ), call!("vcs_revision_files", "external", vcs::vcs_revision_files(host, w, log(), external.head.clone())), call!("vcs_commit_files", "external", vcs::vcs_commit_files(host, w, log(), external.head.clone())), + ( + "vcs_review_apply_commit", + "paused cherry-pick", + Box::pin(async { + git( + &project.root, + &["-c", "core.fsmonitor=false", "-c", "filter.marker.clean=", "add", "--", "src/a.txt"], + ); + let marker = project.root.join(".git/CHERRY_PICK_HEAD"); + let message = project.root.join(".git/MERGE_MSG"); + std::fs::write(&marker, format!("{}\n", project.head)).unwrap(); + std::fs::write(&message, "Review staged changes\n").unwrap(); + let result = vcs::vcs_review_apply_commit(host, w, root(), RequestId(8)).await; + std::fs::remove_file(marker).unwrap(); + std::fs::remove_file(message).unwrap(); + git( + &project.root, + &[ + "-c", + "core.fsmonitor=false", + "-c", + "filter.marker.clean=", + "reset", + "-q", + "HEAD", + "--", + "src/a.txt", + ], + ); + result.ok().flatten().is_some_and(|review| review.paths.len() == 1 && review.paths[0].0 == file) + }), + ), // Last: it rewrites nothing of an existing repository, but it does touch it. call!("vcs_init", "", vcs::vcs_init(host, w, project.root.clone())), ]; diff --git a/crates/ide-host/tests/vcs_documents.rs b/crates/ide-host/tests/vcs_documents.rs index 182214d2f..915d5083c 100644 --- a/crates/ide-host/tests/vcs_documents.rs +++ b/crates/ide-host/tests/vcs_documents.rs @@ -85,7 +85,7 @@ impl Drop for Fixture { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn checkout_reloads_clean_open_documents_before_returning() { let f = Fixture::new().await; - vcs::vcs_checkout(&f.host, "main", None, "other".into(), false, None).await.unwrap(); + vcs::vcs_checkout(&f.host, "main", None, "other".into(), false, None, None).await.unwrap(); f.assert_clean(OTHER); } @@ -104,7 +104,8 @@ async fn stash_and_unstash_reload_clean_open_documents_before_returning() { f.saved_edit(&edited); vcs::vcs_stash_push(&f.host, "main", None, None, false, false, None).await.unwrap(); f.assert_clean(ORIGINAL); - vcs::vcs_stash_apply(&f.host, "main", None, 0, true, false, None).await.unwrap(); + let selected = vcs::vcs_stashes(&f.host, "main", None).await.unwrap().remove(0); + vcs::vcs_stash_apply(&f.host, "main", None, selected, true, false, None).await.unwrap(); f.assert_clean(&edited); } @@ -114,17 +115,39 @@ async fn applying_patch_reloads_clean_open_documents_before_returning() { std::fs::write(&f.path, OTHER).unwrap(); let patch = git(&f.project.root, &["diff"]); git(&f.project.root, &["restore", "."]); - vcs::vcs_apply_patch(&f.host, "main", None, patch).await.unwrap(); + vcs::vcs_apply_patch(&f.host, "main", None, patch, None).await.unwrap(); f.assert_clean(OTHER); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn writing_patch_file_reloads_its_clean_open_document() { let f = Fixture::new().await; - vcs::vcs_write_patch(&f.host, "main", f.path.clone(), OTHER.into()).await.unwrap(); + vcs::vcs_write_patch(&f.host, "main", f.path.clone(), OTHER.into(), None).await.unwrap(); f.assert_clean(OTHER); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn patch_file_encoding_round_trips_without_normalizing_hunks() { + let f = Fixture::new().await; + let path = f.project.root.join("export.patch"); + let patch = + "diff --git a/notes.txt b/notes.txt\n--- a/notes.txt\n+++ b/notes.txt\n@@ -1 +1 @@\n-Café\r\n+Voilà\r\n"; + vcs::vcs_write_patch(&f.host, "main", path.clone(), patch.into(), Some("utf-16le".into())).await.unwrap(); + assert!(std::fs::read(&path).unwrap().starts_with(&[0xff, 0xfe])); + assert_eq!(vcs::vcs_read_patch(&f.host, "main", path.clone()).await.unwrap(), patch); + + vcs::vcs_write_patch(&f.host, "main", path.clone(), patch.into(), Some("windows-1252".into())).await.unwrap(); + let encoded = std::fs::read(&path).unwrap(); + assert!(encoded.windows(5).any(|bytes| bytes == b"Caf\xe9\r")); + assert!( + vcs::vcs_write_patch(&f.host, "main", path.clone(), "你好".into(), Some("windows-1252".into())).await.is_err() + ); + assert_eq!(std::fs::read(&path).unwrap(), encoded); + + std::fs::write(&path, patch).unwrap(); + assert_eq!(vcs::vcs_read_patch(&f.host, "main", path).await.unwrap(), patch); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn directory_compare_overwrite_reloads_clean_open_documents() { let f = Fixture::new().await; @@ -184,7 +207,7 @@ async fn working_tree_operation_does_not_discard_unsaved_edits() { .documents .edit(f.doc, version, ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "-- local\n".into() }] }) .unwrap(); - vcs::vcs_checkout(&f.host, "main", None, "other".into(), false, None).await.unwrap(); + vcs::vcs_checkout(&f.host, "main", None, "other".into(), false, None, None).await.unwrap(); let snapshot = f.project.documents.snapshot(f.doc).unwrap(); assert_eq!(snapshot.text, format!("-- local\n{ORIGINAL}")); assert!(snapshot.dirty); @@ -235,6 +258,6 @@ async fn worktree_checkout_hook_reloads_clean_open_documents() { std::fs::write(&hook, "#!/bin/sh\nprintf 'SELECT hook;' > ../project/node_modules/query.sql\n").unwrap(); std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); let linked = f.project.root.parent().unwrap().join("linked"); - vcs::vcs_add_worktree(&f.host, "main", None, linked, "other".into(), None).await.unwrap(); + vcs::vcs_add_worktree(&f.host, "main", None, linked, "other".into(), None, None, None).await.unwrap(); f.assert_clean("SELECT hook;"); } diff --git a/crates/ide-host/tests/vcs_flow.rs b/crates/ide-host/tests/vcs_flow.rs index ead460e27..d29c17317 100644 --- a/crates/ide-host/tests/vcs_flow.rs +++ b/crates/ide-host/tests/vcs_flow.rs @@ -151,7 +151,11 @@ async fn change_commit_branch_stash_and_merge_a_conflict() { assert!(ops::vcs::vcs_line_hunks(&f.host, WINDOW, lib_path.clone()).await.unwrap().is_empty()); // A branch changes the line its way. - ops::vcs::vcs_create_branch(&f.host, WINDOW, None, "feature".into(), None, true, None).await.unwrap(); + let created = + ops::vcs::vcs_create_branch(&f.host, WINDOW, None, "feature".into(), None, true, None, None, None, None) + .await + .unwrap(); + assert!(created.created.is_some()); let theirs = "pub fn format_price(cents: u64) -> String { // feature"; f.edit_line(lib, theirs).await; f.save(lib).await; @@ -160,7 +164,7 @@ async fn change_commit_branch_stash_and_merge_a_conflict() { assert!(branches.iter().any(|b| b.name == "feature" && b.current), "{branches:?}"); // Back on main, the open file shows main's text. - ops::vcs::vcs_checkout(&f.host, WINDOW, None, "main".into(), false, None).await.unwrap(); + ops::vcs::vcs_checkout(&f.host, WINDOW, None, "main".into(), false, None, None).await.unwrap(); assert!(f.text(lib).await.contains(base)); // Stash: work in progress put aside and brought back. @@ -173,7 +177,7 @@ async fn change_commit_branch_stash_and_merge_a_conflict() { assert!(!f.text(main_rs).await.contains("work in progress")); let stashes = ops::vcs::vcs_stashes(&f.host, WINDOW, None).await.unwrap(); assert!(matches!(&stashes[..], [s] if s.message.contains("wip")), "{stashes:?}"); - ops::vcs::vcs_stash_apply(&f.host, WINDOW, None, 0, true, false, None).await.unwrap(); + ops::vcs::vcs_stash_apply(&f.host, WINDOW, None, stashes[0].clone(), true, false, None).await.unwrap(); assert_eq!(f.text(main_rs).await, wip); assert!(ops::vcs::vcs_stashes(&f.host, WINDOW, None).await.unwrap().is_empty()); ops::vcs::vcs_discard(&f.host, WINDOW, vec![f.root.join("src/main.rs")]).await.unwrap(); @@ -184,7 +188,8 @@ async fn change_commit_branch_stash_and_merge_a_conflict() { f.edit_line(lib, ours).await; f.save(lib).await; f.commit(&["src/lib.rs"], "Main's change").await; - let merged = ops::vcs::vcs_merge(&f.host, WINDOW, None, "feature".into()).await; + let merged = ops::vcs::vcs_merge(&f.host, WINDOW, None, "feature".into(), None, false).await; + assert!(matches!(merged, Ok(ide_vcs::MergeOutcome::Conflicts)), "{merged:?}"); let status = f.status().await; let conflicted = changed(&status, "src/lib.rs").map(|s| (s.staged, s.unstaged)); assert!( @@ -214,7 +219,7 @@ async fn checkout_reports_a_branch_held_by_another_worktree() { let linked = f._tmp.path().join("linked"); git(&f.root, &["worktree", "add", "-q", "-b", "topic", linked.to_str().unwrap()]); - let outcome = ops::vcs::vcs_checkout(&f.host, WINDOW, None, "topic".into(), false, None).await.unwrap(); + let outcome = ops::vcs::vcs_checkout(&f.host, WINDOW, None, "topic".into(), false, None, None).await.unwrap(); assert_eq!( outcome, ide_vcs::CheckoutOutcome::CheckedOutInWorktree { diff --git a/crates/ide-host/tests/vcs_roots.rs b/crates/ide-host/tests/vcs_roots.rs index 9cc2b9e8d..65f39952e 100644 --- a/crates/ide-host/tests/vcs_roots.rs +++ b/crates/ide-host/tests/vcs_roots.rs @@ -23,6 +23,10 @@ async fn patches_read_and_write_the_requested_repository() { git(root, &["config", "user.email", "test@example.com"]); git(root, &["config", "core.autocrlf", "false"]); std::fs::write(root.join("same.txt"), format!("root {i}\n")).unwrap(); + let source = root.join("located/src"); + std::fs::create_dir_all(&source).unwrap(); + std::fs::write(source.join("settings.txt"), format!("port={}\n", if i == 0 { 900 } else { 100 })).unwrap(); + std::fs::write(source.join("report.txt"), "total=100\n").unwrap(); git(root, &["add", "."]); git(root, &["commit", "-m", "initial"]); std::fs::write(root.join("same.txt"), format!("changed {i}\n")).unwrap(); @@ -43,27 +47,452 @@ async fn patches_read_and_write_the_requested_repository() { host.trust.decide(&project_root, true, false).unwrap(); let project = host.open_project("main", &project_root).unwrap(); for _ in 0..500 { - if project.repos().all().len() == 2 { + if project.repos().all().len() == 2 + && !project.index.status().indexing + && project.index.files_named("settings.txt").len() == 2 + { break; } tokio::time::sleep(Duration::from_millis(10)).await; } assert_eq!(project.repos().all().len(), 2); + + let source = roots[1].join("located/src"); + let original = source.join("report.txt"); + let renamed = source.join("new report.txt"); + git(&roots[1], &["mv", "located/src/report.txt", "located/src/new report.txt"]); + let patch = vcs::vcs_create_patch( + &host, + "main", + None, + vcs::PatchSource::Changes { paths: vec![original.into(), renamed.into()], reverse: false }, + Some(roots[1].join("located")), + ) + .await + .unwrap(); + assert!(patch.contains("rename from src/report.txt\n")); + let preview = + vcs::vcs_patch_preview(&host, "main", Some(roots[1].clone()), patch, Some(vcs::PatchTarget::Repository), None) + .await + .unwrap(); + assert_eq!(preview.files.len(), 1); + assert_eq!(preview.files[0].old_path.as_deref(), Some("src/report.txt")); + assert_eq!(preview.files[0].path, "src/new report.txt"); + git(&roots[1], &["reset", "--hard", "HEAD"]); + for (i, root) in roots.iter().enumerate() { let patch = vcs::vcs_create_patch( &host, "main", Some(root.clone()), vcs::PatchSource::Commits { commits: vec![revisions[i].clone()], reverse: true }, + None, ) .await .unwrap(); assert!(patch.contains(&format!("-changed {i}"))); - assert_eq!(vcs::vcs_patch_preview(&host, "main", Some(root.clone()), patch.clone()).await.unwrap().len(), 1); - vcs::vcs_apply_patch(&host, "main", Some(root.clone()), patch).await.unwrap(); + let preview = + vcs::vcs_patch_preview(&host, "main", Some(root.clone()), patch.clone(), None, None).await.unwrap(); + assert!(preview.base.is_none()); + assert_eq!(preview.files.len(), 1); + vcs::vcs_apply_patch(&host, "main", Some(root.clone()), patch, Some(vec!["same.txt".into()])).await.unwrap(); assert_eq!(std::fs::read_to_string(root.join("same.txt")).unwrap(), format!("root {i}\n")); } - assert!(vcs::vcs_apply_patch(&host, "main", Some(base.join("outside")), String::new()).await.is_err()); + assert!(vcs::vcs_apply_patch(&host, "main", Some(base.join("outside")), String::new(), None).await.is_err()); + + for (i, root) in roots.iter().enumerate() { + std::fs::write(root.join("same.txt"), format!("project patch {i}\n")).unwrap(); + } + let entries = roots + .iter() + .map(|root| ide_vcs::StagingPatchEntry { + path: root.join("same.txt").into(), + renamed_from: None, + side: ide_vcs::StagingPatchSide::Unstaged, + }) + .collect(); + let patch = vcs::vcs_create_patch(&host, "main", None, vcs::PatchSource::Staging { entries, reverse: false }, None) + .await + .unwrap(); + let selected_changes = || vcs::PatchSource::Changes { + paths: roots.iter().map(|root| root.join("same.txt").into()).collect(), + reverse: false, + }; + let combined = + vcs::vcs_create_patch(&host, "main", None, selected_changes(), Some(project_root.clone())).await.unwrap(); + assert!(combined.contains("diff --git a/front/same.txt b/front/same.txt")); + assert!(combined.contains("diff --git a/back/same.txt b/back/same.txt")); + let error = + vcs::vcs_create_patch(&host, "main", None, selected_changes(), Some(roots[0].clone())).await.unwrap_err(); + assert_eq!(error.message, "The base directory must contain every selected path"); + for root in &roots { + git(root, &["restore", "--", "same.txt"]); + } + let preview = + vcs::vcs_patch_preview(&host, "main", Some(roots[0].clone()), patch.clone(), None, None).await.unwrap(); + assert_eq!(preview.base.unwrap(), project_root); + assert_eq!( + preview.files.iter().map(|file| file.path.as_str()).collect::>(), + ["back/same.txt", "front/same.txt"] + ); + assert!(preview.files.iter().all(|file| file.applies)); + let diff = vcs::vcs_patch_file_diff( + &host, + "main", + Some(roots[1].clone()), + Some(project_root.clone()), + patch.clone(), + "front/same.txt".into(), + None, + ) + .await + .unwrap(); + assert_eq!(diff.path, roots[0].join("same.txt")); + assert!(matches!( + diff.content, + ide_vcs::PatchDiffContent::Text { before: Some(before), after: Some(after) } + if before == "changed 0\n" && after == "project patch 0\n" + )); + assert_eq!(std::fs::read_to_string(roots[0].join("same.txt")).unwrap(), "changed 0\n"); + + let explicit_repo = vcs::vcs_patch_preview( + &host, + "main", + Some(roots[0].clone()), + patch.clone(), + Some(vcs::PatchTarget::Repository), + None, + ) + .await + .unwrap(); + assert!(explicit_repo.base.is_none()); + assert!(explicit_repo.files.iter().all(|file| !file.applies)); + assert!(vcs::vcs_apply_project_patch(&host, "main", base.join("outside"), patch.clone(), None).await.is_err()); + let cross_root_rename = "diff --git a/front/same.txt b/back/moved.txt\nsimilarity index 100%\nrename from front/same.txt\nrename to back/moved.txt\n"; + assert!( + vcs::vcs_apply_project_patch(&host, "main", project_root.clone(), cross_root_rename.into(), None) + .await + .is_err() + ); + let selected = vcs::vcs_apply_project_patch( + &host, + "main", + project_root.clone(), + patch.clone(), + Some(vec!["front/same.txt".into()]), + ) + .await + .unwrap(); + assert_eq!(selected.outcome.applied, ["front/same.txt"]); + assert!(selected.failures.is_empty()); + assert_eq!(std::fs::read_to_string(roots[0].join("same.txt")).unwrap(), "project patch 0\n"); + assert_eq!(std::fs::read_to_string(roots[1].join("same.txt")).unwrap(), "changed 1\n"); + git(&roots[0], &["restore", "--", "same.txt"]); + std::fs::write(roots[1].join("same.txt"), "local edit\n").unwrap(); + + let partial = vcs::vcs_apply_project_patch(&host, "main", project_root.clone(), patch.clone(), None).await.unwrap(); + assert_eq!(partial.outcome.applied, ["front/same.txt"]); + assert!(partial.outcome.conflicts.is_empty()); + assert_eq!(partial.failures.len(), 1); + assert_eq!(partial.failures[0].root, roots[1]); + assert_eq!(std::fs::read_to_string(roots[0].join("same.txt")).unwrap(), "project patch 0\n"); + assert_eq!(std::fs::read_to_string(roots[1].join("same.txt")).unwrap(), "local edit\n"); + for root in &roots { + assert!(git(root, &["diff", "--cached", "--name-only"]).is_empty()); + } + git(&roots[0], &["restore", "--", "same.txt"]); + git(&roots[1], &["commit", "-am", "conflicting local commit"]); + let conflicted = vcs::vcs_apply_project_patch(&host, "main", project_root, patch, None).await.unwrap(); + assert_eq!(conflicted.outcome.applied, ["front/same.txt"]); + assert_eq!(conflicted.outcome.conflicts, ["back/same.txt"]); + assert_eq!(conflicted.conflicted_repositories, [roots[1].clone()]); + assert!(conflicted.failures.is_empty()); + assert_eq!(git(&roots[1], &["diff", "--name-only", "--diff-filter=U"]), "same.txt"); + let conflict = roots[1].join("same.txt"); + let versions = vcs::vcs_conflict_versions(&host, "main", conflict.clone()).await.unwrap(); + assert_eq!(versions.sides.operation.as_deref(), Some("apply-patch")); + assert!(!versions.sides.reversed); + assert_eq!(versions.ours.as_deref(), Some("local edit\n")); + assert_eq!(versions.theirs.as_deref(), Some("project patch 1\n")); + vcs::vcs_accept_conflict_side(&host, "main", vec![conflict.clone()], ide_vcs::ConflictSide::Theirs).await.unwrap(); + assert_eq!(std::fs::read_to_string(conflict).unwrap(), "project patch 1\n"); + + git(&roots[1], &["restore", "--source=HEAD", "--staged", "--worktree", "--", "same.txt"]); + let target = roots[1].join("moved here"); + std::fs::create_dir_all(&target).unwrap(); + std::fs::write(target.join("before.txt"), "content\n").unwrap(); + let source = "legacy/path/after.txt"; + let patch = concat!( + "diff --git a/legacy/path/before.txt b/legacy/path/after.txt\n", + "similarity index 100%\nrename from legacy/path/before.txt\nrename to legacy/path/after.txt\n", + "diff --git a/same.txt b/same.txt\n--- a/same.txt\n+++ b/same.txt\n", + "@@ -1 +1 @@\n-project patch 0\n+unselected\n" + ); + let mapping = || ide_vcs::PatchPathMapping { + path: source.into(), + directory: Some(target.clone().into()), + strip: 2, + file: None, + }; + let make_invalid = |directory| ide_vcs::PatchPathMapping { + path: "same.txt".into(), + directory: Some(directory), + strip: 0, + file: None, + }; + let preview = vcs::vcs_patch_preview( + &host, + "main", + Some(roots[0].clone()), + patch.into(), + Some(vcs::PatchTarget::Repository), + Some(vec![mapping(), make_invalid(base.clone().into())]), + ) + .await + .unwrap(); + assert!(preview.files[0].applies); + assert!(!preview.files[1].applies); + let placements = preview.placements.unwrap(); + assert_eq!(placements[0].target.as_ref().unwrap(), &target.join("after.txt")); + assert!(placements[1].error.is_some()); + let diff = vcs::vcs_patch_file_diff( + &host, + "main", + Some(roots[0].clone()), + None, + patch.into(), + source.into(), + Some(vec![mapping()]), + ) + .await + .unwrap(); + assert_eq!(diff.path, target.join("after.txt")); + assert_eq!(diff.old_path.unwrap(), target.join("before.txt")); + assert!( + matches!(diff.content, ide_vcs::PatchDiffContent::Text { before: Some(before), after: Some(after) } if before == "content\n" && before == after) + ); + assert!(target.join("before.txt").exists()); + assert!(!target.join("after.txt").exists()); + assert!( + vcs::vcs_apply_mapped_patch( + &host, + "main", + Some(roots[0].clone()), + None, + patch.into(), + None, + vec![mapping(), make_invalid(base.into())], + ) + .await + .is_err() + ); + assert!(target.join("before.txt").exists()); + let applied = vcs::vcs_apply_mapped_patch( + &host, + "main", + Some(roots[0].clone()), + None, + patch.into(), + Some(vec![source.into()]), + vec![mapping()], + ) + .await + .unwrap(); + assert!(applied.failures.is_empty()); + assert_eq!(applied.outcome.applied, [ide_core::ipc_path::to_ipc(&target.join("after.txt"))]); + assert!(!target.join("before.txt").exists()); + assert_eq!(std::fs::read_to_string(target.join("after.txt")).unwrap(), "content\n"); + assert_eq!(std::fs::read_to_string(roots[0].join("same.txt")).unwrap(), "project patch 0\n"); + + let patch = concat!( + "diff --git a/legacy/original.txt b/legacy/renamed.txt\n", + "similarity index 55%\nrename from legacy/original.txt\nrename to legacy/renamed.txt\n", + "--- a/legacy/original.txt\n+++ b/legacy/renamed.txt\n", + "@@ -1 +1 @@\n-content\n+repaired content\n", + ); + let source = "legacy/renamed.txt"; + let existing = target.join("local name.txt"); + std::fs::write(&existing, "content\n").unwrap(); + let to_file = |path: &std::path::Path| ide_vcs::PatchPathMapping { + path: source.into(), + directory: None, + strip: 0, + file: Some(path.into()), + }; + let root = Some(roots[0].clone()); + let preview = vcs::vcs_patch_preview(&host, "main", root.clone(), patch.into(), None, None).await.unwrap(); + assert!(preview.files[0].missing_base); + let invalid = vcs::vcs_patch_preview(&host, "main", root.clone(), patch.into(), None, Some(vec![to_file(&target)])) + .await + .unwrap(); + assert!(invalid.placements.unwrap()[0].error.is_some()); + let mapped = + vcs::vcs_patch_preview(&host, "main", root.clone(), patch.into(), None, Some(vec![to_file(&existing)])) + .await + .unwrap(); + assert_eq!(mapped.files[0].path, source); + assert!(!mapped.files[0].missing_base); + assert!(mapped.files[0].applies); + assert_eq!(mapped.placements.unwrap()[0].target.as_ref().unwrap(), &existing); + let diff = vcs::vcs_patch_file_diff( + &host, + "main", + root.clone(), + None, + patch.into(), + source.into(), + Some(vec![to_file(&existing)]), + ) + .await + .unwrap(); + assert_eq!(diff.path, existing); + assert!(diff.old_path.is_none()); + assert!(matches!(diff.content, ide_vcs::PatchDiffContent::Text { before: Some(before), after: Some(after) } + if before == "content\n" && after == "repaired content\n")); + let applied = vcs::vcs_apply_mapped_patch(&host, "main", root, None, patch.into(), None, vec![to_file(&existing)]) + .await + .unwrap(); + assert!(applied.failures.is_empty()); + assert_eq!(applied.outcome.applied, [ide_core::ipc_path::to_ipc(&existing)]); + assert_eq!(std::fs::read_to_string(&existing).unwrap(), "repaired content\n"); + assert!(!roots[0].join(source).exists() && !target.join("renamed.txt").exists()); + + let patch = concat!( + "diff --git a/checkout/src/settings.txt b/checkout/src/settings.txt\n", + "--- a/checkout/src/settings.txt\n+++ b/checkout/src/settings.txt\n", + "@@ -1 +1 @@\n-port=100\n+port=200\n", + "diff --git a/checkout/src/report.txt b/checkout/src/report.txt\n", + "--- a/checkout/src/report.txt\n+++ b/checkout/src/report.txt\n", + "@@ -1 +1 @@\n-total=100\n+total=200\n", + ); + let root = Some(roots[0].clone()); + let preview = vcs::vcs_patch_preview(&host, "main", root.clone(), patch.into(), None, None).await.unwrap(); + let automatic = preview.automatic_mappings; + assert_eq!(automatic.len(), 1); + assert_eq!(automatic[0].path, "checkout/src/settings.txt"); + assert_eq!(automatic[0].directory.as_ref().unwrap(), &roots[1].join("located")); + assert_eq!(automatic[0].strip, 1); + assert!(preview.files[0].applies && !preview.files[0].missing_base); + assert!(preview.files[1].missing_base); + assert_eq!(preview.directory_matches[0].candidates[0].applies, Some(true)); + assert_eq!(preview.directory_matches[0].candidates[1].applies, Some(false)); + assert_eq!(preview.directory_matches[1].candidates.len(), 2); + assert!(preview.directory_matches[1].candidates.iter().all(|candidate| candidate.applies == Some(true))); + let repo_only = + vcs::vcs_patch_preview(&host, "main", root.clone(), patch.into(), Some(vcs::PatchTarget::Repository), None) + .await + .unwrap(); + assert!(repo_only.automatic_mappings.is_empty()); + assert!(repo_only.files.iter().all(|file| file.missing_base)); + assert!(repo_only.directory_matches.iter().all(|matches| matches.candidates.len() == 1)); + let report = preview.directory_matches[1] + .candidates + .iter() + .find(|candidate| candidate.source.starts_with(&roots[0])) + .unwrap(); + let selected = ide_vcs::PatchPathMapping { + path: "checkout/src/report.txt".into(), + directory: Some(report.directory.clone()), + strip: report.strip, + file: None, + }; + let reset = ide_vcs::PatchPathMapping { path: automatic[0].path.clone(), directory: None, strip: 0, file: None }; + let reset_preview = + vcs::vcs_patch_preview(&host, "main", root.clone(), patch.into(), None, Some(vec![reset])).await.unwrap(); + assert!(reset_preview.automatic_mappings.is_empty()); + assert!(reset_preview.files[0].missing_base); + let mappings = [automatic, vec![selected]].concat(); + let diff = vcs::vcs_patch_file_diff( + &host, + "main", + root.clone(), + None, + patch.into(), + mappings[0].path.clone(), + Some(mappings.clone()), + ) + .await + .unwrap(); + assert_eq!(diff.path, roots[1].join("located/src/settings.txt")); + let applied = vcs::vcs_apply_mapped_patch(&host, "main", root, None, patch.into(), None, mappings).await.unwrap(); + assert!(applied.failures.is_empty()); + assert_eq!(applied.outcome.applied.len(), 2); + assert_eq!(std::fs::read_to_string(&*report.source).unwrap(), "total=200\n"); + assert_eq!(std::fs::read_to_string(roots[1].join("located/src/report.txt")).unwrap(), "total=100\n"); + assert_eq!(std::fs::read_to_string(roots[1].join("located/src/settings.txt")).unwrap(), "port=200\n"); + assert_eq!(std::fs::read_to_string(roots[0].join("located/src/settings.txt")).unwrap(), "port=900\n"); + + // Empty folders never appear in the filename index. The patch should still preserve + // the new subfolder beneath the matched parent and leave a tie at the original path. + let mail = roots[1].join("modules/mail/templates"); + let ignored = roots[0].join("cache/mail/templates"); + for path in [&mail, &ignored, &roots[0].join("alpha/widgets/templates"), &roots[1].join("beta/widgets/templates")] { + std::fs::create_dir_all(path).unwrap(); + } + std::fs::write(roots[0].join(".git/info/exclude"), "/cache/\n").unwrap(); + let new_mail = "checkout/mail/templates/emails/welcome.txt"; + let new_widget = "checkout/widgets/templates/banner.txt"; + let existing_parent = "located/src/new-settings.txt"; + let generic_parent = "checkout/src/new-module.txt"; + let patch = [new_mail, new_widget, existing_parent, generic_parent] + .iter() + .map(|path| { + format!("diff --git a/{path} b/{path}\nnew file mode 100644\n--- /dev/null\n+++ b/{path}\n@@ -0,0 +1 @@\n+new content\n") + }) + .collect::(); + let root = Some(roots[0].clone()); + let preview = vcs::vcs_patch_preview(&host, "main", root.clone(), patch.clone(), None, None).await.unwrap(); + assert!(preview.files.iter().all(|file| file.applies && !file.missing_base)); + assert_eq!(preview.automatic_mappings.len(), 1); + assert_eq!(preview.automatic_mappings[0].path, new_mail); + assert_eq!(preview.automatic_mappings[0].strip, 1); + assert_eq!(preview.automatic_mappings[0].directory.as_ref().unwrap(), &roots[1].join("modules")); + assert_eq!(preview.directory_matches.len(), 2); + assert_eq!(preview.directory_matches[0].path, new_mail); + assert_eq!(preview.directory_matches[0].candidates.len(), 1); + assert_eq!(preview.directory_matches[1].path, new_widget); + assert_eq!(preview.directory_matches[1].candidates.len(), 2); + let expected = mail.join("emails/welcome.txt"); + let placement = |path: &str| { + let placements = preview.placements.as_ref().unwrap(); + placements.iter().find(|entry| entry.path == path).unwrap().target.as_ref().unwrap() + }; + assert_eq!(placement(new_mail), &expected); + assert_eq!(placement(new_widget), &roots[0].join(new_widget)); + assert_eq!(placement(existing_parent), &roots[0].join(existing_parent)); + assert_eq!(placement(generic_parent), &roots[0].join(generic_parent)); + let diff = vcs::vcs_patch_file_diff( + &host, + "main", + root.clone(), + None, + patch.clone(), + new_mail.into(), + Some(preview.automatic_mappings.clone()), + ) + .await + .unwrap(); + assert_eq!(diff.path, expected); + assert!( + matches!(diff.content, ide_vcs::PatchDiffContent::Text { before: None, after: Some(after) } if after == "new content\n") + ); + let applied = vcs::vcs_apply_mapped_patch( + &host, + "main", + root, + None, + patch, + Some(vec![new_mail.into(), new_widget.into()]), + preview.automatic_mappings, + ) + .await + .unwrap(); + assert!(applied.failures.is_empty()); + assert_eq!(applied.outcome.applied.len(), 2); + assert_eq!(std::fs::read_to_string(expected).unwrap(), "new content\n"); + assert_eq!(std::fs::read_to_string(roots[0].join(new_widget)).unwrap(), "new content\n"); + assert!(!ignored.join("emails/welcome.txt").exists()); + assert!(!roots[0].join(existing_parent).exists()); host.close_project("main"); } diff --git a/crates/ide-host/tests/vcs_shelf_roots.rs b/crates/ide-host/tests/vcs_shelf_roots.rs index 45baa4871..7b3470815 100644 --- a/crates/ide-host/tests/vcs_shelf_roots.rs +++ b/crates/ide-host/tests/vcs_shelf_roots.rs @@ -8,27 +8,7 @@ fn git(root: &Path, args: &[&str]) { assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); } -async fn check_shelves(layout: &str) { - let temp = tempfile::tempdir().unwrap(); - let base = dunce::canonicalize(temp.path()).unwrap(); - let project_root = base.join("project"); - let roots = match layout { - "same" => vec![project_root.clone()], - "below" => vec![base.clone()], - "two" => vec![project_root.join("项目A"), project_root.join("repoB")], - _ => vec![project_root.join("项目A")], - }; - std::fs::create_dir_all(project_root.join("dirB")).unwrap(); - for (i, root) in roots.iter().enumerate() { - std::fs::create_dir_all(root.join("src")).unwrap(); - git(root, &["init", "-b", "main"]); - git(root, &["config", "user.name", "Test"]); - git(root, &["config", "user.email", "test@example.com"]); - std::fs::write(root.join("src/same.txt"), format!("base {i}\n")).unwrap(); - git(root, &["add", "src"]); - git(root, &["commit", "-m", "initial"]); - std::fs::write(root.join("src/same.txt"), format!("shelved {i}\n")).unwrap(); - } +async fn open_project(base: &Path, root: &Path, repo_count: usize) -> Host { let host = Host::new(HostConfig { config_dir: base.join("config"), data_dir: base.join("data"), @@ -40,22 +20,99 @@ async fn check_shelves(layout: &str) { runtime: tokio::runtime::Handle::current(), project_environment: false, }); - host.trust.decide(&project_root, true, false).unwrap(); - let project = host.open_project("main", &project_root).unwrap(); + host.trust.decide(root, true, false).unwrap(); + let project = host.open_project("main", root).unwrap(); for _ in 0..500 { - if project.repos().all().len() == roots.len() { + if project.repos().all().len() == repo_count { break; } tokio::time::sleep(Duration::from_millis(10)).await; } - assert_eq!(project.repos().all().len(), roots.len()); + assert_eq!(project.repos().all().len(), repo_count); + host +} + +async fn check_shelves(layout: &str) { + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let project_root = base.join("project"); + let roots = match layout { + "same" => vec![project_root.clone()], + "below" => vec![base.clone()], + "two" => vec![project_root.join("项目A"), project_root.join("repo B")], + _ => vec![project_root.join("项目A")], + }; + std::fs::create_dir_all(project_root.join("dirB")).unwrap(); + for (i, root) in roots.iter().enumerate() { + std::fs::create_dir_all(root.join("src")).unwrap(); + git(root, &["init", "-b", "main"]); + git(root, &["config", "user.name", "Test"]); + git(root, &["config", "user.email", "test@example.com"]); + git(root, &["config", "core.autocrlf", "false"]); + std::fs::write(root.join("src/same.txt"), format!("base {i}\n")).unwrap(); + git(root, &["add", "src"]); + git(root, &["commit", "-m", "initial"]); + std::fs::write(root.join("src/same.txt"), format!("shelved {i}\n")).unwrap(); + } + let host = open_project(&base, &project_root, roots.len()).await; + let project = host.project("main").unwrap(); let primary = project.repos().primary().unwrap().root().to_path_buf(); if roots.len() == 2 { assert!( + vcs::vcs_shelve( + &host, + "main", + "outside".into(), + vec![roots[0].join("src/same.txt"), project_root.join("dirB/unmapped.txt")], + ) + .await + .is_err() + ); + let entry = vcs::vcs_shelve(&host, "main", "mixed".into(), roots.iter().map(|r| r.join("src/same.txt")).collect()) .await - .is_err() - ); + .unwrap(); + let key = |root: &Path| format!("{}/src/same.txt", root.file_name().unwrap().to_str().unwrap()); + assert_eq!(entry.repo.as_deref(), Some(project_root.as_path())); + assert_eq!(entry.files.len(), 2); + let listed = vcs::vcs_shelves(&host, "main").await.unwrap(); + assert_eq!(listed.len(), 1); + let diffs = vcs::vcs_shelf_diff(&host, "main", entry.id.clone()).await.unwrap(); + for (i, root) in roots.iter().enumerate() { + let diff = diffs.iter().find(|diff| diff.path == key(root)).unwrap(); + assert_eq!(diff.before.as_deref(), Some(format!("base {i}\n").as_str())); + assert_eq!(diff.after.as_deref(), Some(format!("shelved {i}\n").as_str())); + assert_eq!(std::fs::read_to_string(root.join("src/same.txt")).unwrap(), format!("base {i}\n")); + } + let saved = ide_core::project_dir::path(&project_root, "shelf").join(&entry.id).join("shelf.json"); + let original = std::fs::read(&saved).unwrap(); + std::fs::remove_file(&saved).unwrap(); + assert!(vcs::vcs_unshelve(&host, "main", entry.id.clone(), true, None).await.is_err()); + let mut metadata: serde_json::Value = serde_json::from_slice(&original).unwrap(); + metadata["repositories"][1]["root"] = serde_json::json!(base.join("missing-repository")); + std::fs::write(&saved, serde_json::to_vec(&metadata).unwrap()).unwrap(); + assert!(vcs::vcs_unshelve(&host, "main", entry.id.clone(), true, None).await.is_err()); + assert_eq!(std::fs::read_to_string(roots[0].join("src/same.txt")).unwrap(), "base 0\n"); + std::fs::write(saved, original).unwrap(); + let chosen = key(&roots[1]); + let patch = vcs::vcs_shelf_patch(&host, "main", entry.id.clone(), Some(chosen.clone()), None).await.unwrap(); + assert!(patch.contains(&format!("a/{chosen}"))); + assert!(!patch.contains("+shelved 0")); + let relocated = + vcs::vcs_shelf_patch(&host, "main", entry.id.clone(), Some(chosen.clone()), Some(roots[1].join("src"))) + .await + .unwrap(); + assert!(relocated.contains("diff --git a/same.txt b/same.txt")); + assert!(relocated.contains("+shelved 1")); + assert!(!relocated.contains("+shelved 0")); + let outcome = vcs::vcs_unshelve(&host, "main", entry.id.clone(), true, Some(chosen.clone())).await.unwrap(); + assert_eq!(outcome.applied, [chosen]); + assert_eq!(std::fs::read_to_string(roots[0].join("src/same.txt")).unwrap(), "base 0\n"); + assert_eq!(std::fs::read_to_string(roots[1].join("src/same.txt")).unwrap(), "shelved 1\n"); + let remainder = vcs::vcs_shelves(&host, "main").await.unwrap(); + assert_eq!(remainder[0].files.iter().map(|file| file.path.as_str()).collect::>(), [key(&roots[0])]); + let outcome = vcs::vcs_unshelve(&host, "main", entry.id.clone(), true, None).await.unwrap(); + assert_eq!(outcome.applied, [key(&roots[0])]); assert!(vcs::vcs_shelves(&host, "main").await.unwrap().is_empty()); } for (i, root) in roots.iter().enumerate() { @@ -68,7 +125,7 @@ async fn check_shelves(layout: &str) { assert_eq!(diffs[0].before.as_deref(), Some(format!("base {i}\n").as_str())); assert_eq!(diffs[0].after.as_deref(), Some(format!("shelved {i}\n").as_str())); vcs::vcs_shelf_rename(&host, "main", entry.id.clone(), "renamed".into()).await.unwrap(); - let patch = vcs::vcs_shelf_patch(&host, "main", entry.id.clone(), None).await.unwrap(); + let patch = vcs::vcs_shelf_patch(&host, "main", entry.id.clone(), None, None).await.unwrap(); vcs::vcs_shelf_import(&host, "main", Some(root.clone()), "imported".into(), patch).await.unwrap(); let imported = vcs::vcs_shelves(&host, "main").await.unwrap().into_iter().find(|s| s.name == "imported").unwrap(); @@ -103,6 +160,23 @@ async fn check_shelves(layout: &str) { ); } } + if roots.len() == 2 { + let entry = + vcs::vcs_shelve(&host, "main", "conflicts".into(), roots.iter().map(|r| r.join("src/same.txt")).collect()) + .await + .unwrap(); + std::fs::write(roots[0].join("src/same.txt"), "new HEAD\n").unwrap(); + git(&roots[0], &["commit", "-am", "conflicting change"]); + let outcome = vcs::vcs_unshelve(&host, "main", entry.id.clone(), true, None).await.unwrap(); + let qualified = |root: &Path| format!("{}/src/same.txt", root.file_name().unwrap().to_str().unwrap()); + assert_eq!(outcome.conflicts, [qualified(&roots[0])]); + assert_eq!(outcome.applied, [qualified(&roots[1])]); + assert_eq!(std::fs::read_to_string(roots[1].join("src/same.txt")).unwrap(), "shelved 1\n"); + let listed = vcs::vcs_shelves(&host, "main").await.unwrap(); + let pending = listed.iter().find(|s| s.id == entry.id).unwrap(); + assert_eq!(pending.files.len(), 1); + assert_eq!(pending.files[0].path, qualified(&roots[0])); + } host.close_project("main"); } @@ -122,3 +196,85 @@ async fn shelves_in_two_repositories() { async fn shelf_in_project_below_repository() { check_shelves("below").await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn automatic_shelf_batch_restores_repositories_independently() { + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let project_root = base.join("project"); + let clean = project_root.join("repo A"); + let paused = project_root.join("repo B"); + for root in [&clean, &paused] { + std::fs::create_dir_all(root.join("src")).unwrap(); + git(root, &["init", "-b", "main"]); + git(root, &["config", "user.name", "Test"]); + git(root, &["config", "user.email", "test@example.com"]); + git(root, &["config", "core.autocrlf", "false"]); + for file in ["src/same.txt", "src/deleted-shelf-file.txt", "merge.txt"] { + std::fs::write(root.join(file), "base\n").unwrap(); + } + git(root, &["add", "."]); + git(root, &["commit", "-m", "base"]); + git(root, &["switch", "-c", "topic"]); + std::fs::write(root.join("merge.txt"), "topic\n").unwrap(); + git(root, &["commit", "-am", "topic"]); + git(root, &["switch", "main"]); + } + std::fs::write(paused.join("merge.txt"), "main\n").unwrap(); + git(&paused, &["commit", "-am", "main"]); + std::fs::write(clean.join("src/same.txt"), "staged in A\n").unwrap(); + git(&clean, &["add", "src/same.txt"]); + std::fs::write(clean.join("src/deleted-shelf-file.txt"), "remove from shelf\n").unwrap(); + std::fs::write(paused.join("src/same.txt"), "saved in B\n").unwrap(); + + let host = open_project(&base, &project_root, 2).await; + let batch = uuid::Uuid::new_v4().to_string(); + let merge = |repo| vcs::vcs_merge(&host, "main", Some(repo), "topic".into(), Some(batch.clone()), true); + assert_eq!(merge(clean.clone()).await.unwrap(), ide_vcs::MergeOutcome::Done); + assert_eq!(merge(paused.clone()).await.unwrap(), ide_vcs::MergeOutcome::Conflicts); + assert_eq!(std::fs::read_to_string(clean.join("src/same.txt")).unwrap(), "base\n"); + assert_eq!(std::fs::read_to_string(paused.join("src/same.txt")).unwrap(), "base\n"); + let shelves = vcs::vcs_shelves(&host, "main").await.unwrap(); + assert_eq!(shelves.len(), 1); + let shelf = &shelves[0]; + assert_eq!(shelf.repo.as_deref(), Some(project_root.as_path())); + assert_eq!(shelf.files.len(), 3); + let diffs = vcs::vcs_shelf_diff(&host, "main", shelf.id.clone()).await.unwrap(); + for (path, after) in [("repo A/src/same.txt", "staged in A\n"), ("repo B/src/same.txt", "saved in B\n")] { + let diff = diffs.iter().find(|diff| diff.path == path).unwrap(); + assert_eq!(diff.before.as_deref(), Some("base\n")); + assert_eq!(diff.after.as_deref(), Some(after)); + } + + let repositories = vec![Some(clean.clone()), Some(paused.clone())]; + vcs::vcs_finish_shelf_batch(&host, "main", uuid::Uuid::new_v4().to_string(), repositories.clone()).await.unwrap(); + assert_eq!(std::fs::read_to_string(clean.join("src/same.txt")).unwrap(), "base\n"); + vcs::vcs_shelf_delete(&host, "main", shelf.id.clone(), Some("repo A/src/deleted-shelf-file.txt".into())) + .await + .unwrap(); + vcs::vcs_finish_shelf_batch(&host, "main", batch, repositories).await.unwrap(); + assert_eq!(std::fs::read_to_string(clean.join("src/same.txt")).unwrap(), "staged in A\n"); + assert_eq!(std::fs::read_to_string(clean.join("src/deleted-shelf-file.txt")).unwrap(), "base\n"); + let index = Command::new("git").current_dir(&clean).args(["show", ":src/same.txt"]).output().unwrap(); + assert!(index.status.success()); + assert_eq!(index.stdout, b"staged in A\n"); + assert_eq!(std::fs::read_to_string(paused.join("src/same.txt")).unwrap(), "base\n"); + let pending = vcs::vcs_shelves(&host, "main").await.unwrap(); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].id, shelf.id); + assert_eq!(pending[0].files.len(), 1); + assert_eq!(pending[0].files[0].path, "repo B/src/same.txt"); + vcs::vcs_operation( + &host, + "main", + Some(paused.clone()), + ide_core::RequestId(1), + vcs::GitOperation::Abort { expected: Some("merge".into()), expected_rebase: None }, + ide_host::ops::Channel::new(|_| {}), + ) + .await + .unwrap(); + assert_eq!(std::fs::read_to_string(paused.join("src/same.txt")).unwrap(), "saved in B\n"); + assert!(vcs::vcs_shelves(&host, "main").await.unwrap().is_empty()); + host.close_project("main"); +} diff --git a/crates/ide-host/tests/vcs_worktrees.rs b/crates/ide-host/tests/vcs_worktrees.rs index ba5991d18..51d14a1ce 100644 --- a/crates/ide-host/tests/vcs_worktrees.rs +++ b/crates/ide-host/tests/vcs_worktrees.rs @@ -1,4 +1,4 @@ -use ide_core::NullSink; +use ide_core::{NullSink, RequestId}; use ide_host::{Host, HostConfig, Project, ops::vcs}; use std::{path::PathBuf, process::Command, sync::Arc, time::Duration}; @@ -62,15 +62,38 @@ impl Drop for Fixture { } } +fn setup_script(root: &std::path::Path, unix: &str, windows: &str) -> PathBuf { + let file = root.join(if cfg!(windows) { "local setup.cmd" } else { "local setup.sh" }); + if cfg!(windows) { + std::fs::write(&file, format!("@echo off\r\n{}", windows.replace('\n', "\r\n"))).unwrap(); + } else { + std::fs::write(&file, format!("#!/bin/sh\n{unix}")).unwrap(); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + file +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn command_added_worktree_joins_the_repository_set() { let f = Fixture::new().await; let linked = f.root.join("linked"); - vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "main".into(), Some("topic".into())).await.unwrap(); + vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "main".into(), Some("topic".into()), None, None) + .await + .unwrap(); let roots = f.project.repos().roots(); assert!(roots.contains(&linked), "worktree below the project did not join the repository set: {roots:?}"); assert_eq!(roots.len(), 2); - let roots = vcs::vcs_roots(&f.host, "main").unwrap(); + std::fs::write(f.root.join(".worktreeinclude"), ".env\n").unwrap(); + let primary = vcs::vcs_worktree_include(&f.host, "main", Some(f.root.clone())).await.unwrap(); + let include = vcs::vcs_worktree_include(&f.host, "main", Some(linked.clone())).await.unwrap(); + assert!(primary.exists); + assert!(!include.exists); + assert_eq!(include.path.into_path_buf(), linked.join(".worktreeinclude")); + let roots = vcs::vcs_roots(&f.host, "main").await.unwrap(); assert_eq!(roots[0].root, f.root); assert_eq!(roots[0].branch_root, f.root); assert_eq!(roots[0].head.as_deref(), Some("main")); @@ -83,12 +106,176 @@ async fn command_added_worktree_joins_the_repository_set() { async fn removed_worktree_leaves_the_repository_set() { let f = Fixture::new().await; let linked = f.root.join("linked"); - vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "main".into(), Some("topic".into())).await.unwrap(); + vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "main".into(), Some("topic".into()), None, None) + .await + .unwrap(); assert_eq!(f.project.repos().all().len(), 2); vcs::vcs_remove_worktree(&f.host, "main", None, linked, false).await.unwrap(); assert_eq!(f.project.repos().all().len(), 1); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn new_worktree_copies_requested_local_configuration() { + let f = Fixture::new().await; + let write = |name: &str, contents: &str| std::fs::write(f.root.join(name), contents).unwrap(); + write(".env.target", "checkout content"); + git(&f.root, &["add", ".env.target"]); + git(&f.root, &["commit", "-m", "track a destination file"]); + git(&f.root, &["branch", "older"]); + git(&f.root, &["rm", ".env.target"]); + write("old-only.txt", "committed"); + git(&f.root, &["add", "old-only.txt"]); + git(&f.root, &["commit", "-m", "track another file"]); + std::fs::create_dir_all(f.root.join(".openidea")).unwrap(); + write(".openidea/settings.toml", "local settings"); + write(".env", "local environment"); + write(".env.secret", "excluded by negated pattern"); + write(".env.staged", "local staged addition"); + write(".env.target", "local collision"); + git(&f.root, &["add", ".env.staged"]); + write("file.txt", "local edits to a committed file"); + write(".worktreeinclude", ".openidea/settings.toml\n.env*\n!.env.secret\nfile.txt\nold-only.txt\n"); + + let linked = f.root.with_file_name("with config"); + let result = vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "older".into(), None, Some(true), None) + .await + .unwrap(); + assert_eq!(result.copy_warning, None); + for (name, contents) in [ + (".openidea/settings.toml", "local settings"), + (".env", "local environment"), + (".env.staged", "local staged addition"), + (".env.target", "checkout content"), + ("file.txt", "original\n"), + ] { + assert_eq!(std::fs::read_to_string(linked.join(name)).unwrap(), contents); + } + assert!(!linked.join(".env.secret").exists()); + assert!(!linked.join("old-only.txt").exists()); + + let no_copy = f.root.with_file_name("without config"); + vcs::vcs_add_worktree(&f.host, "main", None, no_copy.clone(), "main".into(), Some("opt-out".into()), None, None) + .await + .unwrap(); + assert!(!no_copy.join(".env").exists()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn configuration_copy_failure_keeps_the_created_worktree() { + let f = Fixture::new().await; + std::fs::create_dir(f.root.join(".worktreeinclude")).unwrap(); + let include = vcs::vcs_worktree_include(&f.host, "main", None).await; + assert!(matches!(include, Err(err) if err.kind == ide_core::error::ErrorKind::InvalidInput)); + let linked = f.root.with_file_name("still created"); + let result = vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "HEAD".into(), None, Some(true), None) + .await + .unwrap(); + assert!(result.copy_warning.is_some_and(|error| error.contains(".worktreeinclude"))); + assert!(linked.join("file.txt").exists()); + assert_eq!(vcs::vcs_worktrees(&f.host, "main", None).await.unwrap().len(), 2); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn setup_runs_after_copy_in_the_new_worktree() { + let f = Fixture::new().await; + std::fs::write(f.root.join(".worktreeinclude"), ".env\n").unwrap(); + std::fs::write(f.root.join(".env"), "copied contents").unwrap(); + let script = setup_script( + &f.root, + "test \"$#\" -eq 1 || exit 11\npwd >setup-cwd.txt\nprintf '%s' \"$1\" >setup-arg.txt\ncat .env >setup-copy.txt\n", + "if not \"%~2\"==\"\" exit /b 11\ncd >setup-cwd.txt\necho %1>setup-arg.txt\ntype .env >setup-copy.txt\n", + ); + let linked = f.root.with_file_name("initialized worktree"); + let setup = vcs::WorktreeSetup { script, request: RequestId(1) }; + let result = + vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "HEAD".into(), None, Some(true), Some(setup)) + .await + .unwrap(); + assert_eq!(result.copy_warning, None); + assert_eq!(result.setup_warning, None); + for name in ["setup-cwd.txt", "setup-arg.txt"] { + let value = std::fs::read_to_string(linked.join(name)).unwrap(); + assert_eq!(dunce::canonicalize(value.trim().trim_matches('"')).unwrap(), linked); + } + assert_eq!(std::fs::read_to_string(linked.join("setup-copy.txt")).unwrap(), "copied contents"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn invalid_setup_refuses_creation_and_failed_setup_keeps_the_checkout() { + let f = Fixture::new().await; + let linked = f.root.with_file_name("failed setup"); + let setup = vcs::WorktreeSetup { script: f.root.join("does-not-exist"), request: RequestId(1) }; + assert!( + vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "HEAD".into(), None, None, Some(setup)) + .await + .is_err() + ); + assert!(!linked.exists()); + let script = setup_script(&f.root, "echo failed-script >&2\nexit 7\n", "echo failed-script 1>&2\nexit /b 7\n"); + let setup = vcs::WorktreeSetup { script, request: RequestId(2) }; + let result = vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "HEAD".into(), None, None, Some(setup)) + .await + .unwrap(); + let warning = result.setup_warning.unwrap(); + assert!(warning.contains("code 7") && warning.contains("failed-script"), "{warning}"); + assert!(linked.join("file.txt").exists()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn skipping_setup_stops_the_process_and_keeps_the_checkout() { + let f = Fixture::new().await; + let script = setup_script(&f.root, "touch started\nsleep 45\n", "echo started>started\n:wait\ngoto wait\n"); + let linked = f.root.with_file_name("skipped setup"); + let request = RequestId(3); + let setup = vcs::WorktreeSetup { script, request }; + let (result, ()) = tokio::join!( + vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "HEAD".into(), None, None, Some(setup)), + async { + let started = tokio::time::timeout(Duration::from_secs(5), async { + while !linked.join("started").is_file() { + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await; + f.host.cancel_request(request); + started.unwrap(); + }, + ); + assert_eq!(result.unwrap().setup_warning, None); + assert!(linked.join("file.txt").exists()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn tagged_worktree_can_be_locked_unlocked_and_pruned() { + let f = Fixture::new().await; + // The tag and branch share a short name but point to different commits. + git(&f.root, &["tag", "release"]); + let first = vcs::vcs_worktrees(&f.host, "main", None).await.unwrap()[0].head.clone(); + git(&f.root, &["commit", "--allow-empty", "-m", "next"]); + git(&f.root, &["branch", "release"]); + + let linked = f.root.with_file_name("release copy"); + vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "refs/tags/release".into(), None, None, None) + .await + .unwrap(); + let list = vcs::vcs_worktrees(&f.host, "main", None).await.unwrap(); + assert_eq!(list.len(), 2); + assert_eq!(list[1].branch, None); + assert_eq!(list[1].head, first); + + vcs::vcs_set_worktree_locked(&f.host, "main", None, linked.clone(), true).await.unwrap(); + assert!(vcs::vcs_worktrees(&f.host, "main", None).await.unwrap()[1].locked); + vcs::vcs_prune_worktrees(&f.host, "main", None).await.unwrap(); + assert!(linked.join("file.txt").exists()); + vcs::vcs_set_worktree_locked(&f.host, "main", None, linked.clone(), false).await.unwrap(); + assert!(!vcs::vcs_worktrees(&f.host, "main", None).await.unwrap()[1].locked); + + std::fs::remove_dir_all(&linked).unwrap(); + assert!(vcs::vcs_worktrees(&f.host, "main", None).await.unwrap()[1].prunable); + vcs::vcs_prune_worktrees(&f.host, "main", None).await.unwrap(); + assert_eq!(vcs::vcs_worktrees(&f.host, "main", None).await.unwrap().len(), 1); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn watcher_picks_up_a_worktree_added_below_the_project() { let f = Fixture::new().await; diff --git a/crates/ide-index/src/filter.rs b/crates/ide-index/src/filter.rs index b12f7b82f..d45e4a6b5 100644 --- a/crates/ide-index/src/filter.rs +++ b/crates/ide-index/src/filter.rs @@ -8,6 +8,8 @@ use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; use ignore::{WalkBuilder, WalkState}; +use std::collections::HashSet; +use std::ffi::OsStr; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc; @@ -303,6 +305,27 @@ impl PathFilter { builder.build().flatten().filter(|e| e.file_type().is_some_and(|t| t.is_dir())).map(|e| e.into_path()).collect() } + pub(crate) fn directories_with_names(&self, names: &HashSet<&OsStr>) -> Vec { + let matches = parking_lot::Mutex::new(Vec::new()); + for root in self.roots() { + let Some(mut builder) = self.walker(root) else { continue }; + builder.standard_filters(true).hidden(false).require_git(ide_core::ignored::inside_git_repo(root)); + let matches = &matches; + builder.build_parallel().run(|| { + Box::new(move |entry| { + if let Ok(entry) = entry + && entry.file_type().is_some_and(|ty| ty.is_dir()) + && names.contains(entry.file_name()) + { + matches.lock().push(entry.into_path()); + } + WalkState::Continue + }) + }); + } + matches.into_inner() + } + /// All indexable files at or below `dir`, walked in parallel. /// Stops early (returning what was found so far) once `cancel` is set. pub(crate) fn walk(&self, dir: &Path, cancel: &AtomicBool) -> Vec { diff --git a/crates/ide-index/src/lib.rs b/crates/ide-index/src/lib.rs index 576659ed0..8e8a651a9 100644 --- a/crates/ide-index/src/lib.rs +++ b/crates/ide-index/src/lib.rs @@ -8,7 +8,8 @@ use ide_language::{LanguageRegistry, Syntax}; use parking_lot::Mutex; use serde::{Deserialize, Serialize}; use specta::Type; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; +use std::ffi::OsStr; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::Ordering; @@ -280,6 +281,28 @@ impl ProjectIndex { files.into_iter().map(|file| file.path.clone()).collect() } + /// Find exact basenames across the indexed workspace in a single pass. + pub fn files_with_names(&self, names: &HashSet<&OsStr>) -> Vec { + if names.is_empty() { + return Vec::new(); + } + self.shared + .data + .read() + .files + .iter() + .flatten() + .filter(|file| !file.ignored && file.path.file_name().is_some_and(|name| names.contains(name))) + .map(|file| file.path.clone()) + .collect() + } + + /// Exact folder names in the project scope, including empty folders absent from file search. + /// Run off the caller's request thread because discovering those folders walks the disk. + pub fn directories_with_names(&self, names: &HashSet<&OsStr>) -> Vec { + if names.is_empty() { Vec::new() } else { self.shared.filter().directories_with_names(names) } + } + /// Up to `limit` indexed files below `dir` (VCS-ignored ones left out) whose path relative to /// `dir` satisfies `matches`: a file list without walking the disk. `None` while nothing is /// indexed yet (first scan without a cache). diff --git a/crates/ide-language/src/registry.rs b/crates/ide-language/src/registry.rs index 5c9f04611..6bb321416 100644 --- a/crates/ide-language/src/registry.rs +++ b/crates/ide-language/src/registry.rs @@ -1242,6 +1242,7 @@ mod tests { (".env", "dotenv"), (".env.local", "dotenv"), (".gitignore", "ignore"), + (".worktreeinclude", "ignore"), (".gitattributes", "gitattributes"), ("server.log", "log"), ("player.gd", "gdscript"), diff --git a/crates/ide-lsp/src/handler.rs b/crates/ide-lsp/src/handler.rs index 2240b13be..4ea7f175c 100644 --- a/crates/ide-lsp/src/handler.rs +++ b/crates/ide-lsp/src/handler.rs @@ -360,6 +360,9 @@ impl ClientHandler { else { return; }; + if self.server.redirect_transient_diagnostics(&path, self.generation, params.version, &mut params.diagnostics) { + return; + } if self.server.name == crate::compose::SERVER { // Maven resource-filtering placeholders (`@profileActive@`) parse as invalid // YAML but are replaced before the file is ever read: their parser error is noise. @@ -377,9 +380,8 @@ impl ClientHandler { return; } // Files opened only for a request (references search) are not the user's problems. - if (self.server.external_diagnostics.load(std::sync::atomic::Ordering::Acquire) - && !mgr.docs.lock().values().any(|d| d.path == path)) - || self.server.suppresses_diagnostics(&path) + if self.server.external_diagnostics.load(std::sync::atomic::Ordering::Acquire) + && !mgr.docs.lock().values().any(|d| d.path == path) { return; } diff --git a/crates/ide-lsp/src/inspect.rs b/crates/ide-lsp/src/inspect.rs index cb319b9e3..e7daeca5b 100644 --- a/crates/ide-lsp/src/inspect.rs +++ b/crates/ide-lsp/src/inspect.rs @@ -9,10 +9,11 @@ use crate::convert; use crate::server::Server; -use crate::{LspManager, Target}; +use crate::text::DocText; +use crate::{LspManager, Outcome, Target, scope}; use futures::StreamExt; use ide_core::error::ErrorKind; -use ide_core::{CancellationToken, Diagnostic, DocId, IdeError, IdeResult}; +use ide_core::{CancellationToken, Diagnostic, DocId, IdeError, IdeResult, LanguageId}; use lsp_types as lsp; use serde_json::{Value, json}; use std::path::{Path, PathBuf}; @@ -225,6 +226,48 @@ impl LspManager { } } + /// Checks a snapshot without publishing to Problems or changing the live document. + pub async fn snapshot_diagnostics( + &self, + path: &Path, + language: &LanguageId, + text: &str, + cancel: &CancellationToken, + ) -> IdeResult> { + let targets = tokio::select! { + r = self.snapshot_targets(path, language, "snapshot diagnostics", |c| c.restriction.diagnostics()) => r?, + () = cancel.cancelled() => return Err(IdeError::cancelled()), + }; + let snapshot = scope::snapshot_path(path, "diagnostics")?; + let doc = Arc::new(DocText::new(text)); + let mut result = Outcome::>::new(); + let opts = InspectOptions { timeout: Duration::from_secs(2), ..Default::default() }; + let reports = targets.iter().map(|t| async { + let mut opened = scope::TransientFiles::empty(self, t); + let raw = if t.caps().has("diagnosticProvider") { + opened.hold(&snapshot, language, text); + self.pull_diagnostics(t, &opened.files[0].1, cancel, opts.timeout).await + } else { + let receiver = opened.hold_for_diagnostics(&snapshot, language, text); + wait_for_snapshot_publish(receiver, opts, cancel).await + }; + raw.map(|items| { + let conv = convert::Conv::new(t.enc(), |_| Some(doc.clone())); + items.into_iter().map(|d| convert::diagnostic(&conv, path, d, &t.server.name)).collect::>() + }) + }); + for report in futures::future::join_all(reports).await { + match report { + Ok(items) => result.value.get_or_insert_with(Vec::new).extend(items), + Err(error) => result.fail(error), + } + } + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + result.finish(Vec::new()) + } + /// Fresh diagnostics of the open document `doc`, whose text the caller just synced /// (`changed`: at that instant, so diagnostics published before it are stale). Tells the /// servers the document was saved, since checks that run on save (rust-analyzer's @@ -334,6 +377,22 @@ impl LspManager { } } +async fn wait_for_snapshot_publish( + mut receiver: tokio::sync::watch::Receiver>, + opts: InspectOptions, + cancel: &CancellationToken, +) -> IdeResult> { + let listen = async { + if receiver.changed().await.is_ok() { + while matches!(tokio::time::timeout(opts.settle, receiver.changed()).await, Ok(Ok(()))) {} + } + }; + tokio::select! { + _ = tokio::time::timeout(opts.timeout, listen) => Ok(receiver.borrow().clone()), + () = cancel.cancelled() => Err(IdeError::cancelled()), + } +} + /// Waits until `server` published diagnostics for `path` (after `since`, if /// given) and no further publish arrived for `opts.settle`, or `opts.timeout` /// passed; returns the server's current diagnostics for the file. diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index a5331e60d..6aace2f1a 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -35,6 +35,7 @@ mod plugin_requests; mod pull; mod scope; mod server; +mod source_actions; mod tcp; mod text; mod ts_file_moves; @@ -3189,6 +3190,67 @@ impl LspManager { Ok(!self.ready_targets(&snap.servers, |c| c.has("documentFormattingProvider")).await.is_empty()) } + async fn snapshot_targets( + &self, + path: &Path, + language: &LanguageId, + feature: &str, + supports: impl Fn(&ServerCaps) -> bool, + ) -> IdeResult> { + let supports = |caps: &ServerCaps| caps.open_close && supports(caps); + let servers = self.servers_for(language, path); + for server in &servers { + self.ensure_started(server); + } + let mut targets = self.ready_targets(&servers, supports).await; + if targets.is_empty() { + // A primary server can become unavailable while it initializes. + let candidates = self.servers_for(language, path); + if candidates.iter().any(|server| !servers.iter().any(|old| old.id == server.id)) { + for server in &candidates { + self.ensure_started(server); + } + targets = self.ready_targets(&candidates, supports).await; + } + } + if targets.is_empty() { + return Err(unsupported(&servers, feature)); + } + Ok(targets) + } + + async fn text_format_targets(&self, path: &Path, language: &LanguageId) -> IdeResult> { + self.snapshot_targets(path, language, "snapshot formatting", |c| c.has("documentFormattingProvider")).await + } + + pub async fn can_format_text(&self, path: &Path, language: &LanguageId) -> bool { + self.text_format_targets(path, language).await.is_ok() + } + + /// Use a transient URI so requests in the editor still see the working buffer. + pub async fn format_text( + &self, + path: &Path, + language: &LanguageId, + text: &str, + options: FormatOptions, + ) -> IdeResult> { + let path_to_snapshot = scope::snapshot_path(path, "format")?; + let targets = self.text_format_targets(path, language).await?; + let target = &targets[0]; + let mut opened = scope::TransientFiles::empty(self, target); + opened.hold(&path_to_snapshot, language, text); + let params = json!({ + "textDocument": { "uri": opened.files[0].1 }, + "options": { "tabSize": options.tab_size, "insertSpaces": options.insert_spaces }, + }); + let edits: Option> = + self.call(target, "textDocument/formatting", params, None, DEFAULT_TIMEOUT).await?; + let text = Arc::new(DocText::new(text)); + let converter = Conv::new(target.enc(), |_| Some(text.clone())); + Ok(converter.text_edits(&path_to_snapshot, edits.unwrap_or_default())) + } + pub async fn format(&self, doc: DocId, range: Option, options: FormatOptions) -> IdeResult> { let (method, cap, feature) = match range { None => ("textDocument/formatting", "documentFormattingProvider", "formatting"), diff --git a/crates/ide-lsp/src/scope.rs b/crates/ide-lsp/src/scope.rs index 60f971005..30a9a2b12 100644 --- a/crates/ide-lsp/src/scope.rs +++ b/crates/ide-lsp/src/scope.rs @@ -464,6 +464,22 @@ impl LspManager { } } +/// A separate URI in the source directory, with the language's existing extension. +pub(crate) fn snapshot_path(path: &Path, purpose: &str) -> IdeResult { + use std::sync::atomic::{AtomicU64, Ordering}; + let name = path.file_name().ok_or_else(|| IdeError::invalid("a text snapshot requires a file path"))?; + static NEXT: AtomicU64 = AtomicU64::new(0); + loop { + let serial = NEXT.fetch_add(1, Ordering::Relaxed); + let mut unique = std::ffi::OsString::from(format!(".openidea-{purpose}-{}-{serial}-", std::process::id())); + unique.push(name); + let candidate = path.with_file_name(unique); + if !candidate.exists() { + return Ok(candidate); + } + } +} + /// Files opened by [`LspManager::open_transient`]; closed on drop. pub(crate) struct TransientFiles<'a> { mgr: &'a LspManager, @@ -477,9 +493,30 @@ pub(crate) struct TransientFiles<'a> { impl TransientFiles<'_> { /// Opens one file outside a references search (a file operation needs a loaded project). pub(crate) fn hold(&mut self, path: &Path, language: &LanguageId, text: &str) { + self.hold_file(path, language, text, false); + } + + pub(crate) fn hold_for_diagnostics( + &mut self, + path: &Path, + language: &LanguageId, + text: &str, + ) -> tokio::sync::watch::Receiver> { + self.hold_file(path, language, text, true).expect("diagnostics subscription") + } + + fn hold_file( + &mut self, + path: &Path, + language: &LanguageId, + text: &str, + diagnostics: bool, + ) -> Option>> { let _docs = self.mgr.docs.lock(); let uri = crate::uri::path_to_uri(path); - if self.server.hold_transient(path, self.run.generation) { + let open = self.server.hold_transient(path, self.run.generation); + let receiver = diagnostics.then(|| self.server.watch_transient_diagnostics(path)); + if open { let params = json!({ "textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text } }); if let Err(e) = self.run.peer.notify("textDocument/didOpen", params) { @@ -487,6 +524,7 @@ impl TransientFiles<'_> { } } self.files.push((path.to_owned(), uri)); + receiver } } diff --git a/crates/ide-lsp/src/server.rs b/crates/ide-lsp/src/server.rs index 919695134..f922b0f0d 100644 --- a/crates/ide-lsp/src/server.rs +++ b/crates/ide-lsp/src/server.rs @@ -66,6 +66,7 @@ struct Transient { /// The user opened the file meanwhile: its `didOpen` replaced ours. taken: bool, closed_at: Option, + diagnostics: Option>>, } pub struct Progress { @@ -726,10 +727,15 @@ impl Server { pub fn hold_transient(&self, path: &Path, generation: u64) -> bool { let mut map = self.transient.lock(); map.retain(|_, t| t.holders > 0 || t.closed_at.is_some_and(|c| c.elapsed() < TRANSIENT_GRACE)); - let t = - map.entry(path.to_owned()).or_insert(Transient { holders: 0, generation, taken: false, closed_at: None }); + let t = map.entry(path.to_owned()).or_insert(Transient { + holders: 0, + generation, + taken: false, + closed_at: None, + diagnostics: None, + }); if t.holders == 0 || t.generation != generation { - *t = Transient { holders: 1, generation, taken: false, closed_at: None }; + *t = Transient { holders: 1, generation, taken: false, closed_at: None, diagnostics: None }; return true; } t.holders += 1; @@ -748,6 +754,7 @@ impl Server { if t.holders > 0 { return false; } + t.diagnostics = None; let close = !t.taken && t.generation == generation; if close { t.closed_at = Some(Instant::now()); @@ -765,6 +772,7 @@ impl Server { let open = t.holders > 0 && !t.taken && t.generation == generation; if t.holders > 0 { t.taken = true; + t.diagnostics = None; } else { map.remove(path); } @@ -780,6 +788,34 @@ impl Server { .is_some_and(|t| !t.taken && (t.holders > 0 || t.closed_at.is_some_and(|c| c.elapsed() < TRANSIENT_GRACE))) } + pub(crate) fn watch_transient_diagnostics(&self, path: &Path) -> watch::Receiver> { + let (sender, receiver) = watch::channel(Vec::new()); + if let Some(transient) = self.transient.lock().get_mut(path) { + transient.diagnostics = Some(sender); + } + receiver + } + + /// Delivers a snapshot report privately. Other transient files discard their reports. + pub(crate) fn redirect_transient_diagnostics( + &self, + path: &Path, + generation: u64, + version: Option, + items: &mut Vec, + ) -> bool { + let transients = self.transient.lock(); + let Some(t) = transients.get(path).filter(|t| !t.taken && t.generation == generation) else { + return false; + }; + if let Some(sender) = &t.diagnostics + && version.is_none_or(|v| v == 0) + { + sender.send_replace(std::mem::take(items)); + } + t.holders > 0 || t.closed_at.is_some_and(|c| c.elapsed() < TRANSIENT_GRACE) + } + // ---- bookkeeping ---- pub fn push_stderr(&self, generation: u64, line: String) { diff --git a/crates/ide-lsp/src/source_actions.rs b/crates/ide-lsp/src/source_actions.rs new file mode 100644 index 000000000..946c8bea4 --- /dev/null +++ b/crates/ide-lsp/src/source_actions.rs @@ -0,0 +1,119 @@ +use crate::convert::Conv; +use crate::text::DocText; +use crate::{DEFAULT_TIMEOUT, LspManager, Outcome, Target, scope}; +use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Pos, TextEdit}; +use lsp_types as lsp; +use serde_json::json; +use std::path::Path; +use std::sync::Arc; + +impl LspManager { + /// Reads a source action for an isolated text snapshot. The caller owns the text and applies the edits. + pub async fn source_action_text( + &self, + path: &Path, + language: &LanguageId, + text: &str, + kind: &str, + cancel: &CancellationToken, + ) -> IdeResult> { + if !kind.starts_with("source.") { + return Err(IdeError::invalid("a text snapshot requires a source action")); + } + let targets = + self.snapshot_targets(path, language, "snapshot source actions", |c| c.has("codeActionProvider")).await?; + let path = scope::snapshot_path(path, "source")?; + let mut out = Outcome::new(); + for target in &targets { + match self.snapshot_action(target, &path, language, text, kind, cancel).await { + Ok(edits) if !edits.is_empty() => return Ok(edits), + Ok(edits) => out.value = Some(edits), + Err(error) if cancel.is_cancelled() => return Err(error), + Err(error) => out.fail(error), + } + } + out.finish(Vec::new()) + } + + async fn snapshot_action( + &self, + target: &Target, + path: &Path, + language: &LanguageId, + text: &str, + kind: &str, + cancel: &CancellationToken, + ) -> IdeResult> { + let mut opened = scope::TransientFiles::empty(self, target); + opened.hold(path, language, text); + let uri = &opened.files[0].1; + let doc = Arc::new(DocText::new(text)); + let last = doc.line_count() - 1; + let end = doc.ide_to_lsp(target.enc(), Pos::new(last as u32, doc.line(last).encode_utf16().count() as u32)); + let params = json!({ + "textDocument": { "uri": uri }, + "range": lsp::Range::new(lsp::Position::new(0, 0), end), + "context": { "diagnostics": [], "only": [kind], "triggerKind": 1 }, + }); + let actions: Option> = + self.call(target, "textDocument/codeAction", params, Some(cancel), DEFAULT_TIMEOUT).await?; + let (restriction, resolve) = { + let caps = target.caps(); + (caps.restriction.clone(), caps.has_sub("codeActionProvider", "resolveProvider")) + }; + let mut actions: Vec<_> = actions + .unwrap_or_default() + .into_iter() + .filter_map(|action| match action { + lsp::CodeActionOrCommand::CodeAction(action) + if action.disabled.is_none() + && action.command.is_none() + && action.kind.as_ref().is_some_and(|k| { + let value = k.as_str(); + restriction.keeps_action(Some(value)) + && (value == kind || value.strip_prefix(kind).is_some_and(|rest| rest.starts_with('.'))) + }) => + { + Some(action) + } + _ => None, + }) + .collect(); + actions.sort_by_key(|action| action.is_preferred != Some(true)); + for mut action in actions { + if action.edit.is_none() && action.data.is_some() && resolve { + action = self.call(target, "codeAction/resolve", action, Some(cancel), DEFAULT_TIMEOUT).await?; + } + if action.disabled.is_none() + && action.command.is_none() + && let Some(edits) = action.edit.and_then(|edit| snapshot_edits(edit, uri)) + && !edits.is_empty() + { + return Ok(Conv::new(target.enc(), |_| Some(doc.clone())).text_edits(path, edits)); + } + } + Ok(Vec::new()) + } +} + +fn snapshot_edits(edit: lsp::WorkspaceEdit, uri: &lsp::Uri) -> Option> { + match (edit.changes, edit.document_changes) { + (Some(mut changes), None) if changes.len() == 1 => changes.remove(uri), + (None, Some(lsp::DocumentChanges::Edits(mut edits))) if edits.len() == 1 => { + let edit = edits.pop()?; + if edit.text_document.uri != *uri || edit.text_document.version.is_some_and(|version| version != 0) { + return None; + } + Some( + edit.edits + .into_iter() + .map(|edit| match edit { + lsp::OneOf::Left(edit) => edit, + lsp::OneOf::Right(edit) => edit.text_edit, + }) + .collect(), + ) + } + _ => None, + } +} diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 2ddc023f7..ae4e48ffe 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -4205,6 +4205,156 @@ async fn java_dependency_implementations_point_at_the_method() { assert!(commands.iter().any(|r| r["command"] == "openidea.java.implementationLocations")); } +#[tokio::test(flavor = "multi_thread")] +async fn formatting_a_snapshot_never_changes_an_open_document() { + let caps = json!({ + "positionEncoding": "utf-8", + "textDocumentSync": { "openClose": true, "change": 2 }, + "documentFormattingProvider": true, + }); + let h = harness(&[("mock", caps)]); + let (_, path) = h.open("a.mk", "different working text\n"); + h.wait_status("mock", ServerStatus::Ready).await; + let s = h.launcher.state("mock"); + s.respond( + "textDocument/formatting", + json!([{ "range": { "start": { "line": 0, "character": 4 }, "end": { "line": 0, "character": 5 } }, "newText": "X" }]), + ); + let options = FormatOptions { tab_size: 2, insert_spaces: true, on_save: false, tool: None }; + let edits = h.mgr.format_text(&path, &LanguageId("mock".into()), "🙂b\n", options).await.unwrap(); + assert_eq!(edits, vec![ide_core::TextEdit { range: rng(0, 2, 0, 3), new_text: "X".into() }]); + + let uri = uri_of(&path); + let requests = s.requested("textDocument/formatting"); + let shadow = requests[0]["textDocument"]["uri"].as_str().unwrap(); + assert_ne!(shadow, uri); + let opens = s.notified("textDocument/didOpen"); + let snapshot = opens.iter().find(|n| n["textDocument"]["uri"] == shadow).unwrap(); + assert_eq!(snapshot["textDocument"]["text"], "🙂b\n"); + assert!(s.notified("textDocument/didChange").is_empty()); + eventually(|| uris(&s.notified("textDocument/didClose")) == vec![shadow.to_owned()]).await; + assert!(s.docs.lock().contains_key(&uri)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn snapshot_diagnostics_collect_pull_and_push_without_publishing_problems() { + let mut pull_caps = incremental_caps(); + pull_caps["diagnosticProvider"] = json!({ "interFileDependencies": false, "workspaceDiagnostics": false }); + let mut push_caps = incremental_caps(); + push_caps["positionEncoding"] = json!("utf-8"); + let h = harness(&[("mock", pull_caps), ("push", push_caps)]); + let pull = h.launcher.state("mock"); + *pull.responder.lock() = Some(pull_responder()); + let (_, path) = h.open("a.mk", "clean editor\n"); + h.wait_status("mock", ServerStatus::Ready).await; + h.wait_status("push", ServerStatus::Ready).await; + let push = h.launcher.state("push"); + let live = uri_of(&path); + let shadow = || { + push.notified("textDocument/didOpen") + .into_iter() + .find(|n| n["textDocument"]["text"] == "🙂bad\n") + .and_then(|n| n["textDocument"]["uri"].as_str().map(str::to_owned)) + }; + let send = async { + eventually(|| shadow().is_some()).await; + let uri = shadow().unwrap(); + for (version, message) in [(1, "wrong version"), (0, "snapshot only")] { + push.peer() + .notify( + "textDocument/publishDiagnostics", + json!({ + "uri": uri, "version": version, "diagnostics": [{ + "range": {"start": {"line":0,"character":4}, "end": {"line":0,"character":7}}, + "severity": 2, "message": message + }] + }), + ) + .unwrap(); + } + uri + }; + let language = LanguageId("mock".into()); + let cancel = Default::default(); + let (result, shadow) = tokio::join!(h.mgr.snapshot_diagnostics(&path, &language, "🙂bad\n", &cancel), send); + assert_ne!(shadow, live); + let mut items = result.unwrap(); + items.sort_by(|a, b| a.message.cmp(&b.message)); + assert_eq!(items.iter().map(|d| d.message.as_str()).collect::>(), ["bad", "snapshot only"]); + assert_eq!(items[1].range, rng(0, 2, 0, 5)); + eventually(|| uris(&push.notified("textDocument/didClose")) == vec![shadow.clone()]).await; + assert!(uris(&push.notified("textDocument/didChange")).is_empty()); + assert!(push.docs.lock().contains_key(&live)); + assert!(!h.events.lock().iter().any(|event| matches!( + event, + IdeEvent::Diagnostics { items, .. } if !items.is_empty() + ))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn source_actions_use_snapshot_text_and_accept_only_its_passive_edits() { + let caps = json!({ + "positionEncoding": "utf-8", + "textDocumentSync": { "openClose": true, "change": 2 }, + "codeActionProvider": { "resolveProvider": true }, + }); + let h = harness(&[("mock", caps)]); + let (_, path) = h.open("a.mk", "the live editor\n"); + h.wait_status("mock", ServerStatus::Ready).await; + let s = h.launcher.state("mock"); + let uri = uri_of(&path); + let original = uri.clone(); + *s.responder.lock() = Some(Arc::new(move |_, method, params| { + let edit = json!({ "range": { + "start": { "line": 0, "character": 4 }, "end": { "line": 0, "character": 5 } + }, "newText": "X" }); + match method { + "textDocument/codeAction" => { + let shadow = params["textDocument"]["uri"].as_str().unwrap(); + assert_ne!(shadow, original); + assert_eq!(params["range"]["end"], json!({ "line": 0, "character": 5 })); + assert_eq!(params["context"]["diagnostics"], json!([])); + let kind = params["context"]["only"][0].as_str().unwrap(); + if kind == "source.fixAll" { + return Some(json!([{ "title": "Cleanup", "kind": kind, "edit": { "documentChanges": [{ + "textDocument": { "uri": shadow, "version": 0 }, "edits": [edit] + }] }}])); + } + assert_eq!(kind, "source.organizeImports"); + Some(json!([ + { "title": "Cross-file edit", "kind": kind, "isPreferred": true, + "edit": { "changes": { shadow: [edit.clone()], original.clone(): [edit.clone()] } } }, + { "title": "Command", "kind": kind, "isPreferred": true, + "command": { "title": "Command", "command": "mock.organize" }, + "edit": { "changes": { shadow: [edit] } } }, + { "title": "Organize", "kind": kind, "data": { "snapshot": shadow } } + ])) + } + "codeAction/resolve" => { + let shadow = params["data"]["snapshot"].as_str().unwrap(); + Some(json!({ "title": "Organize", "edit": { "changes": { shadow: [edit] } } })) + } + _ => None, + } + })); + for kind in ["source.organizeImports", "source.fixAll"] { + let edits = h + .mgr + .source_action_text(&path, &LanguageId("mock".into()), "🙂b", kind, &Default::default()) + .await + .unwrap(); + assert_eq!(edits, vec![ide_core::TextEdit { range: rng(0, 2, 0, 3), new_text: "X".into() }]); + } + assert!(s.requested("workspace/executeCommand").is_empty()); + assert!(s.notified("textDocument/didChange").is_empty()); + eventually(|| s.notified("textDocument/didClose").len() == 2).await; + let snapshots: Vec<_> = + s.notified("textDocument/didOpen").into_iter().filter(|notice| notice["textDocument"]["uri"] != uri).collect(); + assert_eq!(snapshots.len(), 2); + assert!(snapshots.iter().all(|notice| notice["textDocument"]["text"] == "🙂b")); + assert!(s.docs.lock().contains_key(&uri)); +} + #[tokio::test(flavor = "multi_thread")] async fn navigation_rename_format_and_decorations() { let h = harness(&[("mock", incremental_caps())]); diff --git a/crates/ide-ssh/src/askpass.rs b/crates/ide-ssh/src/askpass.rs index e5414f3de..cbfa7f7c9 100644 --- a/crates/ide-ssh/src/askpass.rs +++ b/crates/ide-ssh/src/askpass.rs @@ -4,6 +4,7 @@ //! program: started with [`PORT_ENV`] set, it sends the prompt to the //! [`AskpassServer`] on 127.0.0.1 and prints the answer ([`run_helper`]). +use ide_core::process::ASKPASS_SILENT_ENV; use ide_core::{IdeError, IdeResult}; use parking_lot::Mutex; use serde::{Deserialize, Serialize}; @@ -15,7 +16,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc; use std::time::Duration; -pub const PORT_ENV: &str = "OPENIDEA_ASKPASS_PORT"; +pub const PORT_ENV: &str = ide_core::process::ASKPASS_PORT_ENV; pub const COMMAND_ENV: &str = "OPENIDEA_GIT_COMMAND_ID"; pub const TOKEN_ENV: &str = "OPENIDEA_ASKPASS_TOKEN"; /// An unanswered prompt fails after this long. @@ -51,6 +52,8 @@ pub fn remembers(prompt: &str) -> bool { struct Request { #[serde(default)] command_id: Option, + #[serde(default)] + silent: bool, token: String, prompt: String, } @@ -157,12 +160,16 @@ fn serve( let _ = writeln!(out, "{}", serde_json::to_string(&Response { answer: Some(answer) }).unwrap_or_default()); return; } - let (tx, rx) = mpsc::channel(); - pending.lock().insert(id, PendingPrompt { command_id: req.command_id, prompt: prompt.clone(), tx }); - on_prompt(AskpassPrompt { id, kind: classify(&prompt), prompt }); - let answer = rx.recv_timeout(ANSWER_TIMEOUT).ok().flatten(); - pending.lock().remove(&id); - answer + if req.silent { + None + } else { + let (tx, rx) = mpsc::channel(); + pending.lock().insert(id, PendingPrompt { command_id: req.command_id, prompt: prompt.clone(), tx }); + on_prompt(AskpassPrompt { id, kind: classify(&prompt), prompt }); + let answer = rx.recv_timeout(ANSWER_TIMEOUT).ok().flatten(); + pending.lock().remove(&id); + answer + } }; let mut out = stream; let _ = writeln!(out, "{}", serde_json::to_string(&Response { answer }).unwrap_or_default()); @@ -190,9 +197,14 @@ pub fn run_helper() -> Option { let token = std::env::var(TOKEN_ENV).unwrap_or_default(); let prompt = std::env::args().nth(1).unwrap_or_else(|| "Password:".into()); let command_id = std::env::var(COMMAND_ENV).ok().and_then(|id| id.parse().ok()); + let silent = std::env::var(ASKPASS_SILENT_ENV).is_ok_and(|value| value == "1"); let ask = || -> std::io::Result> { let mut stream = TcpStream::connect(("127.0.0.1", port))?; - writeln!(stream, "{}", serde_json::to_string(&Request { command_id, token, prompt }).unwrap_or_default())?; + writeln!( + stream, + "{}", + serde_json::to_string(&Request { command_id, silent, token, prompt }).unwrap_or_default() + )?; let mut line = String::new(); BufReader::new(stream).read_line(&mut line)?; Ok(serde_json::from_str::(&line).ok().and_then(|r| r.answer)) @@ -233,7 +245,13 @@ mod tests { writeln!( stream, "{}", - serde_json::to_string(&Request { command_id: Some(42), token, prompt: "Password: ".into() }).unwrap() + serde_json::to_string(&Request { + command_id: Some(42), + silent: false, + token, + prompt: "Password: ".into() + }) + .unwrap() ) .unwrap(); let mut line = String::new(); @@ -252,4 +270,22 @@ mod tests { assert_eq!(client.join().unwrap().as_deref(), Some("hunter2")); assert!(server.env().iter().any(|(k, v)| k == "SSH_ASKPASS" && v == "helper")); } + + #[test] + fn silent_request_with_no_saved_credentials_returns_without_prompting() { + let server = AskpassServer::start("helper".into(), Arc::new(|_| panic!("unexpected prompt"))).unwrap(); + let mut stream = TcpStream::connect(("127.0.0.1", server.port)).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let request = Request { + command_id: Some(42), + silent: true, + token: server.token.clone(), + prompt: "Password for 'https://test-password.example.invalid': ".into(), + }; + writeln!(stream, "{}", serde_json::to_string(&request).unwrap()).unwrap(); + let mut line = String::new(); + BufReader::new(stream).read_line(&mut line).unwrap(); + assert!(serde_json::from_str::(&line).unwrap().answer.is_none()); + assert!(server.pending.lock().is_empty()); + } } diff --git a/crates/ide-vcs/Cargo.toml b/crates/ide-vcs/Cargo.toml index 512b1bde0..c3de5a825 100644 --- a/crates/ide-vcs/Cargo.toml +++ b/crates/ide-vcs/Cargo.toml @@ -10,6 +10,7 @@ encoding_rs.workspace = true dunce.workspace = true ide-core.workspace = true ignore.workspace = true +notify.workspace = true serde.workspace = true serde_json.workspace = true specta.workspace = true diff --git a/crates/ide-vcs/src/blame.rs b/crates/ide-vcs/src/blame.rs index 3fc2c21dd..1ffe43676 100644 --- a/crates/ide-vcs/src/blame.rs +++ b/crates/ide-vcs/src/blame.rs @@ -1,26 +1,32 @@ //! `git blame --porcelain` parsing. use crate::BlameLine; +use ide_core::IpcPath; use std::collections::HashMap; +use std::path::{Component, Path}; #[derive(Default, Clone)] struct CommitMeta { author: String, time_ms: f64, summary: String, + origin_path: Option, } /// Parses `git blame --porcelain` output into one entry per final line. -pub(crate) fn parse_porcelain(out: &str) -> Vec { +pub(crate) fn parse_porcelain(out: &str, root: &Path, relative_path: &str) -> Vec { let mut metas: HashMap = HashMap::new(); - let mut lines: Vec<(u32, String)> = Vec::new(); - let mut current: Option = None; + let mut lines: Vec<(u32, String, Option)> = Vec::new(); + let mut current: Option<(u32, String)> = None; for line in out.split('\n') { - if let Some(_content) = line.strip_prefix('\t') { - current = None; + if line.starts_with('\t') { + if let Some((number, id)) = current.take() { + let origin = metas.get(&id).and_then(|m| m.origin_path.clone()); + lines.push((number, id, origin)); + } continue; } - if let Some(id) = current.as_ref() { + if let Some((_, id)) = current.as_ref() { let meta = metas.entry(id.clone()).or_default(); if let Some(v) = line.strip_prefix("author ") { meta.author = v.to_string(); @@ -28,6 +34,15 @@ pub(crate) fn parse_porcelain(out: &str) -> Vec { meta.time_ms = v.trim().parse::().unwrap_or(0.0) * 1000.0; } else if let Some(v) = line.strip_prefix("summary ") { meta.summary = v.to_string(); + } else if let Some(v) = line.strip_prefix("filename ") { + // Porcelain repeats the filename at group boundaries when one commit + // contributed lines from multiple files, even when it omits other metadata. + let name = crate::patch::git_path(v); + let path = Path::new(&name); + meta.origin_path = (name != relative_path + && !name.is_empty() + && path.components().all(|c| matches!(c, Component::Normal(_)))) + .then(|| root.join(path).into()); } continue; } @@ -41,15 +56,14 @@ pub(crate) fn parse_porcelain(out: &str) -> Vec { } let Ok(final_line) = final_line.parse::() else { continue }; metas.entry(sha.to_string()).or_default(); - lines.push((final_line, sha.to_string())); - current = Some(sha.to_string()); + current = Some((final_line, sha.to_string())); } - lines.sort_by_key(|(n, _)| *n); + lines.sort_by_key(|(n, ..)| *n); lines .into_iter() - .map(|(_, sha)| { + .map(|(_, sha, origin_path)| { let meta = metas.get(&sha).cloned().unwrap_or_default(); - BlameLine { commit: sha, author: meta.author, time_ms: meta.time_ms, summary: meta.summary } + BlameLine { commit: sha, author: meta.author, time_ms: meta.time_ms, summary: meta.summary, origin_path } }) .collect() } @@ -67,7 +81,7 @@ mod tests { {sha_a} 2 2\n\tl2\n\ {sha_z} 3 3 1\nauthor Not Committed Yet\nauthor-time 200\nsummary Version of f from f\nfilename f\n\tl3\n" ); - let lines = parse_porcelain(&out); + let lines = parse_porcelain(&out, Path::new("root"), "f"); assert_eq!(lines.len(), 3); assert_eq!(lines[1].author, "Ann"); assert_eq!(lines[1].time_ms, 100_000.0); diff --git a/crates/ide-vcs/src/changelists.rs b/crates/ide-vcs/src/changelists.rs index de35593b8..83f509597 100644 --- a/crates/ide-vcs/src/changelists.rs +++ b/crates/ide-vcs/src/changelists.rs @@ -13,7 +13,12 @@ impl ChangelistState { /// The default "Changes" list, active, with no file assignments. pub fn initial() -> Self { ChangelistState { - lists: vec![Changelist { id: DEFAULT_ID.into(), name: DEFAULT_NAME.into(), comment: String::new() }], + lists: vec![Changelist { + id: DEFAULT_ID.into(), + name: DEFAULT_NAME.into(), + comment: String::new(), + applied_commit: None, + }], active: DEFAULT_ID.into(), files: Default::default(), } @@ -39,11 +44,23 @@ impl ChangelistState { pub fn load(file: &Path) -> ChangelistState { std::fs::read(file) .ok() - .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|b| decode(&b).ok()) .map(ChangelistState::normalized) .unwrap_or_else(ChangelistState::initial) } +fn decode(bytes: &[u8]) -> serde_json::Result { + let mut value: serde_json::Value = serde_json::from_slice(bytes)?; + if let Some(lists) = value.get_mut("lists").and_then(serde_json::Value::as_array_mut) { + for list in lists.iter_mut().filter_map(serde_json::Value::as_object_mut) { + if let Some(source) = list.remove("cherryPick") { + list.entry("appliedCommit").or_insert(source); + } + } + } + serde_json::from_value(value) +} + pub fn save(file: &Path, state: &ChangelistState) -> IdeResult<()> { if let Some(dir) = file.parent() { std::fs::create_dir_all(dir)?; @@ -93,7 +110,12 @@ mod tests { assert_eq!(load(&file).lists[0].name, "Changes"); let mut st = ChangelistState::initial(); - st.lists.push(Changelist { id: "f".into(), name: "Feature".into(), comment: String::new() }); + st.lists.push(Changelist { + id: "f".into(), + name: "Feature".into(), + comment: String::new(), + applied_commit: None, + }); st.active = "f".into(); st.files.insert("src/a.rs".into(), "f".into()); st.files.insert("b.rs".into(), "missing".into()); @@ -116,4 +138,33 @@ mod tests { assert_eq!(text.matches("/shelf/").count(), 1); assert!(text.contains("/changelists.json\n")); } + + #[test] + fn restores_earlier_cherry_pick_lists() { + let state = decode( + br#"{ + "lists": [{ + "id": "pick", + "name": "Incoming change", + "cherryPick": { + "repo": "/repo", + "commit": "source", + "base": "head", + "author": "Author ", + "authorDate": "2022-06-04T13:20:21+05:30" + } + }], + "active": "pick", + "files": {"a.txt": "pick"} + }"#, + ) + .unwrap(); + let list = &state.lists[0]; + let source = list.applied_commit.as_ref().unwrap(); + assert_eq!(source.kind, crate::CommitApplyKind::CherryPick); + assert_eq!(source.author_date.as_deref(), Some("2022-06-04T13:20:21+05:30")); + let saved = serde_json::to_value(list).unwrap(); + assert_eq!(saved["appliedCommit"]["kind"], "cherry-pick"); + assert_eq!(saved["appliedCommit"]["author"], "Author "); + } } diff --git a/crates/ide-vcs/src/cherry_pick_plan.rs b/crates/ide-vcs/src/cherry_pick_plan.rs new file mode 100644 index 000000000..e3ccea326 --- /dev/null +++ b/crates/ide-vcs/src/cherry_pick_plan.rs @@ -0,0 +1,160 @@ +//! Git's -x applies to the whole invocation. For mixed batches, resume the +//! queued commits after Git finishes the single pick that needed resolution. + +use crate::{ApplyCommitOptions, Repo, cli, ops}; +use ide_core::workflow_settings::EmptyCherryPickAction; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use serde::{Deserialize, Serialize}; +use std::collections::HashSet; +use std::fs; +use std::time::SystemTime; + +const PLAN: &str = "openidea-cherry-pick.json"; + +#[derive(Clone, Copy, Default)] +pub struct CherryPickOptions<'a> { + pub record_origin: bool, + pub record_origin_for: &'a [String], + pub empty_action: EmptyCherryPickAction, +} + +#[derive(Clone, Serialize, Deserialize)] +struct Pick { + commit: String, + record_origin: bool, +} + +#[derive(PartialEq, Eq, Serialize, Deserialize)] +struct Pause { + commit: String, + head: (Option, Option), + modified: SystemTime, +} + +#[derive(Serialize, Deserialize)] +struct Pending { + pause: Pause, + remaining: Vec, +} + +pub(crate) fn start( + repo: &Repo, + commits: &[String], + options: CherryPickOptions<'_>, + cancel: &CancellationToken, + out: &dyn Fn(String), +) -> IdeResult { + let ids = ops::checked_apply_commits(repo, commits, "cherry-pick")?; + let action = options.empty_action; + if options.record_origin_for.is_empty() { + return ops::apply_cherry_pick(repo, &ids, options.record_origin, action, cancel, out); + } + let selected: HashSet<_> = commits.iter().collect(); + let origins: HashSet<_> = options.record_origin_for.iter().collect(); + if !origins.is_subset(&selected) { + return Err(IdeError::invalid("Cherry-pick origins must be among the selected commits")); + } + if selected.len() == origins.len() { + return ops::apply_cherry_pick(repo, &ids, true, action, cancel, out); + } + let picks: Vec<_> = commits + .iter() + .zip(ids) + .map(|(original, commit)| Pick { commit, record_origin: origins.contains(original) }) + .collect(); + apply(repo, &picks, action, cancel, out) +} + +pub(crate) fn resume( + repo: &Repo, + args: &[&str], + edited: Option<(&str, &ApplyCommitOptions)>, + action: EmptyCherryPickAction, + cancel: &CancellationToken, + out: &dyn Fn(String), +) -> IdeResult { + let picking = args.first() == Some(&"cherry-pick"); + let pending = picking.then(|| load(repo)).flatten(); + let mut run_sequence = true; + if let Some((message, options)) = edited { + // Capture the pending plan first: committing removes CHERRY_PICK_HEAD. + ops::commit_apply_message(repo, message, options, cancel, out)?; + run_sequence = repo.git_dir.join("sequencer/todo").is_file(); + } + let empty = if !run_sequence { + 0 + } else if picking { + ops::apply_resolving_empty(repo, "cherry-pick", args, action, cancel, out)? + } else { + cli::run_streaming(repo.root(), args, cancel, out)?; + 0 + }; + match pending { + Some(pending) => apply(repo, &pending.remaining, action, cancel, out).map(|rest| empty + rest), + None => Ok(empty), + } +} + +fn apply( + repo: &Repo, + picks: &[Pick], + action: EmptyCherryPickAction, + cancel: &CancellationToken, + out: &dyn Fn(String), +) -> IdeResult { + if repo.operation()?.is_some() { + return Err(IdeError::invalid("Another Git operation is in progress.")); + } + clear(repo); + let mut empty = 0; + for (index, pick) in picks.iter().enumerate() { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let head = repo.head()?; + match ops::apply_cherry_pick(repo, std::slice::from_ref(&pick.commit), pick.record_origin, action, cancel, out) + { + Ok(count) => empty += count, + Err(error) => { + let remaining = &picks[index + 1..]; + if !remaining.is_empty() + && let Some(pause) = current_pause(repo) + && pause.commit == pick.commit + && pause.head == head + { + save(repo, pause, remaining)?; + } + return Err(error); + } + } + } + Ok(empty) +} + +fn current_pause(repo: &Repo) -> Option { + let path = repo.git_dir.join("CHERRY_PICK_HEAD"); + let modified = fs::metadata(&path).ok()?.modified().ok()?; + let commit = fs::read_to_string(&path).ok()?.trim().to_owned(); + Some(Pause { commit, head: repo.head().ok()?, modified }) +} + +fn load(repo: &Repo) -> Option { + let pending: Pending = serde_json::from_slice(&fs::read(repo.git_dir.join(PLAN)).ok()?).ok()?; + // The same commit can be cherry-picked later outside the IDE. Its Git + // checkpoint must match before any previously queued picks are replayed. + (current_pause(repo)? == pending.pause + && pending.remaining.iter().all(|pick| gix::ObjectId::from_hex(pick.commit.as_bytes()).is_ok())) + .then_some(pending) +} + +fn save(repo: &Repo, pause: Pause, remaining: &[Pick]) -> IdeResult<()> { + let mut file = tempfile::NamedTempFile::new_in(&repo.git_dir)?; + serde_json::to_writer(&mut file, &(Pending { pause, remaining: remaining.to_vec() })) + .map_err(|err| IdeError::internal(err.to_string()))?; + file.persist(repo.git_dir.join(PLAN)).map_err(|err| err.error)?; + Ok(()) +} + +pub(crate) fn clear(repo: &Repo) { + let _ = fs::remove_file(repo.git_dir.join(PLAN)); +} diff --git a/crates/ide-vcs/src/cli.rs b/crates/ide-vcs/src/cli.rs index b7fa6d406..d14fe2d7e 100644 --- a/crates/ide-vcs/src/cli.rs +++ b/crates/ide-vcs/src/cli.rs @@ -6,6 +6,7 @@ use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::OnceLock; +use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::mpsc; use std::time::{Duration, Instant}; @@ -13,6 +14,32 @@ use std::time::{Duration, Instant}; /// to exit on `SIGTERM` before `SIGKILL`: git removes its `index.lock` on `SIGTERM`. const KILL_GRACE: Duration = Duration::from_millis(20); +/// A throwaway index file in the repository's Git directory. +pub(crate) struct TempIndex(PathBuf); + +impl TempIndex { + pub(crate) fn new(repo: &crate::Repo) -> Self { + static SEQ: AtomicU32 = AtomicU32::new(0); + let n = SEQ.fetch_add(1, Ordering::Relaxed); + Self(repo.git_dir.join(format!("openidea-index-{}-{n}", std::process::id()))) + } + + pub(crate) fn env(&self) -> [(&'static str, &std::ffi::OsStr); 1] { + [("GIT_INDEX_FILE", self.0.as_os_str())] + } + + pub(crate) fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempIndex { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + let _ = std::fs::remove_file(self.0.with_extension("lock")); + } +} + /// Git executable of the user's global settings (`None` = auto-detect). Never a project's: a /// project's repositories carry their own ([`crate::Repo::set_git_executable`]). static DEFAULT: std::sync::RwLock> = std::sync::RwLock::new(None); @@ -275,6 +302,7 @@ pub(crate) fn command(root: &Path) -> IdeResult { .env("GIT_PAGER", "cat") .env("GIT_EDITOR", "true") .env("GIT_SEQUENCE_EDITOR", "true") + .env_remove(ide_core::process::ASKPASS_SILENT_ENV) .env_remove("GIT_DIR") .env_remove("GIT_WORK_TREE") .env_remove("GIT_INDEX_FILE"); @@ -478,7 +506,7 @@ fn run_cancellable_raw_stdin( stdin: Option<&[u8]>, cancel: &CancellationToken, ) -> IdeResult { - run_capture(root, args, stdin, cancel, usize::MAX) + run_capture(root, args, stdin, cancel, usize::MAX, Credentials::Interactive, &[]) } /// Options for a `git diff` that reads the working tree in Restricted Mode: git asks a submodule @@ -522,29 +550,99 @@ pub fn filter_overrides_from(config: &[u8]) -> IdeResult> { /// Cancellable capture with bounded stdout and stderr; stops git on overflow. pub(crate) fn run_bounded(root: &Path, args: &[&str], cancel: &CancellationToken, max: usize) -> IdeResult { - let out = run_capture(root, args, None, cancel, max)?; + run_bounded_env(root, args, cancel, max, &[]) +} + +pub(crate) fn run_bounded_env( + root: &Path, + args: &[&str], + cancel: &CancellationToken, + max: usize, + env: &[(&str, &std::ffi::OsStr)], +) -> IdeResult { + let out = run_capture(root, args, None, cancel, max, Credentials::Interactive, env)?; if out.code == Some(0) { Ok(out) } else { Err(failure(args, &out.stderr, &out.stdout, out.code)) } } +/// Quiet transport that may still obtain credentials from the IDE's saved store. +pub(crate) fn run_with_saved_credentials(root: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult { + let out = run_with_saved_credentials_raw(root, args, cancel)?; + if out.code == Some(0) { Ok(out) } else { Err(failure(args, &out.stderr, &out.stdout, out.code)) } +} + +pub(crate) fn run_with_saved_credentials_raw( + root: &Path, + args: &[&str], + cancel: &CancellationToken, +) -> IdeResult { + run_capture(root, args, None, cancel, 1 << 20, Credentials::Saved, &[]) +} + +fn suppress_credential_prompts(cmd: &mut Command) { + cmd.env("GCM_INTERACTIVE", "never"); + let ide_askpass = cmd.get_envs().any(|(key, value)| key == ide_core::process::ASKPASS_PORT_ENV && value.is_some()); + if ide_askpass { + cmd.env(ide_core::process::ASKPASS_SILENT_ENV, "1"); + } else { + cmd.args(["-c", "credential.interactive=false"]) + .env("GIT_ASKPASS", no_program()) + .env("SSH_ASKPASS", no_program()) + .env("SSH_ASKPASS_REQUIRE", "never"); + } +} + +enum Credentials { + Interactive, + Saved, +} + fn run_capture( root: &Path, args: &[&str], stdin: Option<&[u8]>, cancel: &CancellationToken, max: usize, + credentials: Credentials, + env: &[(&str, &std::ffi::OsStr)], +) -> IdeResult { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let mut cmd = command(root)?; + match credentials { + Credentials::Interactive => {} + Credentials::Saved => suppress_credential_prompts(&mut cmd), + } + cmd.args(args).envs(env.iter().copied()); + let refresh = IndexRefresh::before(root, args, env); + let mut session = CommandSession::start(&mut cmd); + let out = capture_command(cmd, stdin, cancel, max, "git")?; + session.finish(out.code == Some(0), &String::from_utf8_lossy(&out.stderr)); + refresh.after(); + Ok(out) +} + +pub(crate) fn capture_command( + mut cmd: Command, + stdin: Option<&[u8]>, + cancel: &CancellationToken, + max: usize, + program: &str, ) -> IdeResult { if cancel.is_cancelled() { return Err(IdeError::cancelled()); } let overflow = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let mut cmd = command(root)?; - cmd.args(args) - .stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() }) + own_group(&mut cmd); + cmd.stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() }) .stdout(Stdio::piped()) .stderr(Stdio::piped()); - own_group(&mut cmd); - let refresh = IndexRefresh::before(root, args, &[]); - let mut session = CommandSession::start(&mut cmd); - let mut child = cmd.spawn().map_err(spawn_error)?; + let mut child = cmd.spawn().map_err(|error| { + if error.kind() == std::io::ErrorKind::NotFound { + IdeError::unavailable(format!("could not run {program}: {error}")) + } else { + error.into() + } + })?; let writer = match (stdin, child.stdin.take()) { (Some(data), Some(mut pipe)) => { let data = data.to_vec(); @@ -580,7 +678,7 @@ fn run_capture( return Err(if cancel.is_cancelled() { IdeError::cancelled() } else { - IdeError::invalid(format!("git output exceeds {max} bytes")) + IdeError::invalid(format!("{program} output exceeds {max} bytes")) }); } if let Some(status) = child.try_wait()? { @@ -592,13 +690,14 @@ fn run_capture( let _ = w.join(); } let join = |thread: std::thread::JoinHandle>>| { - thread.join().map_err(|_| IdeError::internal("git output reader panicked"))?.map_err(IdeError::from) + thread + .join() + .map_err(|_| IdeError::internal(format!("{program} output reader panicked")))? + .map_err(IdeError::from) }; let out = Output { stdout: join(stdout)?, stderr: join(stderr)?, code: status.code() }; - session.finish(status.success(), &String::from_utf8_lossy(&out.stderr)); - refresh.after(); if out.stdout.len() > max || out.stderr.len() > max { - return Err(IdeError::invalid(format!("git output exceeds {max} bytes"))); + return Err(IdeError::invalid(format!("{program} output exceeds {max} bytes"))); } Ok(out) } @@ -694,6 +793,29 @@ pub(crate) fn run_streaming( run_streaming_env(root, args, &[], cancel, on_output) } +/// Also feeds machine-readable stdout to the caller, separately from progress and stderr. +pub(crate) fn run_streaming_stdout( + root: &Path, + args: &[&str], + cancel: &CancellationToken, + on_output: &dyn Fn(String), + stdout: &mut dyn FnMut(&str), +) -> IdeResult<()> { + run_streaming_command(root, args, &[], &|| cancel.is_cancelled(), on_output, (Stream::Stdout, stdout), false) +} + +/// Also feeds Git's ref status lines on stderr to the caller. +pub(crate) fn run_streaming_stderr( + root: &Path, + args: &[&str], + cancel: &CancellationToken, + on_output: &dyn Fn(String), + stderr: &mut dyn FnMut(&str), + silent: bool, +) -> IdeResult<()> { + run_streaming_command(root, args, &[], &|| cancel.is_cancelled(), on_output, (Stream::Stderr, stderr), silent) +} + /// [`run_streaming`] with extra environment variables (e.g. a sequence editor). pub(crate) fn run_streaming_env( root: &Path, @@ -702,13 +824,39 @@ pub(crate) fn run_streaming_env( cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - if cancel.is_cancelled() { + run_streaming_env_until(root, args, env, &|| cancel.is_cancelled(), on_output) +} + +/// Like `run_streaming_env`, with a predicate for sessions that can stop cooperatively. +pub(crate) fn run_streaming_env_until( + root: &Path, + args: &[&str], + env: &[(&str, &std::ffi::OsStr)], + should_cancel: &dyn Fn() -> bool, + on_output: &dyn Fn(String), +) -> IdeResult<()> { + run_streaming_command(root, args, env, should_cancel, on_output, (Stream::Stdout, &mut |_| {}), false) +} + +fn run_streaming_command( + root: &Path, + args: &[&str], + env: &[(&str, &std::ffi::OsStr)], + should_cancel: &dyn Fn() -> bool, + on_output: &dyn Fn(String), + (capture_stream, capture): (Stream, &mut dyn FnMut(&str)), + silent: bool, +) -> IdeResult<()> { + if should_cancel() { return Err(IdeError::cancelled()); } let mut cmd = command(root)?; for (k, v) in env { cmd.env(k, v); } + if silent { + suppress_credential_prompts(&mut cmd); + } cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); own_group(&mut cmd); tracing::debug!(?args, "git (streaming)"); @@ -725,12 +873,12 @@ pub(crate) fn run_streaming_env( } drop(tx); - // Keep the tail of stderr (and stdout conflict reports) for the error message. + // Keep the tail of stderr and machine-readable failures from stdout. let mut stderr_tail: Vec = Vec::new(); - let mut conflicts: Vec = Vec::new(); + let mut diagnostics: Vec = Vec::new(); let mut open = readers.len(); while open > 0 { - if cancel.is_cancelled() { + if should_cancel() { terminate_tree(&mut child, KILL_GRACE); for r in readers { let _ = r.join(); @@ -739,13 +887,18 @@ pub(crate) fn run_streaming_env( } match rx.recv_timeout(Duration::from_millis(40)) { Ok(Event::Line(stream, line)) => { + if stream == capture_stream { + capture(&line); + } if stream == Stream::Stderr { stderr_tail.push(line.clone()); if stderr_tail.len() > 40 { stderr_tail.remove(0); } - } else if line.starts_with("CONFLICT") && conflicts.len() < 40 { - conflicts.push(line.clone()); + } else if (line.starts_with("CONFLICT") || (args.first() == Some(&"push") && line.starts_with("!\t"))) + && diagnostics.len() < 40 + { + diagnostics.push(line.clone()); } on_output(line); } @@ -759,7 +912,7 @@ pub(crate) fn run_streaming_env( if let Some(status) = child.try_wait()? { break status; } - if cancel.is_cancelled() { + if should_cancel() { terminate_tree(&mut child, KILL_GRACE); return Err(IdeError::cancelled()); } @@ -773,7 +926,7 @@ pub(crate) fn run_streaming_env( return Ok(()); } let relevant: Vec<&str> = - conflicts.iter().chain(stderr_tail.iter()).map(String::as_str).filter(|l| !is_progress_line(l)).collect(); + diagnostics.iter().chain(stderr_tail.iter()).map(String::as_str).filter(|l| !is_progress_line(l)).collect(); let msg = relevant.join("\n"); session.finish(false, &stderr_tail.join("\n")); Err(failure(args, msg.as_bytes(), b"", status.code())) diff --git a/crates/ide-vcs/src/commit_message.rs b/crates/ide-vcs/src/commit_message.rs new file mode 100644 index 000000000..44db15e49 --- /dev/null +++ b/crates/ide-vcs/src/commit_message.rs @@ -0,0 +1,650 @@ +use crate::{Repo, cherry_pick_plan, cli, ops}; +use ide_core::workflow_settings::EmptyCherryPickAction; +use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath}; +use notify::event::{MetadataKind, ModifyKind}; +use notify::{RecommendedWatcher, RecursiveMode, Watcher}; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::collections::BTreeSet; +use std::fs::File; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +const MESSAGE_LIMIT: usize = 1 << 20; +const PREPARED_MESSAGE_FILES: [&str; 2] = ["SQUASH_MSG", "MERGE_MSG"]; +const APPLY_HEADS: [(CommitApplyKind, &str); 2] = + [(CommitApplyKind::CherryPick, "CHERRY_PICK_HEAD"), (CommitApplyKind::Revert, "REVERT_HEAD")]; + +fn apply_changed() -> IdeError { + IdeError::invalid("The Git operation changed. Review the current changes and try again.") +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct CommitMessages { + pub template: Option, + pub prepared: Option, + #[serde(default)] + pub pending_apply: Option, +} + +#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize, Type)] +#[serde(rename_all = "kebab-case")] +pub enum CommitApplyKind { + #[default] + CherryPick, + Revert, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct CommitApplySource { + #[serde(default)] + pub kind: CommitApplyKind, + pub repo: IpcPath, + pub commit: String, + pub base: String, + pub author: Option, + pub author_date: Option, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, Type)] +pub struct PendingCommitApply { + pub source: CommitApplySource, + pub paths: Vec, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ApplyCommitReview { + pub kind: CommitApplyKind, + pub checkpoint: String, + pub message: String, + pub paths: Vec, + #[serde(default)] + pub author: Option, + #[serde(default)] + pub author_date: Option, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, Type)] +#[serde(default, rename_all = "camelCase")] +pub struct ApplyCommitOptions { + pub author: Option, + pub author_date: Option, + pub sign_off: bool, + pub run_hooks: bool, +} + +impl Default for ApplyCommitOptions { + fn default() -> Self { + Self { author: None, author_date: None, sign_off: false, run_hooks: true } + } +} + +/// Watches Git-prepared messages and the effective template, including files outside the worktree. +pub struct CommitMessageWatch { + watcher: RecommendedWatcher, + base_files: BTreeSet, + files: Arc>>, + dirs: BTreeSet, +} + +impl CommitMessageWatch { + fn new(base_files: BTreeSet, changed: impl Fn() + Send + 'static) -> IdeResult { + let files = Arc::new(Mutex::new(BTreeSet::::new())); + let watched = files.clone(); + let watcher = notify::recommended_watcher(move |event: notify::Result| { + if let Ok(event) = event + && (event.need_rescan() + || (!event.kind.is_access() + && event.kind != notify::EventKind::Modify(ModifyKind::Metadata(MetadataKind::AccessTime)) + && event.paths.iter().any(|p| { + watched.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|f| f.starts_with(p)) + }))) + { + changed(); + } + }) + .map_err(|e| IdeError::internal(format!("Git commit message watcher: {e}")))?; + let mut watch = Self { watcher, base_files, files, dirs: BTreeSet::new() }; + watch.replace_files(BTreeSet::new()); + Ok(watch) + } + + fn replace_files(&mut self, paths: BTreeSet) -> bool { + let mut files = BTreeSet::new(); + let mut dirs = BTreeSet::new(); + for path in self.base_files.iter().chain(&paths) { + // Track both a symlink's name and the file it resolves to. Watching the nearest + // existing directory also catches a missing template or config appearing later. + for file in [watch_path(path), dunce::canonicalize(path).ok()].into_iter().flatten() { + if let Some(dir) = file.ancestors().skip(1).find(|dir| dir.is_dir()) { + dirs.insert(dir.to_path_buf()); + files.insert(file); + } + } + } + let changed = { + let mut watched = self.files.lock().unwrap_or_else(|e| e.into_inner()); + let changed = *watched != files || self.dirs != dirs; + *watched = files; + changed + }; + for dir in self.dirs.difference(&dirs) { + let _ = self.watcher.unwatch(dir); + } + dirs.retain(|dir| { + self.dirs.contains(dir) + || self + .watcher + .watch(dir, RecursiveMode::NonRecursive) + .map_err(|e| { + tracing::debug!("Git commit message watcher {}: {e}", dir.display()); + }) + .is_ok() + }); + self.dirs = dirs; + changed + } +} + +fn watch_path(path: &Path) -> Option { + let parent = path.parent()?.ancestors().find(|p| p.is_dir())?; + Some(dunce::canonicalize(parent).ok()?.join(path.strip_prefix(parent).ok()?)) +} + +#[derive(Default)] +struct MessageConfig { + configured: bool, + encoding: Option, + comment: Option, + files: BTreeSet, +} + +impl MessageConfig { + fn parse(root: &Path, bytes: &[u8]) -> Self { + let mut config = Self::default(); + let mut fields = bytes.split(|byte| *byte == 0); + while let (Some(origin), Some(entry)) = (fields.next(), fields.next()) { + let source = origin.strip_prefix(b"file:").map(|path| root.join(String::from_utf8_lossy(path).as_ref())); + config.files.extend(source.iter().cloned()); + let entry = String::from_utf8_lossy(entry); + let (key, value) = entry.split_once('\n').unwrap_or((&entry, "")); + match key { + "commit.template" => config.configured = !value.is_empty(), + "i18n.commitencoding" => config.encoding = Some(value.to_owned()), + "core.commentchar" | "core.commentstring" => config.comment = Some(value.to_owned()), + key if key == "include.path" || (key.starts_with("includeif.") && key.ends_with(".path")) => { + // Git only reports origins that produced entries. Keep watching an include + // even when its file is empty or has yet to be created. + if let Some(path) = include_path(source.as_deref(), value) { + config.files.insert(path); + } + } + _ => {} + } + } + config + } +} + +fn include_path(source: Option<&Path>, value: &str) -> Option { + if value.is_empty() { + return None; + } + if let Some(relative) = value.strip_prefix("~/") { + return Some(gix::path::env::home_dir()?.join(relative)); + } + let path = Path::new(value); + if path.is_absolute() { + return Some(path.to_path_buf()); + } + Some(source?.parent()?.join(path)) +} + +impl Repo { + pub fn watch_commit_messages( + &self, + cancel: &CancellationToken, + changed: impl Fn() + Send + 'static, + ) -> IdeResult { + let _scope = self.execution_scope(); + let [git_dir, common_dir] = self.metadata_dirs()?; + let mut files = + BTreeSet::from([git_dir.join("HEAD"), git_dir.join("config.worktree"), common_dir.join("config")]); + files.extend(PREPARED_MESSAGE_FILES.map(|name| git_dir.join(name))); + files.extend(APPLY_HEADS.map(|(_, name)| git_dir.join(name))); + for variable in ["GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM"] { + if let Ok(out) = cli::run_bounded(self.root(), &["var", variable], cancel, 65536) { + files.extend(out.stdout_str().lines().filter(|line| !line.is_empty()).map(PathBuf::from)); + } + } + CommitMessageWatch::new(files, changed) + } + + pub fn commit_messages( + &self, + watch: &mut CommitMessageWatch, + cancel: &CancellationToken, + ) -> IdeResult { + // Read again after installing newly discovered watches. This closes the gap between + // reading the configuration and observing changes to a newly configured template. + let (mut config, mut path) = self.commit_message_config(cancel)?; + if set_template_paths(watch, &config, path.as_deref()) { + (config, path) = self.commit_message_config(cancel)?; + set_template_paths(watch, &config, path.as_deref()); + } + let template = path.and_then(|path| read_message(&path, &config, false)); + let prepared = PREPARED_MESSAGE_FILES + .iter() + .filter_map(|file| read_message(&self.git_dir.join(file), &config, true)) + .collect::>(); + let prepared = (!prepared.is_empty()).then(|| prepared.join("\n\n")); + let pending_apply = prepared.as_ref().and_then(|_| self.pending_apply(cancel)); + Ok(CommitMessages { template, prepared, pending_apply }) + } + + fn pending_apply(&self, cancel: &CancellationToken) -> Option { + let _scope = self.execution_scope(); + let (kind, marker, revision) = self.apply_head()?; + let commit = gix::ObjectId::from_hex(revision.as_bytes()).ok()?.to_string(); + let (_, base) = self.head().ok()?; + let base = base?; + let (author, author_date) = self.apply_author(kind, &commit, cancel); + let index = cli::run_bounded( + self.root(), + &["diff", "--cached", "--name-only", "-z", "--no-renames", "--no-ext-diff", "--no-relative", &base, "--"], + cancel, + 4 << 20, + ) + .ok()?; + // Git starts these operations with a clean index. The cached paths include both + // applied and unmerged changes, leaving pre-existing unstaged changes alone. + let paths = index + .stdout + .split(|byte| *byte == 0) + .filter(|path| !path.is_empty()) + .map(|path| IpcPath(self.root().join(String::from_utf8_lossy(path).as_ref()))) + .collect(); + if read_message(&marker, &MessageConfig::default(), false).as_deref() != Some(&revision) + || self.head().ok()?.1.as_deref() != Some(&base) + { + return None; + } + Some(PendingCommitApply { + source: CommitApplySource { + kind, + repo: IpcPath(self.root().to_path_buf()), + commit, + base, + author, + author_date, + }, + paths, + }) + } + + fn apply_head(&self) -> Option<(CommitApplyKind, PathBuf, String)> { + APPLY_HEADS.into_iter().find_map(|(kind, name)| { + let marker = self.git_dir.join(name); + let revision = read_message(&marker, &MessageConfig::default(), false)?; + Some((kind, marker, revision)) + }) + } + + /// The staged changes Git would commit after a cherry-pick or revert stopped. + pub fn review_apply_commit(&self, cancel: &CancellationToken) -> IdeResult> { + let _scope = self.execution_scope(); + self.review_apply_index(cancel, &[]) + } + + pub(crate) fn review_apply_index( + &self, + cancel: &CancellationToken, + env: &[(&str, &std::ffi::OsStr)], + ) -> IdeResult> { + let Some((kind, marker, revision)) = self.apply_head() else { return Ok(None) }; + let (branch, head) = self.head()?; + let head = head.ok_or_else(|| IdeError::invalid("Git operation has no current commit"))?; + let modified = marker.metadata()?.modified()?; + let raw = cli::run_bounded_env( + self.root(), + &[ + "diff", + "--cached", + "--raw", + "-z", + "--no-abbrev", + "--no-renames", + "--no-ext-diff", + "--no-relative", + "--ignore-submodules=none", + &head, + "--", + ], + cancel, + 16 << 20, + env, + )?; + let mut paths = Vec::new(); + let mut fields = raw.stdout.split(|&b| b == 0).filter(|field| !field.is_empty()); + while let (Some(change), Some(path)) = (fields.next(), fields.next()) { + if change.ends_with(b" U") { + return Err(IdeError::invalid("Resolve all conflicts before continuing")); + } + paths.push(IpcPath(self.root().join(String::from_utf8_lossy(path).as_ref()))); + } + if paths.is_empty() { + return Ok(None); + } + let (config, _) = self.commit_message_config(cancel)?; + let message = read_message(&self.git_dir.join("MERGE_MSG"), &config, true).unwrap_or_default(); + if self.apply_head().as_ref() != Some(&(kind, marker.clone(), revision.clone())) + || marker.metadata()?.modified()? != modified + || self.head()? != (branch.clone(), Some(head.clone())) + { + return Err(apply_changed()); + } + let mut digest = blake3::Hasher::new(); + digest.update(format!("{kind:?}\0{revision}\0{branch:?}\0{head}\0{modified:?}\0{message}\0").as_bytes()); + digest.update(&raw.stdout); + let (author, author_date) = self.apply_author(kind, &revision, cancel); + Ok(Some(ApplyCommitReview { + kind, + checkpoint: digest.finalize().to_hex().to_string(), + message, + paths, + author, + author_date, + })) + } + + pub fn continue_reviewed_apply( + &self, + checkpoint: &str, + message: &str, + options: &ApplyCommitOptions, + empty_action: EmptyCherryPickAction, + cancel: &CancellationToken, + out: &dyn Fn(String), + ) -> IdeResult { + let _scope = self.execution_scope(); + if message.trim().is_empty() || message.contains('\0') || message.len() > MESSAGE_LIMIT { + return Err(IdeError::invalid("Invalid commit message")); + } + ops::continue_op(self, false, |args| { + let review = self.require_apply_review(checkpoint, cancel)?; + let edited = + (message != review.message || *options != ApplyCommitOptions::default()).then_some((message, options)); + cherry_pick_plan::resume(self, args, edited, empty_action, cancel, out) + }) + } + + pub(crate) fn require_apply_review( + &self, + checkpoint: &str, + cancel: &CancellationToken, + ) -> IdeResult { + self.review_apply_index(cancel, &[])?.filter(|review| review.checkpoint == checkpoint).ok_or_else(apply_changed) + } + + fn apply_author( + &self, + kind: CommitApplyKind, + commit: &str, + cancel: &CancellationToken, + ) -> (Option, Option) { + if kind == CommitApplyKind::CherryPick + && gix::ObjectId::from_hex(commit.as_bytes()).is_ok() + && let Some((author, date)) = self.commit_author(commit, cancel) + { + return (Some(author), Some(date)); + } + (None, None) + } + + fn commit_author(&self, commit: &str, cancel: &CancellationToken) -> Option<(String, String)> { + let raw = cli::run_bounded( + self.root(), + &["show", "-s", "--no-show-signature", "--format=%an%x00%ae%x00%aI", commit, "--"], + cancel, + 64 << 10, + ) + .ok()?; + let text = raw.stdout_str(); + let mut fields = text.trim_end().split('\0'); + let author = format!("{} <{}>", fields.next()?, fields.next()?); + Some((author, fields.next()?.to_owned())) + } + + fn commit_message_config(&self, cancel: &CancellationToken) -> IdeResult<(MessageConfig, Option)> { + let _scope = self.execution_scope(); + let raw = cli::run_bounded( + self.root(), + &["config", "--includes", "--show-origin", "--null", "--list"], + cancel, + 4 << 20, + )?; + let config = MessageConfig::parse(self.root(), &raw.stdout); + let path = if config.configured { + let raw = cli::run_bounded( + self.root(), + &["config", "--type=path", "--null", "--get", "commit.template"], + cancel, + 65536, + )?; + let value = raw.stdout.strip_suffix(&[0]).unwrap_or(&raw.stdout); + let path = String::from_utf8_lossy(value); + (!path.is_empty() && !path.ends_with('/')).then(|| self.root().join(path.as_ref())) + } else { + None + }; + Ok((config, path)) + } +} + +fn set_template_paths(watch: &mut CommitMessageWatch, config: &MessageConfig, path: Option<&Path>) -> bool { + let mut files = config.files.clone(); + files.extend(path.map(Path::to_path_buf)); + watch.replace_files(files) +} + +fn read_message(path: &Path, config: &MessageConfig, prepared: bool) -> Option { + let mut options = File::options(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NONBLOCK); + } + let file = options.open(path).ok()?; + let metadata = file.metadata().ok()?; + if !metadata.is_file() || metadata.len() > MESSAGE_LIMIT as u64 { + return None; + } + let mut bytes = Vec::new(); + file.take(MESSAGE_LIMIT as u64 + 1).read_to_end(&mut bytes).ok()?; + if bytes.len() > MESSAGE_LIMIT { + return None; + } + let encoding = config + .encoding + .as_deref() + .and_then(|label| encoding_rs::Encoding::for_label(label.as_bytes())) + .unwrap_or(encoding_rs::UTF_8); + let (text, _, _) = encoding.decode(&bytes); + let comment = config.comment.as_deref().filter(|prefix| !prefix.is_empty() && *prefix != "auto").unwrap_or("#"); + let message = text + .lines() + .filter(|line| !(line.starts_with(comment) || prepared && line.starts_with('\u{1}'))) + .collect::>() + .join("\n"); + let message = message.trim(); + (!message.is_empty()).then(|| message.to_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::process::Command; + use std::sync::mpsc; + use std::time::{Duration, Instant}; + + fn git(root: &Path, args: &[&str]) { + let output = Command::new("git").current_dir(root).args(args).output().unwrap(); + assert!(output.status.success(), "{args:?}: {}", String::from_utf8_lossy(&output.stderr)); + } + + fn conflicting_git(root: &Path, args: &[&str]) { + let output = Command::new("git").current_dir(root).args(args).output().unwrap(); + assert_eq!(output.status.code(), Some(1), "{args:?}: {}", String::from_utf8_lossy(&output.stderr)); + assert!(String::from_utf8_lossy(&output.stdout).contains("CONFLICT"), "{args:?} did not conflict"); + } + + #[test] + fn follows_an_included_config_and_a_template_outside_the_repository() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("repo"); + fs::create_dir(&root).unwrap(); + git(&root, &["init", "-q"]); + let include = tmp.path().join("template.gitconfig"); + let template = tmp.path().join("commit message.txt"); + let template_arg = template.to_str().unwrap(); + let include_arg = include.to_str().unwrap(); + git(&root, &["config", "--file", include_arg, "commit.template", template_arg]); + git(&root, &["config", "--file", include_arg, "i18n.commitEncoding", "windows-1252"]); + git(&root, &["config", "--file", include_arg, "core.commentChar", ";"]); + git(&root, &["config", "--add", "include.path", "../../template.gitconfig"]); + fs::write(&template, b"R\xe9sum\xe9\r\n; instructions\r\n# Keep this").unwrap(); + + let repo = Repo::discover(&root).unwrap().unwrap(); + let token = CancellationToken::new(); + let (tx, rx) = mpsc::channel(); + let mut watch = repo + .watch_commit_messages(&token, move || { + let _ = tx.send(()); + }) + .unwrap(); + let message = repo.commit_messages(&mut watch, &token).unwrap().template; + assert_eq!(message.as_deref(), Some("Résumé\n# Keep this")); + + let mut expect_update = |expected: Option<&str>| { + let deadline = Instant::now() + Duration::from_secs(8); + loop { + rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) + .expect("template watcher did not report the change"); + let message = repo.commit_messages(&mut watch, &token).unwrap().template; + if message.as_deref() == expected { + return; + } + } + }; + fs::write(&template, "Updated").unwrap(); + expect_update(Some("Updated")); + fs::remove_file(&template).unwrap(); + expect_update(None); + fs::write(&template, "Restored").unwrap(); + expect_update(Some("Restored")); + fs::write(root.join("local template"), "Local template").unwrap(); + git(&root, &["config", "--file", include_arg, "commit.template", "local template"]); + expect_update(Some("Local template")); + fs::write(&include, "").unwrap(); + expect_update(None); + git(&root, &["config", "--file", include_arg, "commit.template", "local template"]); + expect_update(Some("Local template")); + } + + #[test] + fn follows_prepared_messages_in_the_linked_git_directory() { + let tmp = tempfile::tempdir().unwrap(); + let main = tmp.path().join("main"); + let linked = tmp.path().join("linked"); + fs::create_dir(&main).unwrap(); + git(&main, &["init", "-q", "-b", "main"]); + for (key, value) in [ + ("user.name", "Fixture"), + ("user.email", "fixture@example.invalid"), + ("commit.gpgsign", "false"), + ("core.commentChar", ";"), + ("core.autocrlf", "false"), + ] { + git(&main, &["config", "--local", key, value]); + } + fs::write(main.join("notes.txt"), "base\n").unwrap(); + fs::write(main.join("local.txt"), "untouched\n").unwrap(); + git(&main, &["add", "notes.txt", "local.txt"]); + git(&main, &["commit", "-qm", "Base notes"]); + git(&main, &["switch", "-qc", "incoming"]); + fs::write(main.join("notes.txt"), "incoming\n").unwrap(); + git(&main, &["commit", "-qam", "Incoming notes"]); + git(&main, &["worktree", "add", "-qb", "workspace", linked.to_str().unwrap(), "main"]); + fs::write(linked.join("notes.txt"), "local\n").unwrap(); + git(&linked, &["commit", "-qam", "Local notes"]); + + let repo = Repo::discover(&linked).unwrap().unwrap(); + let [git_dir, common_dir] = repo.metadata_dirs().unwrap(); + assert_ne!(git_dir, common_dir); + let token = CancellationToken::new(); + let (tx, rx) = mpsc::channel(); + let mut watch = repo + .watch_commit_messages(&token, move || { + let _ = tx.send(()); + }) + .unwrap(); + assert_eq!(repo.commit_messages(&mut watch, &token).unwrap().prepared, None); + let mut expect_update = |subject: Option<&str>| { + let deadline = Instant::now() + Duration::from_secs(8); + loop { + rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) + .expect("prepared message watcher did not report the change"); + let message = repo.commit_messages(&mut watch, &token).unwrap().prepared; + if message.as_deref().and_then(|m| m.lines().next()) == subject { + return message; + } + } + }; + + conflicting_git(&linked, &["merge", "incoming"]); + let merge = expect_update(Some("Merge branch 'incoming' into workspace")).unwrap(); + assert!(!merge.contains("Conflicts:") && !merge.contains("notes.txt")); + fs::write(git_dir.join("MERGE_MSG"), "Message edited on disk\n; Conflicts:\n").unwrap(); + assert_eq!(expect_update(Some("Message edited on disk")).as_deref(), Some("Message edited on disk")); + git(&linked, &["merge", "--abort"]); + expect_update(None); + + fs::write(linked.join("local.txt"), "unrelated local edit\n").unwrap(); + conflicting_git(&linked, &["cherry-pick", "incoming"]); + expect_update(Some("Incoming notes")); + let mut read = repo.watch_commit_messages(&token, || {}).unwrap(); + let pending = repo.commit_messages(&mut read, &token).unwrap().pending_apply.unwrap(); + assert_eq!(pending.source.kind, CommitApplyKind::CherryPick); + assert_eq!(pending.source.author.as_deref(), Some("Fixture ")); + assert_eq!(pending.source.base, repo.head().unwrap().1.unwrap()); + assert_eq!(pending.paths, [IpcPath(repo.root().join("notes.txt"))]); + git(&linked, &["cherry-pick", "--abort"]); + expect_update(None); + assert!(repo.commit_messages(&mut read, &token).unwrap().pending_apply.is_none()); + + conflicting_git(&linked, &["revert", "--no-edit", "incoming"]); + expect_update(Some("Revert \"Incoming notes\"")); + let pending = repo.commit_messages(&mut read, &token).unwrap().pending_apply.unwrap(); + assert_eq!(pending.source.kind, CommitApplyKind::Revert); + assert_eq!(pending.source.author, None); + assert_eq!(pending.source.author_date, None); + assert_eq!(pending.paths, [IpcPath(repo.root().join("notes.txt"))]); + git(&linked, &["revert", "--abort"]); + expect_update(None); + assert!(repo.commit_messages(&mut read, &token).unwrap().pending_apply.is_none()); + + conflicting_git(&linked, &["merge", "--squash", "incoming"]); + let squash = expect_update(Some("Squashed commit of the following:")).unwrap(); + assert!(squash.contains("Incoming notes")); + fs::write(git_dir.join("MERGE_MSG"), "Extra context\n; Conflicts:\n").unwrap(); + assert!(expect_update(Some("Squashed commit of the following:")).is_some()); + let prepared = repo.commit_messages(&mut watch, &token).unwrap().prepared.unwrap(); + assert!(prepared.ends_with("\n\nExtra context")); + } +} diff --git a/crates/ide-vcs/src/commit_rewrite.rs b/crates/ide-vcs/src/commit_rewrite.rs new file mode 100644 index 000000000..aea13b8ca --- /dev/null +++ b/crates/ide-vcs/src/commit_rewrite.rs @@ -0,0 +1,569 @@ +//! Editing a commit and replaying its descendants. + +use crate::cli::{TempIndex, failure, run, run_env, run_raw}; +use crate::repo::{absolute, gx, resolve}; +use crate::{AmendTarget, CommitOptions, HeadChange, HistoryTip, Repo, RewrittenCommit, TextEncoding}; +use gix::bstr::ByteSlice; +use ide_core::error::ErrorData; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use std::collections::HashSet; +use std::ffi::OsStr; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; + +#[derive(Clone)] +struct History { + head: gix::ObjectId, + branch: Option, + commits: Vec, +} + +impl History { + fn load(repo: &Repo, target: &str, expected_head: Option<&HistoryTip>) -> IdeResult { + if repo.branch_info()?.operation.is_some() { + return Err(IdeError::invalid("cannot rewrite history while a Git operation is in progress")); + } + let objects = repo.gix()?; + let head = objects.head().map_err(gx)?; + let branch = head.referent_name().map(|name| name.as_bstr().to_string()); + let head = head.id().ok_or_else(|| IdeError::invalid("there is no commit to edit"))?.detach(); + if expected_head.is_some_and(|expected| { + let current_branch = branch.as_deref().and_then(|name| name.strip_prefix("refs/heads/")); + gix::ObjectId::from_hex(expected.commit.as_bytes()).ok() != Some(head) + || expected.branch.as_deref() != current_branch + }) { + return Err(IdeError::invalid("the branch has changed since the selection was made")); + } + let commit = objects.find_object(resolve(&objects, target)?).map_err(gx)?.peel_to_commit().map_err(gx)?; + if commit.parent_ids().count() > 1 { + return Err(IdeError::invalid("cannot rewrite a merge commit")); + } + let target = commit.id.to_string(); + if run_raw(repo.root(), &["merge-base", "--is-ancestor", &target, &head.to_string()], None)?.code != Some(0) { + return Err(IdeError::invalid("the commit is not in the current branch")); + } + let range = format!("{target}..{head}"); + let listed = run(repo.root(), &["rev-list", "--reverse", "--topo-order", "--parents", &range], None)?; + let mut commits = vec![target]; + for line in listed.stdout_str().lines() { + let ids: Vec<&str> = line.split_whitespace().collect(); + if ids.len() != 2 || ids[1] != commits.last().unwrap() { + return Err(IdeError::invalid("the commits after this one are not a linear history")); + } + commits.push(ids[0].to_string()); + } + Ok(Self { head, branch, commits }) + } + + fn ensure_current(&self, repo: &Repo) -> IdeResult<()> { + let objects = repo.gix()?; + let head = objects.head().map_err(gx)?; + if head.referent_name().map(|name| name.as_bstr().to_str_lossy()).as_deref() != self.branch.as_deref() + || head.id().is_none_or(|id| id.detach() != self.head) + || repo.branch_info()?.operation.is_some() + { + return Err(IdeError::invalid("the branch has changed since the selection was made")); + } + Ok(()) + } + + fn rewrite_descendants(self, repo: &Repo, mut parent: String, reason: &str) -> IdeResult { + for id in &self.commits[1..] { + let commit = Commit::read(repo, id)?; + parent = commit.write(repo, &commit.tree, Some(&parent), None)?; + } + self.ensure_current(repo)?; + let before = self.head.to_string(); + self.move_tip(repo, &before, &parent, reason)?; + Ok(HeadChange { before, after: parent }) + } + + fn move_tip(&self, repo: &Repo, from: &str, to: &str, reason: &str) -> IdeResult<()> { + run( + repo.root(), + &["update-ref", "--no-deref", "-m", reason, self.branch.as_deref().unwrap_or("HEAD"), to, from], + None, + )?; + Ok(()) + } + + fn publish_amend( + &self, + repo: &Repo, + index: Option<&[u8]>, + paths: &[u8], + commit: &str, + reason: &str, + ) -> IdeResult<()> { + let index_path = repo.gix()?.index_path(); + let updated = index_after_amend(repo, index, paths, commit)?; + let mut lock = + gix::lock::File::acquire_to_update_resource(&index_path, gix::lock::acquire::Fail::Immediately, None, 0) + .map_err(gx)?; + if read_index(&index_path)?.as_deref() != index { + return Err(IdeError::invalid("the index changed while the commit was being amended")); + } + if let Some(updated) = &updated { + lock.with_mut(|out| { + out.write_all(updated)?; + if let Ok(metadata) = fs::metadata(&index_path) { + out.set_permissions(metadata.permissions())?; + } + out.sync_all() + })?; + } + self.ensure_current(repo)?; + let before = self.head.to_string(); + self.move_tip(repo, &before, commit, reason)?; + if updated.is_some() + && let Err(error) = lock.commit() + { + self.move_tip(repo, commit, &before, "restore tip after amend index write failed")?; + return Err(gx(error)); + } + Ok(()) + } +} + +struct Commit { + tree: String, + parent: Option, + author: String, + encoding: Option, + data: Vec, + message_start: usize, +} + +impl Commit { + fn read(repo: &Repo, id: &str) -> IdeResult { + let data = run(repo.root(), &["cat-file", "commit", id], None)?.stdout; + let header_end = data.find(b"\n\n").ok_or_else(|| IdeError::invalid("invalid commit data"))?; + let headers = data[..header_end].to_str_lossy(); + let header = |prefix| headers.lines().find_map(|line| line.strip_prefix(prefix)).map(str::to_owned); + let tree = header("tree ").ok_or_else(|| IdeError::invalid("commit has no tree"))?; + let author = header("author ").ok_or_else(|| IdeError::invalid("commit has no author"))?; + Ok(Self { + tree, + parent: header("parent "), + author, + encoding: header("encoding "), + data, + message_start: header_end + 2, + }) + } + + fn write(&self, repo: &Repo, tree: &str, parent: Option<&str>, new_message: Option<&str>) -> IdeResult { + let (message, encoding) = + new_message.map_or_else(|| (self.message(), self.encoding()), |message| (message.as_bytes(), "UTF-8")); + Self::write_commit(repo, tree, parent, message, encoding, self.identity()) + } + + fn identity(&self) -> (&str, &str, &str) { + let (name, rest) = self.author.split_once(" <").unwrap_or((&self.author, "")); + let (email, date) = rest.split_once("> ").unwrap_or((rest, "")); + (name, email, date) + } + + fn write_commit( + repo: &Repo, + tree: &str, + parent: Option<&str>, + message: &[u8], + encoding: &str, + author: (&str, &str, &str), + ) -> IdeResult { + let (name, email, date) = author; + let env = [ + ("GIT_AUTHOR_NAME", OsStr::new(name)), + ("GIT_AUTHOR_EMAIL", OsStr::new(email)), + ("GIT_AUTHOR_DATE", OsStr::new(date)), + ]; + let encoding = format!("i18n.commitEncoding={encoding}"); + let mut args = vec!["-c", &encoding, "commit-tree", tree]; + if let Some(parent) = parent { + args.extend(["-p", parent]); + } + Ok(run_env(repo.root(), &args, Some(message), &env)?.stdout_str().trim().to_string()) + } + + fn message(&self) -> &[u8] { + &self.data[self.message_start..] + } + + fn encoding(&self) -> &str { + self.encoding.as_deref().unwrap_or("UTF-8") + } +} + +fn new_message(message: &str) -> IdeResult { + let message = message.trim(); + if message.is_empty() { + return Err(IdeError::invalid("commit message is empty")); + } + Ok(format!("{message}\n")) +} + +pub(crate) fn reword(repo: &Repo, id: &str, message: &str) -> IdeResult { + let message = new_message(message)?; + let history = History::load(repo, id, None)?; + let commit = Commit::read(repo, &history.commits[0])?; + let rewritten = commit.write(repo, &commit.tree, commit.parent.as_deref(), Some(&message))?; + let reason = format!("reword: {}", message.lines().next().unwrap_or_default()); + history.rewrite_descendants(repo, rewritten, &reason) +} + +/// Builds the selected commit in a detached Git directory, using the real +/// repository's config, hooks and objects. Only a successful replay changes HEAD. +pub(crate) fn amend( + repo: &Repo, + target: &AmendTarget, + message: &str, + commit_args: &[&str], + options: &CommitOptions, + encoding: &dyn Fn(&Path) -> IdeResult, +) -> IdeResult { + let history = History::load(repo, &target.commit, Some(&target.head))?; + if history.commits.len() < 2 { + return Err(IdeError::invalid("the commit to amend must be older than HEAD")); + } + let original = &history.commits[0]; + ensure_unpublished(repo, original, &target.protected_branches)?; + let commit = Commit::read(repo, original)?; + let before = history.head.to_string(); + let head = Commit::read(repo, &before)?; + let git = repo.gix()?; + let index_path = git.index_path(); + let index = read_index(&index_path)?; + let scratch = tempfile::tempdir_in(&repo.git_dir)?; + let chosen = TempIndex::new(repo); + if let Some(index) = &index { + fs::write(chosen.path(), index)?; + // Split indexes refer to objects in the original per-worktree Git directory. + run_env(repo.root(), &["update-index", "--no-split-index"], None, &chosen.env())?; + } + fs::write(scratch.path().join("HEAD"), format!("{before}\n"))?; + let worktree_config = repo.git_dir.join("config.worktree"); + if worktree_config.is_file() { + fs::copy(worktree_config, scratch.path().join("config.worktree"))?; + } + let common_dir = absolute(git.common_dir())?; + let env = [ + ("GIT_DIR", scratch.path().as_os_str()), + ("GIT_COMMON_DIR", common_dir.as_os_str()), + ("GIT_WORK_TREE", repo.root().as_os_str()), + ("GIT_INDEX_FILE", chosen.path().as_os_str()), + ]; + crate::write::fill_commit_index(repo, &env, options, encoding)?; + let message = if message.trim().is_empty() { commit.message() } else { message.as_bytes() }; + run_env(repo.root(), commit_args, Some(message), &env)?; + let selected = fs::read_to_string(scratch.path().join("HEAD"))?; + let selected = selected.trim(); + let addition = Commit::read(repo, selected)?; + + let (original_name, original_email, original_date) = commit.identity(); + let (new_name, new_email, new_date) = addition.identity(); + let (name, email) = if options.author.as_deref().is_some_and(|a| !a.trim().is_empty()) { + (new_name, new_email) + } else { + (original_name, original_email) + }; + let date = if options.author_date.as_deref().is_some_and(|date| !date.trim().is_empty()) { + new_date + } else { + original_date + }; + let author = (name, email, date); + let paths = changed_paths(repo, &before, selected)?; + let Some(rewritten) = + replay_amend(repo, &history, &commit, &addition, author, selected, head.tree != addition.tree)? + else { + history.ensure_current(repo)?; + let mut message = format!("amend! {original}\n\n").into_bytes(); + message.extend_from_slice(addition.message()); + let commit = Commit::write_commit(repo, &addition.tree, Some(&before), &message, addition.encoding(), author)?; + let entries = affected_index_entries(repo, &before, index.as_deref(), &paths)?; + *repo.amend_recovery.lock().unwrap_or_else(|e| e.into_inner()) = + Some(PendingAmend { commit: commit.clone(), history, paths, entries }); + let mut error = IdeError::invalid("Amending this commit would cause a conflict."); + error.data = Some(ErrorData::AmendConflict { commit }); + return Err(error); + }; + ensure_unpublished(repo, original, &target.protected_branches)?; + history.publish_amend(repo, index.as_deref(), &paths, &rewritten, "amend earlier commit")?; + Ok(rewritten) +} + +fn replay_amend( + repo: &Repo, + history: &History, + commit: &Commit, + addition: &Commit, + author: (&str, &str, &str), + selected: &str, + changed: bool, +) -> IdeResult> { + let tree = if changed { + let Some(tree) = merge_onto(repo, &history.head.to_string(), &history.commits[0], selected)? else { + return Ok(None); + }; + tree + } else { + commit.tree.clone() + }; + let mut rewritten = + Commit::write_commit(repo, &tree, commit.parent.as_deref(), addition.message(), addition.encoding(), author)?; + let mut final_tree = tree; + for pair in history.commits.windows(2) { + let next = Commit::read(repo, &pair[1])?; + final_tree = if changed && next.tree != final_tree { + let Some(tree) = merge_onto(repo, &pair[0], &rewritten, &pair[1])? else { return Ok(None) }; + tree + } else { + next.tree.clone() + }; + rewritten = next.write(repo, &final_tree, Some(&rewritten), None)?; + } + // The replay must consume exactly the selected changes. The worktree can then + // stay as it is, including local edits and untracked files on the same paths. + Ok((final_tree == addition.tree).then_some(rewritten)) +} + +#[derive(Clone)] +pub(crate) struct PendingAmend { + commit: String, + history: History, + paths: Vec, + entries: blake3::Hash, +} + +pub(crate) fn keep_amend(repo: &Repo, commit: &str) -> IdeResult { + let pending = repo.amend_recovery.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let pending = pending + .filter(|pending| pending.commit == commit) + .ok_or_else(|| IdeError::invalid("The prepared amend commit is no longer available."))?; + pending.history.ensure_current(repo)?; + let index = read_index(&repo.gix()?.index_path())?; + if affected_index_entries(repo, &pending.history.head.to_string(), index.as_deref(), &pending.paths)? + != pending.entries + { + return Err(IdeError::invalid("Staged changes for the prepared amend commit have changed.")); + } + pending.history.publish_amend(repo, index.as_deref(), &pending.paths, commit, "keep prepared amend commit")?; + let mut recovery = repo.amend_recovery.lock().unwrap_or_else(|e| e.into_inner()); + if recovery.as_ref().is_some_and(|pending| pending.commit == commit) { + *recovery = None; + } + Ok(pending.commit) +} + +fn read_index(path: &Path) -> IdeResult>> { + match fs::read(path) { + Ok(bytes) => Ok(Some(bytes)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error.into()), + } +} + +fn ensure_unpublished(repo: &Repo, commit: &str, protected: &[String]) -> IdeResult<()> { + if protected.is_empty() { + return Ok(()); + } + let refs = + run(repo.root(), &["for-each-ref", "--contains", commit, "--format=%(refname:strip=2)", "refs/remotes"], None)? + .stdout_str(); + if let Some(branch) = refs.lines().find(|branch| protected.iter().any(|name| name == branch)) { + return Err(IdeError::invalid(format!("The commit has already been pushed to protected branch '{branch}'."))); + } + Ok(()) +} + +fn merge_onto(repo: &Repo, base: &str, ours: &str, theirs: &str) -> IdeResult> { + let base = format!("--merge-base={base}"); + let args = ["merge-tree", "--write-tree", "--no-messages", &base, ours, theirs]; + let output = run_raw(repo.root(), &args, None)?; + match output.code { + Some(0) => Ok(Some(output.stdout_str().trim().to_string())), + Some(1) => Ok(None), + _ => Err(failure(&args, &output.stderr, &output.stdout, output.code)), + } +} + +fn changed_paths(repo: &Repo, before: &str, selected: &str) -> IdeResult> { + Ok(run( + repo.root(), + &["diff-tree", "-r", "--no-commit-id", "--no-renames", "--name-only", "-z", before, selected], + None, + )? + .stdout) +} + +fn path_parents(path: &[u8]) -> impl Iterator { + path.iter().enumerate().filter_map(|(i, byte)| (*byte == b'/').then_some(&path[..i])) +} + +/// Ignore index stat refreshes and unrelated staged edits. Ancestors and descendants +/// matter too, since Git can replace a file with a directory at an affected path. +fn affected_index_entries(repo: &Repo, head: &str, index: Option<&[u8]>, paths: &[u8]) -> IdeResult { + let mut hash = blake3::Hasher::new(); + if let Some(index) = index { + let temp = TempIndex::new(repo); + fs::write(temp.path(), index)?; + let output = run_env(repo.root(), &["ls-files", "-v", "--stage", "-z"], None, &temp.env())?; + let paths: HashSet<_> = paths.split(|&byte| byte == 0).filter(|path| !path.is_empty()).collect(); + let parents: HashSet<_> = paths.iter().flat_map(|path| path_parents(path)).collect(); + let related = |path: &[u8]| { + paths.contains(path) || parents.contains(path) || path_parents(path).any(|p| paths.contains(p)) + }; + for entry in output.stdout.split(|&byte| byte == 0) { + let Some(tab) = entry.find_byte(b'\t') else { continue }; + if related(&entry[tab + 1..]) { + hash.update(entry); + hash.update(b"\0"); + } + } + // ls-files gives both intent-to-add and a staged empty file the empty blob ID. + let additions = run_env( + repo.root(), + &[ + "diff-index", + "--cached", + "--ita-invisible-in-index", + "--diff-filter=A", + "--name-only", + "-z", + "--no-renames", + head, + "--", + ], + None, + &temp.env(), + )?; + hash.update(b"\0"); + for path in additions.stdout.split(|&byte| byte == 0).filter(|path| related(path)) { + hash.update(path); + hash.update(b"\0"); + } + } + Ok(hash.finalize()) +} + +fn index_after_amend(repo: &Repo, original: Option<&[u8]>, paths: &[u8], selected: &str) -> IdeResult>> { + if paths.is_empty() { + return Ok(None); + } + let next = TempIndex::new(repo); + if let Some(original) = original { + fs::write(next.path(), original)?; + } else { + run_env(repo.root(), &["read-tree", "--empty"], None, &next.env())?; + } + run_env( + repo.root(), + &["--literal-pathspecs", "reset", "-q", selected, "--pathspec-from-file=-", "--pathspec-file-nul"], + Some(paths), + &next.env(), + )?; + Ok(Some(fs::read(next.path())?)) +} + +pub(crate) fn extract( + repo: &Repo, + id: &str, + expected_head: &HistoryTip, + paths: &[PathBuf], + message: &str, +) -> IdeResult { + let message = new_message(message)?; + let history = History::load(repo, id, Some(expected_head))?; + let target = &history.commits[0]; + let commit = Commit::read(repo, target)?; + let remaining = remaining_tree(repo, target, &commit, paths)?; + let rewritten = commit.write(repo, &remaining, commit.parent.as_deref(), None)?; + let extracted = commit.write(repo, &commit.tree, Some(&rewritten), Some(&message))?; + let head = history.rewrite_descendants(repo, extracted.clone(), "extract selected changes")?; + Ok(RewrittenCommit { head, commit: extracted }) +} + +pub(crate) fn drop_changes( + repo: &Repo, + id: &str, + expected_head: &HistoryTip, + paths: &[PathBuf], + cancel: &CancellationToken, + out: &dyn Fn(String), +) -> IdeResult { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let history = History::load(repo, id, Some(expected_head))?; + let target = &history.commits[0]; + let commit = Commit::read(repo, target)?; + let remaining = remaining_tree(repo, target, &commit, paths)?; + let replacement = commit.write(repo, &remaining, commit.parent.as_deref(), None)?; + let mut todo = format!("drop {target}\npick {replacement}\n"); + for descendant in &history.commits[1..] { + todo.push_str(&format!("pick {descendant}\n")); + } + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + history.ensure_current(repo)?; + let work = tempfile::tempdir_in(&repo.git_dir)?; + let args = [ + "-c", + "rebase.missingCommitsCheck=error", + "rebase", + "--interactive", + "--no-autosquash", + "--empty=keep", + commit.parent.as_deref().unwrap_or("--root"), + ]; + crate::ops::run_rebase_todo(repo, work.path(), &todo, &args, cancel, out)?; + let after = run(repo.root(), &["rev-parse", "--verify", "HEAD"], None)?.stdout_str().trim().to_string(); + let rewritten = format!("{after}~{}", history.commits.len() - 1); + let commit = run(repo.root(), &["rev-parse", "--verify", &rewritten], None)?.stdout_str().trim().to_string(); + Ok(RewrittenCommit { head: HeadChange { before: history.head.to_string(), after }, commit }) +} + +fn remaining_tree(repo: &Repo, id: &str, commit: &Commit, paths: &[PathBuf]) -> IdeResult { + let paths = paths.iter().map(|path| repo.given_rel_path(path)).collect::>>()?; + if paths.is_empty() || paths.contains("") { + return Err(IdeError::invalid("select files from the commit")); + } + let source_tree = if let Some(parent) = &commit.parent { + run(repo.root(), &["rev-parse", &format!("{parent}^{{tree}}")], None)? + } else { + run(repo.root(), &["hash-object", "-t", "tree", "-w", "--stdin"], Some(b""))? + } + .stdout_str(); + let source = format!("--source={}", source_tree.trim()); + let index = TempIndex::new(repo); + let env = index.env(); + let config = ["-c", "core.sparseCheckout=false", "-c", "index.sparse=false"]; + run_env(repo.root(), &[&config[..], &["read-tree", id]].concat(), None, &env)?; + let mut pathspec = Vec::new(); + for path in &paths { + pathspec.extend_from_slice(path.as_bytes()); + pathspec.push(0); + } + let restore = + ["--literal-pathspecs", "restore", "--staged", &source, "--pathspec-from-file=-", "--pathspec-file-nul"]; + run_env(repo.root(), &[&config[..], &restore].concat(), Some(&pathspec), &env)?; + let changed = run_env( + repo.root(), + &[&config[..], &["diff", "--cached", "--name-only", "--no-renames", "-z", id, "--"]].concat(), + None, + &env, + )?; + let restored: HashSet<&[u8]> = changed.stdout.split(|&b| b == 0).filter(|path| !path.is_empty()).collect(); + // A file/directory replacement can make a pathspec touch unselected paths. + if restored.len() != paths.len() || paths.iter().any(|path| !restored.contains(path.as_bytes())) { + return Err(IdeError::invalid("the selected paths cannot be split from the other changes in this commit")); + } + let tree = run_env(repo.root(), &[&config[..], &["write-tree"]].concat(), None, &env)?.stdout_str(); + if tree.trim() == source_tree.trim() { + return Err(IdeError::invalid("select fewer than all changes in the commit")); + } + Ok(tree.trim().to_string()) +} diff --git a/crates/ide-vcs/src/compare.rs b/crates/ide-vcs/src/compare.rs index 424bfa056..1d8af5370 100644 --- a/crates/ide-vcs/src/compare.rs +++ b/crates/ide-vcs/src/compare.rs @@ -705,6 +705,45 @@ mod tests { (marker, script.to_str().unwrap().replace('\\', "/")) } + #[test] + fn log_details_reads_each_signed_commit_once_when_git_displays_signatures() { + let temp = tempfile::tempdir().unwrap(); + let root = normalized(temp.path()); + init(&root, "main"); + git(&root, &["commit", "--allow-empty", "-qm", "first signed"]); + sign_head(&root, "PGP SIGNATURE"); + git(&root, &["commit", "--allow-empty", "-qm", "second signed"]); + sign_head(&root, "PGP SIGNATURE"); + let (_, script) = verifier_script(&root); + std::fs::write( + &script, + "#!/bin/sh\nprintf 'attempt\\n' >> verification-attempts\n\ + printf '%s\\n' 'gpg: Test diagnostic' >&2\n\ + printf '%s\\n' '[GNUPG:] NEWSIG' '[GNUPG:] BADSIG 61CF236723A1C18B Synthetic Signer'\nexit 1\n", + ) + .unwrap(); + git(&root, &["config", "log.showSignature", "true"]); + git(&root, &["config", "gpg.program", &script]); + + let repo = crate::Repo::discover(&root).unwrap().unwrap(); + repo.set_execution_allowed(true); + let revisions = ["HEAD^", "HEAD~2", "HEAD", "HEAD^"].map(String::from); + let cancel = CancellationToken::new(); + let details = repo.log_details_batch_cancellable(&revisions, &cancel).unwrap(); + assert_eq!( + details.iter().map(|d| (d.message.as_str(), d.signature.as_str())).collect::>(), + [("first signed", "B"), ("initial", "N"), ("second signed", "B"), ("first signed", "B")] + ); + assert_eq!(details[0].signer, "Synthetic Signer"); + assert_eq!(details[2].key, "61CF236723A1C18B"); + assert_eq!(repo.log_details("HEAD").unwrap().signature, "B"); + + repo.set_execution_allowed(false); + assert_eq!(repo.log_details("HEAD").unwrap().signature, "E"); + let attempts = std::fs::read_to_string(root.join("verification-attempts")).unwrap(); + assert_eq!(attempts.lines().count(), 2); + } + /// Security audit lead 2: Restricted Mode `git log` must not run the repository's signature verifier. #[test] fn restricted_log_does_not_execute_signature_verifier() { diff --git a/crates/ide-vcs/src/conflict_resolution.rs b/crates/ide-vcs/src/conflict_resolution.rs new file mode 100644 index 000000000..f06375d5a --- /dev/null +++ b/crates/ide-vcs/src/conflict_resolution.rs @@ -0,0 +1,241 @@ +//! Whole-file conflict resolution and the original stages Git saves for undo. + +use crate::cli::run; +use crate::repo::gx; +use crate::{ConflictSide, Repo, StashApplyOutcome}; +use gix::bstr::BStr; +use gix::index::entry::Stage; +use ide_core::{IdeError, IdeResult}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; + +const CONFLICT_STAGES: [Stage; 3] = [Stage::Base, Stage::Ours, Stage::Theirs]; +const RESTORE_CONFLICTS: &str = "openidea-manual-stash-conflicts.json"; + +#[derive(Clone, Copy, Default, serde::Serialize, serde::Deserialize)] +pub(crate) enum RestoreConflict { + #[default] + ManualStash, + AutomaticShelf, + PatchApply, +} + +#[derive(serde::Serialize, serde::Deserialize)] +struct RestoreConflicts { + #[serde(default)] + kind: RestoreConflict, + head: (Option, Option), + stages: BTreeSet, +} + +fn unmerged_stages(repo: &Repo) -> IdeResult> { + let index = run(repo.root(), &["ls-files", "--unmerged", "-z"], None)?; + Ok(index + .stdout + .split(|&byte| byte == 0) + .filter(|entry| !entry.is_empty()) + .map(|entry| blake3::hash(entry).to_hex().to_string()) + .collect()) +} + +fn save_restore_conflicts(repo: &Repo, kind: RestoreConflict, stages: BTreeSet) -> IdeResult<()> { + let conflicts = RestoreConflicts { kind, head: repo.head()?, stages }; + let mut file = tempfile::NamedTempFile::new_in(&repo.git_dir)?; + serde_json::to_writer(&mut file, &conflicts).map_err(|error| IdeError::internal(error.to_string()))?; + file.persist(repo.git_dir.join(RESTORE_CONFLICTS)).map_err(|error| error.error)?; + Ok(()) +} + +pub(crate) fn clear_restore_conflicts(repo: &Repo) { + let _ = std::fs::remove_file(repo.git_dir.join(RESTORE_CONFLICTS)); +} + +pub(crate) fn record_conflicts(repo: &Repo, kind: RestoreConflict) { + let result = unmerged_stages(repo).and_then(|stages| save_restore_conflicts(repo, kind, stages)); + if let Err(error) = result { + tracing::warn!(?error, "could not record conflict sides"); + } +} + +pub(crate) fn run_manual_unstash(repo: &Repo, args: &[&str]) -> IdeResult { + let _guard = repo.conflict_mutation.lock().unwrap_or_else(|error| error.into_inner()); + let fresh = crate::write::unmerged_paths(repo)?.is_empty(); + if fresh { + clear_restore_conflicts(repo); + } + match run(repo.root(), args, None) { + Ok(_) => Ok(StashApplyOutcome::Done), + Err(error) if fresh => { + let Ok(stages) = unmerged_stages(repo) else { return Err(error) }; + if stages.is_empty() { + return Err(error); + } + if let Err(error) = save_restore_conflicts(repo, RestoreConflict::ManualStash, stages) { + tracing::warn!(?error, "could not record manual stash conflicts"); + } + Ok(StashApplyOutcome::Conflicts { repository: repo.root().into() }) + } + Err(error) => Err(error), + } +} + +pub(crate) fn restore_conflict(repo: &Repo) -> IdeResult> { + let Ok(bytes) = std::fs::read(repo.git_dir.join(RESTORE_CONFLICTS)) else { return Ok(None) }; + let Ok(conflicts) = serde_json::from_slice::(&bytes) else { return Ok(None) }; + if conflicts.head != repo.head()? { + return Ok(None); + } + // Resolving a file removes its stages from the index. The remaining files + // keep the same side labels as long as their original stages still match. + let stages = unmerged_stages(repo)?; + Ok((!stages.is_empty() && stages.is_subset(&conflicts.stages)).then_some(conflicts.kind)) +} + +pub(crate) fn accept_side(repo: &Repo, paths: &[PathBuf], side: ConflictSide) -> IdeResult<()> { + if paths.is_empty() { + return Ok(()); + } + let _guard = repo.conflict_mutation.lock().unwrap_or_else(|e| e.into_inner()); + let ours = (side == ConflictSide::Ours) != repo.merge_sides()?.reversed; + let (stage, option) = if ours { (Stage::Ours, "--ours") } else { (Stage::Theirs, "--theirs") }; + let git = repo.gix()?; + let index = git.open_index().map_err(gx)?; + let paths = paths.iter().map(|path| repo.rel_path(path)).collect::>>()?; + let mut kept = Vec::new(); + let mut deleted = Vec::new(); + for path in paths { + let key = BStr::new(path.as_bytes()); + if let Some(entry) = index.entry_by_path_and_stage(key, stage) { + kept.push((path, entry.mode, entry.id)); + } else if CONFLICT_STAGES.iter().any(|&s| index.entry_by_path_and_stage(key, s).is_some()) { + deleted.push(path); + } else { + return Err(IdeError::invalid(format!("{path} has no conflict to resolve"))); + } + } + + let present: Vec<_> = kept.iter().map(|(path, _, _)| path.clone()).collect(); + checkout(repo, option, &present)?; + run_literal_paths(repo, &["rm", "--sparse", "--ignore-unmatch"], &deleted)?; + if !kept.is_empty() { + let current = git.open_index().map_err(gx)?; + let mut records = Vec::new(); + for (path, mode, id) in kept { + let entry = current.entry_by_path_and_stage(BStr::new(path.as_bytes()), stage); + if !entry.is_some_and(|entry| entry.mode == mode && entry.id == id) { + return Err(IdeError::invalid(format!("the conflict in {path} changed while resolving it"))); + } + // Stage the exact blob and mode. Replacing the unmerged entries this way + // makes Git retain their original stages for Revert Resolved. + records.extend_from_slice(format!("{:o} {id}\t{path}\0", mode.bits()).as_bytes()); + } + run(repo.root(), &["update-index", "-z", "--index-info"], Some(&records))?; + } + Ok(()) +} + +struct SavedStage { + mode: String, + id: String, + stage: u8, +} + +fn saved_resolutions(repo: &Repo) -> IdeResult>> { + let objects = repo.gix()?; + let mut resolutions = BTreeMap::>::new(); + if !matches!( + crate::refs::operation(&objects).as_deref(), + Some("merge" | "rebase" | "revert" | "cherry-pick" | "am") + ) { + return Ok(resolutions); + } + let index = objects.index_or_empty().map_err(gx)?; + if index.resolve_undo().is_none() { + return Ok(resolutions); + } + let listed = run(repo.root(), &["ls-files", "--resolve-undo", "-z"], None)?; + for entry in listed.stdout.split(|&b| b == 0).filter_map(|entry| std::str::from_utf8(entry).ok()) { + let Some((info, path)) = entry.split_once('\t') else { continue }; + let path_key = BStr::new(path.as_bytes()); + if CONFLICT_STAGES.iter().any(|stage| index.entry_by_path_and_stage(path_key, *stage).is_some()) { + continue; + } + let mut fields = info.split_ascii_whitespace(); + if let (Some(mode), Some(id), Some(Ok(stage @ 1..=3))) = + (fields.next(), fields.next(), fields.next().map(str::parse::)) + { + resolutions.entry(path.to_string()).or_default().push(SavedStage { + mode: mode.to_string(), + id: id.to_string(), + stage, + }); + } + } + Ok(resolutions) +} + +pub(crate) fn resolved_paths(repo: &Repo) -> IdeResult> { + Ok(saved_resolutions(repo)?.into_keys().map(|path| repo.abs_path(&path)).collect()) +} + +pub(crate) fn revert_resolved(repo: &Repo, paths: &[PathBuf]) -> IdeResult<()> { + if paths.is_empty() { + return Ok(()); + } + let _guard = repo.conflict_mutation.lock().unwrap_or_else(|e| e.into_inner()); + let paths = paths.iter().map(|path| repo.rel_path(path)).collect::>>()?; + let resolutions = saved_resolutions(repo)?; + if let Some(path) = paths.iter().find(|path| !resolutions.contains_key(*path)) { + return Err(IdeError::invalid(format!("{path} has no resolution to revert"))); + } + let mut merge = Vec::new(); + let mut ours = Vec::new(); + let mut theirs = Vec::new(); + let mut index_info = Vec::new(); + let zero = repo.gix()?.object_hash().null(); + for path in paths { + let stages = &resolutions[&path]; + let has_ours = stages.iter().any(|s| s.stage == 2); + let has_theirs = stages.iter().any(|s| s.stage == 3); + if has_ours && has_theirs { + merge.push(path); + } else { + // Checkout --merge needs both sides. For modify/delete, restore the + // saved index stages and check out the surviving side. + index_info.extend_from_slice(format!("0 {zero}\t{path}\0").as_bytes()); + for stage in stages { + let SavedStage { mode, id, stage } = stage; + index_info.extend_from_slice(format!("{mode} {id} {stage}\t{path}\0").as_bytes()); + } + if has_ours { + ours.push(path); + } else if has_theirs { + theirs.push(path); + } + } + } + checkout(repo, "--merge", &merge)?; + if !index_info.is_empty() { + run(repo.root(), &["update-index", "-z", "--index-info"], Some(&index_info))?; + checkout(repo, "--ours", &ours)?; + checkout(repo, "--theirs", &theirs)?; + } + Ok(()) +} + +fn checkout(repo: &Repo, option: &str, paths: &[String]) -> IdeResult<()> { + run_literal_paths(repo, &["checkout", option, "--no-recurse-submodules", "--ignore-skip-worktree-bits"], paths) +} + +fn run_literal_paths(repo: &Repo, command: &[&str], paths: &[String]) -> IdeResult<()> { + if paths.is_empty() { + return Ok(()); + } + let mut pathspec = paths.join("\0").into_bytes(); + pathspec.push(0); + let mut args = vec!["--literal-pathspecs"]; + args.extend_from_slice(command); + args.extend(["--pathspec-from-file=-", "--pathspec-file-nul"]); + run(repo.root(), &args, Some(&pathspec))?; + Ok(()) +} diff --git a/crates/ide-vcs/src/diff.rs b/crates/ide-vcs/src/diff.rs index 9a2e935ff..8524697c7 100644 --- a/crates/ide-vcs/src/diff.rs +++ b/crates/ide-vcs/src/diff.rs @@ -1,8 +1,9 @@ //! Line diffs (imara-diff Histogram) for gutter markers and partial staging. -use crate::{HunkKind, LineHunk}; +use crate::{HunkKind, LineHunk, PartialCommitHunk, StagingLineHunk}; use gix::diff::blob::{Algorithm, Diff, InternedInput}; use std::borrow::Cow; +use std::collections::{BTreeMap, HashSet}; use std::ops::Range; /// Converts CRLF (and lone CR) line endings to LF. @@ -54,6 +55,91 @@ pub fn line_hunks(old: &str, new: &str) -> Vec { .collect() } +struct IndexRange { + lines: Range, + head_delta: i64, + working_delta: i64, + staged: bool, + unstaged: bool, +} + +/// Combine the two diffs in index coordinates, then project each connected +/// block onto HEAD and the working text. +pub(crate) fn staging_line_hunks(head: &str, index: &str, working: &str) -> Vec { + let head = normalize_eol(head); + let working = normalize_eol(working); + let head = split_lines(&head); + let index = split_lines(index); + let working = split_lines(&working); + let delta = |from: &Range, to: &Range| to.len() as i64 - from.len() as i64; + let mut changes: Vec<_> = raw_hunks(&head, &index) + .into_iter() + .map(|(before, after)| IndexRange { + head_delta: delta(&after, &before), + lines: after, + working_delta: 0, + staged: true, + unstaged: false, + }) + .chain(raw_hunks(&index, &working).into_iter().map(|(before, after)| IndexRange { + working_delta: delta(&before, &after), + lines: before, + head_delta: 0, + staged: false, + unstaged: true, + })) + .collect(); + changes.sort_unstable_by_key(|block| block.lines.start); + let mut blocks: Vec = Vec::new(); + for change in changes { + if let Some(block) = blocks.last_mut().filter(|block| change.lines.start <= block.lines.end) { + block.lines.end = block.lines.end.max(change.lines.end); + block.head_delta += change.head_delta; + block.working_delta += change.working_delta; + block.staged |= change.staged; + block.unstaged |= change.unstaged; + } else { + blocks.push(change); + } + } + let mut head_shift = 0; + let mut working_shift = 0; + blocks + .into_iter() + .map(|block| { + let head_start = (i64::from(block.lines.start) + head_shift) as u32; + let start = (i64::from(block.lines.start) + working_shift) as u32; + head_shift += block.head_delta; + working_shift += block.working_delta; + let head_end = (i64::from(block.lines.end) + head_shift) as u32; + let end = (i64::from(block.lines.end) + working_shift) as u32; + let index_start = block.lines.start; + let index_end = block.lines.end; + let before_is_empty = if block.unstaged { index_end == index_start } else { head_end == head_start }; + let kind = if end == start { + HunkKind::Deleted + } else if before_is_empty { + HunkKind::Added + } else { + HunkKind::Modified + }; + StagingLineHunk { + kind, + start, + lines: end - start, + head_start, + head_lines: head_end - head_start, + head_text: head[head_start as usize..head_end as usize].concat(), + index_start, + index_lines: index_end - index_start, + index_text: index[index_start as usize..index_end as usize].concat(), + staged: block.staged, + unstaged: block.unstaged, + } + }) + .collect() +} + /// Hunks for a file that does not exist in the base (untracked / newly added). pub(crate) fn all_added(new: &str) -> Vec { let new = normalize_eol(new); @@ -154,7 +240,7 @@ fn push_line(out: &mut String, prefix: char, line: &str) { } /// C-style quoting for paths git would quote in patch headers. -fn quote_path(path: &str) -> String { +pub(crate) fn quote_path(path: &str) -> String { let needs = path.chars().any(|c| c == '"' || c == '\\' || c.is_control() || c == ' ' || c == '\t'); if !needs { return path.to_string(); @@ -176,11 +262,53 @@ fn quote_path(path: &str) -> String { /// Apply selected line hunks while retaining the base's line separators. pub(crate) fn selected_text(old: &str, new: &str, selected: &[usize]) -> String { + selected_lines_text(old, new, selected, &BTreeMap::new()) +} + +pub(crate) fn selected_lines_text( + old: &str, + new: &str, + selected: &[usize], + lines: &BTreeMap, +) -> String { + apply_text_hunks(old, new, |index| match lines.get(&index) { + Some(selection) => HunkSelection::Lines(selection), + None if selected.contains(&index) => HunkSelection::Whole, + None => HunkSelection::Excluded, + }) +} + +pub(crate) fn replace_text(old: &str, new: &str) -> String { + apply_text_hunks(old, new, |_| HunkSelection::Whole) +} + +enum HunkSelection<'a> { + Whole, + Lines(&'a PartialCommitHunk), + Excluded, +} + +fn apply_text_hunks<'a>(old: &str, new: &str, included: impl Fn(usize) -> HunkSelection<'a>) -> String { let old_norm = normalize_eol(old); let new_norm = normalize_eol(new); let old_lines = split_lines(&old_norm); let new_lines = split_lines(&new_norm); - let old_raw = split_raw_lines(old); + let mut start = 0; + let old_raw: Vec<_> = old + .bytes() + .enumerate() + .filter_map(|(i, byte)| { + let end = i + 1; + let separator = byte == b'\n' || (byte == b'\r' && old.as_bytes().get(end) != Some(&b'\n')); + if separator || end == old.len() { + let line = &old[start..end]; + start = end; + Some(line) + } else { + None + } + }) + .collect(); let eol = if old.contains("\r\n") { "\r\n" } else if old.contains('\r') { @@ -191,13 +319,30 @@ pub(crate) fn selected_text(old: &str, new: &str, selected: &[usize]) -> String let mut result = String::new(); let mut cursor = 0; for (index, (before, after)) in raw_hunks(&old_lines, &new_lines).iter().enumerate() { - if !selected.contains(&index) { - continue; - } + let lines = match included(index) { + HunkSelection::Excluded => continue, + HunkSelection::Whole => None, + HunkSelection::Lines(lines) => Some(lines), + }; for line in &old_raw[cursor..before.start as usize] { result.push_str(line); } - for line in &new_lines[after.start as usize..after.end as usize] { + if let Some(lines) = lines { + let deletions: HashSet<_> = lines.deletions.iter().copied().collect(); + for (offset, line) in old_raw[before.start as usize..before.end as usize].iter().enumerate() { + if !deletions.contains(&(offset as u32)) { + result.push_str(line); + } + } + } + let additions = lines.map(|lines| lines.additions.iter().copied().collect::>()); + for (offset, line) in new_lines[after.start as usize..after.end as usize].iter().enumerate() { + if additions.as_ref().is_some_and(|lines| !lines.contains(&(offset as u32))) { + continue; + } + if lines.is_some() && !result.is_empty() && !result.ends_with(['\r', '\n']) { + result.push_str(eol); + } if let Some(body) = line.strip_suffix('\n') { result.push_str(body); result.push_str(eol); @@ -217,6 +362,41 @@ pub(crate) fn selected_text(old: &str, new: &str, selected: &[usize]) -> String mod tests { use super::*; + #[test] + fn staging_line_hunks_keep_both_changes_when_head_and_worktree_match() { + let hunks = staging_line_hunks("top\r\nhead\r\nend", "top\nindex\nend", "top\nhead\nend"); + assert_eq!(hunks.len(), 1); + let hunk = &hunks[0]; + assert!(hunk.staged && hunk.unstaged); + assert_eq!((hunk.start, hunk.lines, hunk.index_start, hunk.index_lines), (1, 1, 1, 1)); + assert_eq!(hunk.head_text, "head\n"); + assert_eq!(hunk.index_text, "index\n"); + } + + #[test] + fn staging_line_hunks_project_deletions_and_insertions_into_worktree_lines() { + let hunks = staging_line_hunks( + "intro\nremoved\npivot\ntarget\ntail\nend\n", + "intro\npivot\ntarget\ntail\nstaged tail\nend\n", + "intro\ninserted A\ninserted B\npivot\nworking target\ntail\nstaged tail\nend\n", + ); + assert_eq!(hunks.len(), 3); + assert!(hunks[0].staged && hunks[0].unstaged); + assert_eq!((hunks[0].start, hunks[0].lines, hunks[0].head_start), (1, 2, 1)); + assert_eq!(hunks[0].head_text, "removed\n"); + assert_eq!(hunks[0].index_text, ""); + assert!(!hunks[1].staged && hunks[1].unstaged); + assert_eq!((hunks[1].start, hunks[1].head_start, hunks[1].index_start), (4, 3, 2)); + assert_eq!(hunks[1].index_text, "target\n"); + assert!(hunks[2].staged && !hunks[2].unstaged); + assert_eq!((hunks[2].start, hunks[2].head_start, hunks[2].index_start), (6, 5, 4)); + } + + #[test] + fn selected_text_handles_lone_carriage_returns() { + assert_eq!(selected_text("old\rkeep\r", "new\rkeep\r", &[0]), "new\rkeep\r"); + } + #[test] fn hunk_kinds() { let old = "a\nb\nc\nd\n"; diff --git a/crates/ide-vcs/src/history.rs b/crates/ide-vcs/src/history.rs index 54d2de593..fb17ba2f3 100644 --- a/crates/ide-vcs/src/history.rs +++ b/crates/ide-vcs/src/history.rs @@ -1,12 +1,212 @@ //! Commit history (topological walk) and per-commit changed files via gitoxide. use crate::repo::{gx, link_target, resolve, to_string}; -use crate::{ChangeKind, ChangedFile, Commit, LogOrder, LogQuery, Repo, RevisionChange}; +use crate::{ChangeKind, ChangedFile, Commit, LogDetails, LogOrder, LogQuery, Repo, RevisionChange}; use gix::ObjectId; use gix::bstr::ByteSlice; use ide_core::{CancellationToken, IdeError, IdeResult}; use redb::ReadableDatabase; use std::collections::{HashMap, HashSet}; +use std::path::Path; +use std::time::{Duration, Instant}; + +pub(crate) struct LogSignature { + pub code: String, + pub signer: String, + pub key: String, + pub fingerprint: String, +} + +impl LogSignature { + pub(crate) fn apply(&self, details: &mut LogDetails) { + details.signature.clone_from(&self.code); + details.signer.clone_from(&self.signer); + details.key.clone_from(&self.key); + details.fingerprint.clone_from(&self.fingerprint); + } +} + +const SIGNATURE_TTL: Duration = Duration::from_secs(60); +const MAX_SIGNATURES: usize = 1_000; + +#[derive(Default)] +pub(crate) struct LogSignatureCache { + pub generation: u64, + entries: HashMap, +} + +impl LogSignatureCache { + pub(crate) fn clear(&mut self) { + self.generation = self.generation.wrapping_add(1); + self.entries.clear(); + } + + pub(crate) fn get(&self, id: &ObjectId, now: Instant) -> Option<&LogSignature> { + self.entries + .get(id) + .filter(|(checked_at, _)| now.saturating_duration_since(*checked_at) < SIGNATURE_TTL) + .map(|(_, signature)| signature) + } + + pub(crate) fn store(&mut self, generation: u64, checked_at: Instant, signatures: HashMap) { + if generation != self.generation || signatures.is_empty() { + return; + } + self.entries.retain(|_, (time, _)| checked_at.saturating_duration_since(*time) < SIGNATURE_TTL); + for (id, signature) in signatures { + if self.entries.get(&id).is_none_or(|(time, _)| *time <= checked_at) { + self.entries.insert(id, (checked_at, signature)); + } + } + let excess = self.entries.len().saturating_sub(MAX_SIGNATURES); + if excess > 0 { + let mut ages: Vec<_> = self.entries.iter().map(|(id, (time, _))| (*time, *id)).collect(); + ages.sort_unstable(); + for (_, id) in ages.into_iter().take(excess) { + self.entries.remove(&id); + } + } + } +} + +pub(crate) fn log_signatures( + root: &Path, + commits: &HashSet, + cancel: &CancellationToken, +) -> IdeResult> { + if commits.is_empty() { + return Ok(HashMap::new()); + } + let mut stdin = String::new(); + for id in commits { + use std::fmt::Write; + let _ = writeln!(stdin, "{id}"); + } + let output = crate::cli::run_cancellable_stdin( + root, + &[ + "log", + "--no-walk=unsorted", + "--no-show-signature", + "--no-notes", + "--no-decorate", + "-z", + "--format=%H%x00%G?%x00%GS%x00%GK%x00%GF", + "--stdin", + "--", + ], + stdin.as_bytes(), + cancel, + )?; + let text = output.stdout_str(); + let fields: Vec<_> = text.split_terminator('\0').collect(); + Ok(fields + .as_chunks::<5>() + .0 + .iter() + .filter_map(|row| { + let id = ObjectId::from_hex(row[0].as_bytes()).ok()?; + let code = match row[1] { + "G" | "U" | "B" | "E" | "X" | "Y" | "R" => row[1], + // The caller only requests commits with a signature header. + _ => "E", + }; + Some(( + id, + LogSignature { + code: code.into(), + signer: row[2].into(), + key: row[3].into(), + fingerprint: row[4].into(), + }, + )) + }) + .collect()) +} + +/// Source-side commits that have no equivalent on the target branch. +pub(crate) fn not_cherry_picked( + r: &Repo, + source: &str, + target: &str, + cancel: &CancellationToken, +) -> IdeResult>> { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let repo = r.gix()?; + let Some(source) = comparison_tip(&repo, source)? else { return Ok(None) }; + let Some(target) = comparison_tip(&repo, target)? else { return Ok(None) }; + if source == target { + return Ok(Some(Vec::new())); + } + let out = crate::cli::run_cancellable(r.root(), &["cherry", "--no-abbrev", &target, &source], cancel)?; + let mut unmatched = + out.stdout_str().lines().filter_map(|line| line.strip_prefix("+ ").map(str::to_owned)).collect::>(); + if unmatched.is_empty() { + return Ok(Some(Vec::new())); + } + + // A pick resolved with conflicts can have a different patch-id. Match the recorded + // origin or the original author, author time and message on the other side. + let range = format!("{target}...{source}"); + let history = crate::cli::run_cancellable( + r.root(), + &[ + "log", + "--left-right", + "--no-merges", + "--no-notes", + "--no-show-signature", + "-z", + "--format=%m%H%x00%an%x00%ae%x00%at%x00%B", + &range, + "--", + ], + cancel, + )?; + let fields: Vec<_> = history.stdout.split(|byte| *byte == 0).collect(); + let records = fields.as_chunks::<5>().0.iter(); + let mut target_metadata = HashSet::new(); + for row in records.clone().filter(|row| row[0].starts_with(b"<")) { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + target_metadata.insert(&row[1..]); + if let Some(origin) = String::from_utf8_lossy(row[4]) + .trim_end() + .lines() + .last() + .and_then(|line| line.strip_prefix("(cherry picked from commit ")) + .and_then(|line| line.strip_suffix(')')) + { + unmatched.remove(origin); + } + } + for row in records.filter(|row| row[0].starts_with(b">")) { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + if target_metadata.contains(&row[1..]) { + unmatched.remove(String::from_utf8_lossy(&row[0][1..]).as_ref()); + } + } + let mut commits: Vec<_> = unmatched.into_iter().collect(); + commits.sort_unstable(); + Ok(Some(commits)) +} + +fn comparison_tip(repo: &gix::Repository, rev: &str) -> IdeResult> { + if rev != "HEAD" && !rev.starts_with("refs/") { + for namespace in ["heads", "remotes"] { + let name = format!("refs/{namespace}/{rev}"); + if let Some(mut reference) = repo.try_find_reference(name.as_str()).map_err(gx)? { + return reference.peel_to_id().map(|id| Some(id.to_string())).map_err(gx); + } + } + } + Ok(resolve(repo, rev).ok().map(|id| id.to_string())) +} /// Log "Text or hash" filter: the message (substring or regex), or a hash prefix. enum TextFilter { @@ -1321,10 +1521,48 @@ struct Merged { /// after the last one, following renames. Files added and then deleted drop out. pub(crate) fn commits_changes(r: &Repo, commits: &[String]) -> IdeResult> { let repo = r.gix()?; + merge_commit_changes(&repo, commits, &CancellationToken::new()) +} + +pub(crate) fn commit_selection_changes( + r: &Repo, + commits: &[String], + cancel: &CancellationToken, +) -> IdeResult> { + let repo = r.gix()?; + if commits.len() <= 1 { + return merge_commit_changes(&repo, commits, cancel); + } + let mut ids = Vec::with_capacity(commits.len()); + let mut seen = HashSet::new(); + for rev in commits { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let id = resolve(&repo, rev)?; + let id = repo.find_object(id).map_err(gx)?.peel_to_commit().map_err(gx)?.id; + if seen.insert(id) { + ids.push(id); + } + } + let shallow = repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect()).unwrap_or_default(); + let ordered = sort_subset(&repo, ids, LogOrder::Topo, false, &shallow, cancel, &HashMap::new())?; + let commits: Vec<_> = ordered.into_iter().rev().map(|id| id.to_string()).collect(); + merge_commit_changes(&repo, &commits, cancel) +} + +fn merge_commit_changes( + repo: &gix::Repository, + commits: &[String], + cancel: &CancellationToken, +) -> IdeResult> { let mut merged: Vec = Vec::new(); let mut seen = HashSet::new(); for rev in commits { - let c = first_parent_changes(&repo, rev)?; + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let c = first_parent_changes(repo, rev)?; if !seen.insert(c.id) { continue; } @@ -1379,7 +1617,39 @@ pub(crate) fn commits_changes(r: &Repo, commits: &[String]) -> IdeResult IdeResult { } /// A symlink, or a Windows reparse point such as a junction, is a single entry for Git. -fn is_link(meta: &fs::Metadata) -> bool { +pub(crate) fn is_link(meta: &fs::Metadata) -> bool { if meta.file_type().is_symlink() { return true; } diff --git a/crates/ide-vcs/src/incoming.rs b/crates/ide-vcs/src/incoming.rs new file mode 100644 index 000000000..09facdac2 --- /dev/null +++ b/crates/ide-vcs/src/incoming.rs @@ -0,0 +1,169 @@ +//! Remote ref checks that leave the object database and tracking refs alone. + +use crate::{Repo, TrackedTip, UpstreamTracking, cli, ops::remote_fetch_url, refs, repo}; +use gix::bstr::ByteSlice; +use ide_core::error::ErrorKind; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::collections::{BTreeMap, HashMap}; + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct UnfetchedBranch { + pub branch: String, + pub tracked_tip: TrackedTip, + pub advertised_commit: String, +} + +#[derive(Debug, Serialize, Deserialize, Type)] +pub struct IncomingRemoteError { + pub remote: String, + pub error: IdeError, +} + +#[derive(Debug, Serialize, Deserialize, Type)] +pub struct IncomingRefsReport { + pub branches: Vec, + pub errors: Vec, +} + +#[derive(Default)] +pub(crate) struct IncomingObservations { + generation: u64, + branches: HashMap, + // Resolved URLs may contain credentials. Keep them in the repository, outside IPC reports. + endpoints: HashMap, +} + +impl Repo { + pub fn check_incoming_refs(&self, cancel: &CancellationToken) -> IdeResult { + let _scope = self.execution_scope(); + let generation = { + let mut observations = self.incoming_observations.lock().unwrap_or_else(|p| p.into_inner()); + observations.generation += 1; + observations.generation + }; + let mut endpoints = HashMap::new(); + let report = self.read_incoming_refs(&mut endpoints, cancel); + let mut observations = self.incoming_observations.lock().unwrap_or_else(|p| p.into_inner()); + if generation == observations.generation && !cancel.is_cancelled() { + observations.branches = report + .as_ref() + .into_iter() + .flat_map(|report| &report.branches) + .map(|branch| (branch.branch.clone(), branch.clone())) + .collect(); + observations.endpoints = endpoints; + } + report + } + + pub(crate) fn observed_incoming_tip( + &self, + branch: &str, + tracking: &UpstreamTracking, + tracked_tip: &str, + endpoint: &str, + ) -> Option { + let observations = self.incoming_observations.lock().unwrap_or_else(|p| p.into_inner()); + let observed = observations.branches.get(branch)?; + if &observed.tracked_tip.tracking != tracking + || observed.tracked_tip.commit != tracked_tip + || observations.endpoints.get(&tracking.remote)? != endpoint + { + return None; + } + Some(observed.advertised_commit.clone()) + } + + fn read_incoming_refs( + &self, + endpoints: &mut HashMap, + cancel: &CancellationToken, + ) -> IdeResult { + let repo = self.gix()?; + let remotes = repo.remote_names(); + let mut by_remote: BTreeMap> = BTreeMap::new(); + for reference in repo.references().map_err(repo::gx)?.local_branches().map_err(repo::gx)? { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let reference = reference.map_err(repo::gx)?; + if reference.target().try_name().is_some() { + continue; + } + let name = reference.name(); + let Some(tracking) = refs::configured_upstream(&repo, name) else { continue }; + if !remotes.iter().any(|remote| remote.as_bstr() == tracking.remote.as_str()) { + continue; + } + let Some((_, tip)) = refs::upstream_of(&repo, name) else { continue }; + by_remote + .entry(tracking.remote.clone()) + .or_default() + .push((repo::to_string(name.shorten()), TrackedTip { tracking, commit: tip.to_string() })); + } + + let mut branches = Vec::new(); + let mut errors = Vec::new(); + for (remote, tracked) in by_remote { + let mut refs: Vec<_> = + tracked.iter().map(|(_, tip)| format!("refs/heads/{}", tip.tracking.branch)).collect(); + refs.sort_unstable(); + refs.dedup(); + let advertised = match remote_fetch_url(self, &remote, cancel) + .and_then(|url| self.advertised_heads(&remote, &refs, cancel).map(|advertised| (url, advertised))) + { + Ok(advertised) => advertised, + Err(error) if error.kind == ErrorKind::Cancelled => return Err(error), + Err(error) => { + errors.push(IncomingRemoteError { remote, error }); + continue; + } + }; + let (endpoint, advertised) = advertised; + let before = branches.len(); + for (branch, tracked_tip) in tracked { + let Some(commit) = advertised.get(tracked_tip.tracking.branch.as_str()) else { continue }; + if *commit != tracked_tip.commit { + branches.push(UnfetchedBranch { branch, tracked_tip, advertised_commit: commit.clone() }); + } + } + if branches.len() > before { + if remote_fetch_url(self, &remote, cancel).is_ok_and(|url| url == endpoint) { + endpoints.insert(remote, endpoint); + } else { + branches.truncate(before); + } + } + } + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + Ok(IncomingRefsReport { branches, errors }) + } + + fn advertised_heads( + &self, + remote: &str, + refs: &[String], + cancel: &CancellationToken, + ) -> IdeResult> { + let base = ["ls-remote", "--heads", "--refs", "--", remote]; + let mut heads = HashMap::new(); + for batch in cli::batch_paths(cli::base_command_line_len(&base), refs, 16 * 1024) { + let mut args = base.to_vec(); + args.extend(batch.iter().map(String::as_str)); + let output = cli::run_with_saved_credentials(self.root(), &args, cancel)?; + for line in output.stdout_str().lines() { + let Some((commit, reference)) = line.split_once('\t') else { continue }; + let Some(branch) = reference.strip_prefix("refs/heads/") else { continue }; + if let Ok(commit) = gix::ObjectId::from_hex(commit.as_bytes()) { + heads.insert(branch.to_owned(), commit.to_string()); + } + } + } + Ok(heads) + } +} diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index e1c59fa66..a32d6255b 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -3,10 +3,12 @@ //! hooks, credentials and signing behave exactly as on the command line. use ide_core::ignored::IgnoredNames; +use ide_core::workflow_settings::{EmptyCherryPickAction, FetchTagsMode, GitAnnotateSettings}; use ide_core::{CancellationToken, IdeError, IdeResult}; use serde::{Deserialize, Serialize}; use specta::Type; use std::path::{Path, PathBuf}; +use std::time::Instant; pub use text_encoding::TextEncoding; pub use write::PendingChange; @@ -34,6 +36,22 @@ pub struct FileStatus { pub renamed_from: Option, } +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum StagingPatchSide { + Staged, + Unstaged, + Both, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct StagingPatchEntry { + pub path: ide_core::IpcPath, + pub renamed_from: Option, + pub side: StagingPatchSide, +} + #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct BranchInfo { @@ -41,10 +59,43 @@ pub struct BranchInfo { pub head: Option, pub head_commit: Option, pub upstream: Option, + /// The upstream as configured on the current branch, even before its tracking ref is fetched. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub upstream_tracking: Option, + #[serde(default)] + #[specta(optional)] + pub tracked_tip: Option, pub ahead: u32, pub behind: u32, + /// Outgoing commits to the default Push destination, when it has a local tracking ref. + #[serde(default)] + #[specta(optional)] + pub outgoing: Option, /// Merge / rebase / cherry-pick in progress. pub operation: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rebase: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +pub struct UpstreamTracking { + pub remote: String, + pub branch: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +pub struct TrackedTip { + pub tracking: UpstreamTracking, + pub commit: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +pub struct OutgoingCommits { + pub remote: String, + pub branch: String, + /// Full local tracking ref, which may use a custom fetch refspec. + pub reference: String, + pub count: u32, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] @@ -76,6 +127,10 @@ pub struct BlameLine { pub author: String, pub time_ms: f64, pub summary: String, + /// The file blamed for this line when it had another path in the attributed commit. + #[serde(skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub origin_path: Option, } /// History for Selection: the commits that changed a block of lines, newest first. @@ -254,8 +309,14 @@ pub struct Branch { pub remote: bool, pub current: bool, pub upstream: Option, + #[serde(default)] + #[specta(optional)] + pub tracked_tip: Option, pub ahead: u32, pub behind: u32, + #[serde(default)] + #[specta(optional)] + pub outgoing: Option, pub last_commit_ms: f64, /// Tip commit id. #[serde(default)] @@ -281,6 +342,9 @@ pub struct BranchUpdate { pub status: BranchUpdateStatus, /// Why it failed. pub message: Option, + /// Linked worktree where the update was attempted. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub worktree: Option, } /// Commit Options (IDEA's commit options popup). @@ -288,9 +352,15 @@ pub struct BranchUpdate { #[serde(rename_all = "camelCase")] pub struct CommitOptions { pub amend: bool, + /// Amend this older commit instead of HEAD, with the history snapshot selected in the UI. + #[serde(default)] + pub amend_target: Option, pub sign_off: bool, /// `--author`, e.g. `Name `; `None` or blank uses the configured user. pub author: Option, + /// Explicit Git author date, e.g. an ISO 8601 timestamp with a time zone. + #[serde(default)] + pub author_date: Option, /// False skips the pre-commit and commit-msg hooks (`--no-verify`). pub run_hooks: bool, /// Files committed with only some of their changes (IDEA's partial commit). They are @@ -306,6 +376,16 @@ pub struct CommitOptions { pub exclude: Vec, } +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct AmendTarget { + pub commit: String, + pub head: HistoryTip, + /// Remote-tracking branch names protected from history rewrites. + #[serde(default)] + pub protected_branches: Vec, +} + /// A file of a partial commit: which of its changes against HEAD to commit. #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -313,6 +393,39 @@ pub struct PartialCommitFile { pub path: ide_core::IpcPath, /// The hunks to commit, as [`diff_hunks`] of the HEAD and on-disk texts reports them. pub hunks: Vec, + /// Hunks whose added and removed lines have individual inclusion. + #[serde(default)] + #[specta(optional)] + pub line_hunks: Vec, + /// Before-commit edits against the exact text selected by these hunks. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub prepared: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +pub struct PreparedPartialCommit { + /// LF version of the selected text before running the language server. + pub before: String, + pub text: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PartialCommitHunk { + pub range: HunkRange, + /// The normalised texts that the user selected from, used to detect stale selections. + pub old_text: String, + pub new_text: String, + /// Included deletions and additions, 0-based offsets within their respective sides. + pub deletions: Vec, + pub additions: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +pub struct LargeCommitFile { + pub path: ide_core::IpcPath, + pub size: u64, } /// A hunk identified by its line ranges (0-based), see [`LineHunk`]. @@ -388,6 +501,30 @@ pub struct Stash { pub id: String, /// The commit the stash was made on (the stash commit's first parent). pub base: Option, + /// The stash's third parent, when untracked files were included. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub untracked: Option, +} + +impl Stash { + pub(crate) fn same_entry(&self, other: &Self) -> bool { + self.id == other.id && self.message == other.message && self.time_ms == other.time_ms + } +} + +/// Applying or popping a stash can leave the working tree with conflicts. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum StashApplyOutcome { + Done, + Conflicts { repository: ide_core::IpcPath }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +pub struct StashApplyResult { + /// The entry's position when the operation started. + pub index: u32, + pub outcome: StashApplyOutcome, } /// Push dialog › Push tags: every tag, or only annotated tags on the pushed commits. @@ -479,10 +616,10 @@ pub struct ShelvedChangeList { pub time_ms: f64, /// Branch checked out when the changes were shelved. pub branch: Option, - /// Repository owning the patch; absent in legacy shelves. + /// Path base of the patch: the owning repository or a common directory for multiple repositories. #[serde(default)] pub repo: Option, - /// Repository-relative paths. + /// Paths relative to the patch base. pub files: Vec, } @@ -499,6 +636,25 @@ pub struct PatchFile { pub binary: bool, /// Applies cleanly to the working tree (otherwise a 3-way merge is attempted). pub applies: bool, + #[serde(default)] + pub missing_base: bool, +} + +#[derive(Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PatchFileDiff { + pub path: ide_core::IpcPath, + pub old_path: Option, + pub content: PatchDiffContent, +} + +#[derive(Debug, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum PatchDiffContent { + Text { before: Option, after: Option }, + Conflict { local: Option, base: Option, patched: Option }, + Raw { local: Option, patch: String, applies: bool }, + Binary, } #[derive(Clone, Debug, Default, Serialize, Deserialize, Type)] @@ -547,8 +703,7 @@ pub struct CheckoutOptions { pub ignore_other_worktrees: bool, } -/// Result of [`Repo::checkout_with`]; the non-`Done` variants other than `Conflicts` -/// left the repository untouched. +/// Result of [`Repo::checkout_with`]. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(tag = "kind", rename_all = "camelCase")] pub enum CheckoutOutcome { @@ -574,6 +729,10 @@ pub enum CheckoutOutcome { Conflicts { files: Vec, }, + /// Switched, but the saved changes could not be restored. + RestoreFailed { + message: String, + }, /// Git refused: `branch` is checked out in the linked worktree at `path`. Nothing /// changed; the branch can be worked on there. CheckedOutInWorktree { @@ -582,6 +741,12 @@ pub enum CheckoutOutcome { }, } +impl CheckoutOutcome { + fn switched(&self) -> bool { + matches!(self, Self::Done | Self::Conflicts { .. } | Self::RestoreFailed { .. }) + } +} + /// HEAD before and after a history rewrite, for its Undo. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -590,6 +755,65 @@ pub struct HeadChange { pub after: String, } +/// The branch tip before and after creation, used to roll back a partially successful operation. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct BranchCreation { + pub tip: String, + pub previous_tip: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +pub struct BranchCreationOutcome { + pub checkout: CheckoutOutcome, + /// Present once the branch was created, even if restoring local changes needs attention. + pub created: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +pub struct RewrittenCommit { + pub head: HeadChange, + pub commit: String, +} + +/// Branch and tip confirmed in the UI before editing history. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +pub struct HistoryTip { + pub branch: Option, + pub commit: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +pub struct RebaseState { + pub original: HistoryTip, + pub onto: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +pub struct BranchRebasePlan { + pub head: HistoryTip, + pub target: String, + pub onto: String, +} + +/// The refs shown before checking out and rebasing a branch onto the current branch. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct CheckoutRebasePlan { + pub base: HistoryTip, + pub branch: String, + pub branch_tip: Option, + pub remote: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct CheckoutRebaseRemote { + pub name: String, + pub commit: String, + pub drop_local_commits: bool, +} + /// A deleted local branch, enough to restore it (IDEA's "Restore" notification action). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -599,7 +823,13 @@ pub struct DeletedBranch { pub tip: String, /// Its upstream (`origin/x`), restored with it. pub upstream: Option, - /// It was not fully merged: its own commits are now unreachable from any branch. + /// Configured remote and source branch, if the upstream is remote. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub remote_upstream: Option, + /// Tip that Git compared the deleted branch with when deciding it was unmerged. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub unmerged_base: Option, + /// Git required a force delete because the branch was not fully merged. pub unmerged: bool, } @@ -632,10 +862,21 @@ pub struct MergeSides { pub other_branch: Option, } +/// Which version the user accepts, relative to the merge editor's labels. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum ConflictSide { + Ours, + Theirs, +} + /// The versions of a conflicted file as the merge editor shows them. #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct MergeVersions { + /// Binary versions are available for whole-file acceptance, without decoding their data. + #[serde(default)] + pub binary: bool, pub base: Option, /// The user's side ("Accept Yours"): git's stage 2, or stage 3 when `sides.reversed`. pub ours: Option, @@ -654,6 +895,8 @@ pub struct Changelist { pub name: String, #[serde(default)] pub comment: String, + #[serde(default)] + pub applied_commit: Option, } /// User change lists of a project and which list each changed file belongs to. @@ -673,8 +916,16 @@ mod bek; mod blame; mod block_history; pub mod changelists; +mod cherry_pick_plan; mod cli; +mod commit_message; +mod commit_rewrite; +pub use commit_message::{ + ApplyCommitOptions, ApplyCommitReview, CommitApplyKind, CommitApplySource, CommitMessageWatch, CommitMessages, + PendingCommitApply, +}; mod compare; +mod conflict_resolution; mod diff; mod external_diff; mod history; @@ -685,35 +936,63 @@ mod manage; mod ops; mod patch; mod preserve; +mod push_preview; +mod push_report; +mod rebase_editor; +mod worktree_config; pub use ops::UNSTAGED_CHANGES_PREVENT_REBASE; +mod incoming; mod refs; mod remotes; mod repo; +pub use repo::DiffEntry; mod roots; pub use compare::{CompareResult, CompareScope, RepositoryComparison, WorkingTreeChange}; pub mod shelf; +mod signing; +mod staged_text; mod status; +mod submodules; pub use index_writes::is_own_index_write; +pub use submodules::SubmoduleRollbackSource; mod text_encoding; mod write; pub use backend::Backend; +pub use cherry_pick_plan::CherryPickOptions; pub use cli::{ GitCommandObserver, detected_git_executable, filter_overrides_from, git_version, restrict, set_askpass_env, set_default_git_executable, set_git_command_observer, }; pub use diff::build_partial_patch; pub use external_diff::{ExternalDiffSide, launch_external_diff}; +pub use ide_core::error::{PushRefResult, PushRefStatus, PushReport}; pub use ignore::{IgnoreDestination, add_to_ignore}; -pub use manage::{MergeOptions, RebaseOptions, RemoteEdit, Worktree}; -pub use remotes::Remote; -pub use roots::Repos; +pub use incoming::IncomingRefsReport; +pub use manage::{MergeOptions, MergeOutcome, RebaseOptions, RemoteEdit, Worktree}; +pub use patch::{ + MappedPatch, PatchDirectoryMatches, PatchDirectoryScope, PatchPathMapping, PatchPlacement, ProjectPatch, + discover_patch_directories, rebase_patch, +}; +pub use push_preview::{ + CommitPushTarget, DefaultPushTarget, PushInspection, PushSelection, PushTargetChoices, PushTargetState, +}; +pub use rebase_editor::{ + RebaseEdit, RebaseEditKind, RebaseEditorOperation, RebaseEditorReply, RebaseFixupMessage, RebaseTodoRow, +}; +pub use remotes::{FetchReport, Remote}; +pub use roots::{ProjectUpdateTarget, Repos}; +pub use signing::{GitSigningConfig, GitSigningEdit, GpgSigningKey}; +pub use staged_text::{StagedText, StagedTextEdit, StagingLineHunk, StagingLineHunks}; -fn clone_args(url: &str, dest: &str, depth: Option) -> IdeResult> { +fn clone_args(url: &str, dest: &str, depth: Option, recurse_submodules: bool) -> IdeResult> { if depth == Some(0) { return Err(IdeError::invalid("clone depth must be greater than zero")); } let mut args = vec!["-c".into(), "core.hooksPath=".into(), "clone".into(), "--progress".into()]; + if recurse_submodules { + args.push("--recurse-submodules".into()); + } if let Some(depth) = depth { args.extend(["--depth".into(), depth.to_string()]); } @@ -727,6 +1006,7 @@ pub fn clone( url: &str, dest: &Path, depth: Option, + recurse_submodules: bool, cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { @@ -738,7 +1018,7 @@ pub fn clone( let cwd = tempfile::tempdir()?; // No repository's config applies in that empty folder, so the user's git runs as it is. let _scope = ExecutionScope::enter(true); - let args = clone_args(url, &dest, depth)?; + let args = clone_args(url, &dest, depth, recurse_submodules)?; let args: Vec<&str> = args.iter().map(String::as_str).collect(); cli::run_streaming(cwd.path(), &args, cancel, on_output) } @@ -750,16 +1030,17 @@ mod clone_tests { #[test] fn builds_full_and_shallow_clone_commands() { assert_eq!( - clone_args("https://example.test/repo.git", "/tmp/repo", None).unwrap(), + clone_args("https://example.test/repo.git", "/tmp/repo", None, false).unwrap(), ["-c", "core.hooksPath=", "clone", "--progress", "--", "https://example.test/repo.git", "/tmp/repo"] ); assert_eq!( - clone_args("https://example.test/repo.git", "/tmp/repo", Some(3)).unwrap(), + clone_args("https://example.test/repo.git", "/tmp/repo", Some(3), true).unwrap(), [ "-c", "core.hooksPath=", "clone", "--progress", + "--recurse-submodules", "--depth", "3", "--", @@ -767,7 +1048,7 @@ mod clone_tests { "/tmp/repo", ] ); - assert!(clone_args("https://example.test/repo.git", "/tmp/repo", Some(0)).is_err()); + assert!(clone_args("https://example.test/repo.git", "/tmp/repo", Some(0), true).is_err()); } } @@ -795,11 +1076,27 @@ pub struct Repo { ignored: std::sync::RwLock, /// Working-tree status from `git status` instead of gitoxide. cli_status: std::sync::atomic::AtomicBool, + automatic_shelf: std::sync::RwLock>, log_index: std::sync::Mutex, - log_signatures: std::sync::Mutex>, + log_signatures: std::sync::Mutex, + conflict_mutation: std::sync::Mutex<()>, + amend_recovery: std::sync::Mutex>, + incoming_observations: std::sync::Mutex, } impl Repo { + /// Uses the project's Shelf for automatic preservation when configured by the host. + pub fn set_automatic_shelf(&self, directory: Option, changelist_root: Option) { + *self.automatic_shelf.write().unwrap_or_else(|poison| poison.into_inner()) = + directory.map(|directory| shelf::AutomaticShelf { directory, changelist_root }); + } + + /// Restores this batch's pending Shelf after its repository commands have returned. + pub fn finish_shelf_batch(&self, batch: &str) -> IdeResult<()> { + let _scope = self.execution_scope(); + preserve::finish_batch(self, batch) + } + /// Discovers the repository containing `path`; `Ok(None)` when not under git. The /// repository is in Restricted Mode until [`Repo::set_execution_allowed`] says otherwise. pub fn discover(path: &Path) -> IdeResult> { @@ -832,6 +1129,10 @@ impl Repo { let _scope = self.execution_scope(); status::status(self) } + pub fn ignored_files(&self) -> IdeResult> { + let _scope = self.execution_scope(); + status::ignored_files(self) + } /// Status of `paths` only (absolute; those outside the repository are ignored), for the /// dirty-scope refresh after a watcher batch. An empty list is the full status. pub fn status_paths(&self, paths: &[PathBuf]) -> IdeResult> { @@ -865,6 +1166,10 @@ impl Repo { let _scope = self.execution_scope(); Ok(refs::operation(&self.gix()?)) } + /// Whether Git is running an interactive rebase in this worktree. + pub fn is_interactive_rebase(&self) -> bool { + refs::rebase_dir(&self.git_dir).is_some_and(|dir| dir.join("interactive").is_file()) + } /// Content of `path` at `rev` (default HEAD); `None` if absent there. /// `rev` may be any revision git understands, or `":"` / `":0"` for the index. pub fn file_at( @@ -948,9 +1253,25 @@ impl Repo { revision: Option<&str>, encoding: impl Into, ) -> IdeResult> { - let encoding = encoding.into(); + self.blame_with_options( + path, + current_text, + revision, + encoding.into(), + GitAnnotateSettings { ignore_whitespace: false, ..GitAnnotateSettings::default() }, + ) + } + + pub fn blame_with_options( + &self, + path: &Path, + current_text: Option<&str>, + revision: Option<&str>, + encoding: TextEncoding, + options: GitAnnotateSettings, + ) -> IdeResult> { let _scope = self.execution_scope(); - write::blame(self, path, current_text, revision, encoding) + write::blame(self, path, current_text, revision, encoding, options) } /// Adds `commit` to the list `blame.ignoreRevsFile` names, so annotate skips it; with none /// configured, to `.git-blame-ignore-revs` at the worktree root, which the local config then names. @@ -987,6 +1308,16 @@ impl Repo { let _scope = self.execution_scope(); history::log(self, query, cancel) } + /// Commits unique to `source` that have no equivalent on `target`; `None` if a ref is absent. + pub fn not_cherry_picked( + &self, + source: &str, + target: &str, + cancel: &CancellationToken, + ) -> IdeResult>> { + let _scope = self.execution_scope(); + history::not_cherry_picked(self, source, target, cancel) + } /// Enables the disposable, content-addressed log cache outside the worktree. pub fn enable_log_index(&self, cache_dir: &Path) { let key = blake3::hash(self.git_dir.to_string_lossy().as_bytes()).to_hex().to_string(); @@ -1021,18 +1352,27 @@ impl Repo { .next() .ok_or_else(|| IdeError::not_found("commit not found")) } + + pub fn invalidate_log_signatures(&self) { + self.log_signatures.lock().unwrap_or_else(|p| p.into_inner()).clear(); + } + pub fn log_details_batch_cancellable( &self, revisions: &[String], cancel: &CancellationToken, ) -> IdeResult> { - let allowed = self.execution_allowed.load(std::sync::atomic::Ordering::Acquire); let _scope = self.execution_scope(); + let allowed = crate::execution_allowed(); let repo = self.gix()?; let shallow: std::collections::HashSet = repo.shallow_commits().map_err(repo::gx)?.map(|ids| ids.iter().copied().collect()).unwrap_or_default(); let mut out = Vec::with_capacity(revisions.len()); let mut commit_ids = Vec::with_capacity(revisions.len()); + let mut verify = std::collections::HashSet::new(); + let mut uncached = Vec::new(); + let now = Instant::now(); + let generation = self.log_signatures.lock().unwrap_or_else(|p| p.into_inner()).generation; for revision in revisions { if cancel.is_cancelled() { return Err(IdeError::cancelled()); @@ -1044,48 +1384,37 @@ impl Repo { .map_err(repo::gx)?; let commit_id = object.id; commit_ids.push(commit_id); - let id = commit_id.to_string(); - let cache_key = format!("{allowed}:{id}"); - let cached = self.log_signatures.lock().unwrap_or_else(|p| p.into_inner()).get(&cache_key).cloned(); - let details = if let Some(details) = cached { - details - } else { - let end = object.data.windows(2).position(|s| s == b"\n\n").unwrap_or(object.data.len()); - let headers = &object.data[..end]; - let signed = - headers.windows(8).any(|s| s == b"\ngpgsig ") || headers.windows(8).any(|s| s == b"\ngpgsig-"); - let output = if allowed && signed { - Some(cli::run_cancellable( - self.root(), - &["log", "-1", "--format=%G?%x00%GS%x00%GK%x00%GF", "--end-of-options", &id], - cancel, - )?) - } else { - None - }; - let text = output.as_ref().map(|out| out.stdout_str()).unwrap_or_default(); - let fields: Vec<_> = text.trim_end().split('\0').collect(); - let message = { - let mut index = self.log_index.lock().unwrap_or_else(|p| p.into_inner()); - index.message(&repo, commit_id)? - }; - let details = LogDetails { - message, - containing_branches: Vec::new(), - signature: if !signed { - "N".into() - } else { - fields.first().filter(|s| !s.is_empty()).unwrap_or(&"E").to_string() - }, - signer: fields.get(1).unwrap_or(&"").to_string(), - key: fields.get(2).unwrap_or(&"").to_string(), - fingerprint: fields.get(3).unwrap_or(&"").to_string(), - }; - self.log_signatures.lock().unwrap_or_else(|p| p.into_inner()).insert(cache_key, details.clone()); - details + let end = object.data.windows(2).position(|s| s == b"\n\n").unwrap_or(object.data.len()); + let headers = &object.data[..end]; + let signed = headers.windows(8).any(|s| s == b"\ngpgsig " || s == b"\ngpgsig-"); + let message = self.log_index.lock().unwrap_or_else(|p| p.into_inner()).message(&repo, commit_id)?; + let mut details = LogDetails { + message, + containing_branches: Vec::new(), + signature: if signed { "E" } else { "N" }.into(), + signer: String::new(), + key: String::new(), + fingerprint: String::new(), }; + if allowed && signed { + let cache = self.log_signatures.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(signature) = cache.get(&commit_id, now) { + signature.apply(&mut details); + } else { + verify.insert(commit_id); + uncached.push(out.len()); + } + } out.push(details); } + let checked_at = Instant::now(); + let signatures = history::log_signatures(self.root(), &verify, cancel)?; + for i in uncached { + if let Some(signature) = signatures.get(&commit_ids[i]) { + signature.apply(&mut out[i]); + } + } + self.log_signatures.lock().unwrap_or_else(|p| p.into_inner()).store(generation, checked_at, signatures); let branches_per_commit = { let mut index = self.log_index.lock().unwrap_or_else(|p| p.into_inner()); let res = index.containing_branches_batch(&repo, &commit_ids, &shallow, cancel)?; @@ -1145,6 +1474,15 @@ impl Repo { let _scope = self.execution_scope(); history::commits_changes(self, commits) } + /// The combined changes of a selection whose display order can differ from history. + pub fn commit_selection_changes( + &self, + commits: &[String], + cancel: &CancellationToken, + ) -> IdeResult> { + let _scope = self.execution_scope(); + history::commit_selection_changes(self, commits, cancel) + } /// Local and remote branches; the current branch first, then most recent first. pub fn branches(&self) -> IdeResult> { let _scope = self.execution_scope(); @@ -1196,6 +1534,19 @@ impl Repo { Ok((out.code == Some(0)).then(|| out.stdout_str().trim().to_string())) } + /// Reads a boolean in Git's own config syntax, including implicit true. + pub fn config_get_bool(&self, key: &str) -> IdeResult> { + let _scope = self.execution_scope(); + let args = ["config", "--type=bool", "--get", "--", key]; + let out = cli::run_raw(&self.root, &args, None)?; + match (out.code, out.stdout_str().trim()) { + (Some(0), "true") => Ok(Some(true)), + (Some(0), "false") => Ok(Some(false)), + (Some(1), _) if out.stderr.is_empty() => Ok(None), + _ => Err(cli::failure(&args, &out.stderr, &out.stdout, out.code)), + } + } + /// Sets `user.name` and `user.email` for commits: in this repository's config, or in the /// user's global one (`global`). pub fn set_user_identity(&self, name: &str, email: &str, global: bool) -> IdeResult<()> { @@ -1215,10 +1566,19 @@ impl Repo { let _scope = self.execution_scope(); write::stage(self, paths) } + pub fn stage_without_content(&self, paths: &[PathBuf]) -> IdeResult<()> { + let _scope = self.execution_scope(); + write::stage_without_content(self, paths) + } pub fn unstage(&self, paths: &[PathBuf]) -> IdeResult<()> { let _scope = self.execution_scope(); write::unstage(self, paths) } + /// Restores the selected worktree files from the index. + pub fn restore_unstaged(&self, paths: &[PathBuf]) -> IdeResult<()> { + let _scope = self.execution_scope(); + write::restore_unstaged(self, paths) + } /// Applies a unified-diff patch to the index (partial staging of hunks/lines). /// Zero-context patches (see [`build_partial_patch`]) are accepted. pub fn stage_patch>( @@ -1229,6 +1589,30 @@ impl Repo { let _scope = self.execution_scope(); write::stage_patch(self, patch, &|path| encoding(path).map(Into::into)) } + /// Stages a formatter's edits against the index text it started from. + pub fn stage_formatted_text( + &self, + path: &Path, + before: &str, + after: &str, + encoding: impl Into, + ) -> IdeResult<()> { + let encoding = encoding.into(); + let _scope = self.execution_scope(); + let rel = self.rel_path(path)?; + let staged = self + .blob_of(path, ":0")? + .filter(|bytes| !text_encoding::is_binary(bytes, encoding)) + .ok_or_else(|| IdeError::invalid("The selected index text changed"))?; + let staged = text_encoding::decode(&staged, encoding); + if diff::normalize_eol(&staged) != before { + return Err(IdeError::invalid("The selected index text changed")); + } + let hunks = diff::line_hunks(&staged, after); + let selected: Vec<_> = (0..hunks.len()).collect(); + let patch = diff::build_partial_patch(&rel, &staged, after, &selected); + write::stage_patch(self, &patch, &|_| Ok(encoding)) + } /// Discards unstaged changes: tracked paths are restored from the index (staged /// changes are kept), untracked files and directories are deleted. A submodule goes back /// to the commit the index records, with its tracked files restored. @@ -1253,6 +1637,44 @@ impl Repo { let _scope = self.execution_scope(); write::commit(self, message, options, &|path| encoding(path).map(Into::into)) } + /// Appends the commit prepared during a failed earlier Amend. + pub fn keep_amend_commit(&self, commit: &str) -> IdeResult { + let _scope = self.execution_scope(); + commit_rewrite::keep_amend(self, commit) + } + /// The text a partial commit would put in the index, without changing it. + pub fn preview_partial_commit>( + &self, + file: &PartialCommitFile, + encoding: E, + ) -> IdeResult { + let relative = self.rel_path(&file.path.0)?; + write::partial_commit_text(self, &relative, file, encoding.into()).map(|(text, _)| text) + } + + /// Included paths whose selected content contains CRLF without a Git line-ending policy. + pub fn commit_crlf_paths>( + &self, + paths: &[PathBuf], + options: &CommitOptions, + encoding: &dyn Fn(&Path) -> IdeResult, + cancel: &CancellationToken, + ) -> IdeResult> { + let _scope = self.execution_scope(); + write::commit_crlf_paths(self, paths, options, &|path| encoding(path).map(Into::into), cancel) + } + /// Check the selected sources for large files, respecting this repo's Git LFS configuration. + pub fn commit_large_files>( + &self, + paths: &[PathBuf], + options: &CommitOptions, + limit: u64, + encoding: &dyn Fn(&Path) -> IdeResult, + cancel: &CancellationToken, + ) -> IdeResult> { + let _scope = self.execution_scope(); + write::commit_large_files(self, paths, options, limit, &|path| encoding(path).map(Into::into), cancel) + } /// What [`Repo::commit_with`] would commit with `options`, file by file, without /// committing or touching the index: patches against HEAD, `max_bytes` in all. pub fn pending_changes>( @@ -1279,6 +1701,12 @@ impl Repo { let _scope = self.execution_scope(); write::checkout_with(self, branch, create, options) } + /// Finds tracked local changes that may block a switch to `branch` without changing HEAD, + /// the index, or the worktree. + pub fn checkout_affected_files(&self, branch: &str) -> IdeResult> { + let _scope = self.execution_scope(); + write::checkout_affected_files(self, branch) + } /// Creates branch `name` at `start` (default HEAD), optionally switching to it. A /// remote-tracking start point (`origin/x`) becomes the new branch's upstream. pub fn create_branch(&self, name: &str, start: Option<&str>, checkout: bool) -> IdeResult<()> { @@ -1293,8 +1721,48 @@ impl Repo { checkout: bool, overwrite: bool, ) -> IdeResult<()> { + self.create_branch_recorded(name, start, checkout, overwrite, None).map(|_| ()) + } + + pub fn create_branch_recorded( + &self, + name: &str, + start: Option<&str>, + checkout: bool, + overwrite: bool, + expected_tip: Option<&str>, + ) -> IdeResult { + let options = checkout.then(CheckoutOptions::default); + let outcome = self.create_branch_with(name, start, options.as_ref(), overwrite, expected_tip)?; + outcome.created.ok_or_else(|| match outcome.checkout { + CheckoutOutcome::CheckedOutInWorktree { branch, path } => IdeError::invalid(format!( + "branch '{branch}' is already checked out in worktree at '{}'", + path.display() + )), + _ => IdeError::invalid("Could not check out the new branch"), + }) + } + + pub fn create_branch_with( + &self, + name: &str, + start: Option<&str>, + checkout: Option<&CheckoutOptions>, + overwrite: bool, + expected_tip: Option<&str>, + ) -> IdeResult { let _scope = self.execution_scope(); - write::create_branch(self, name, start, checkout, overwrite) + write::create_branch(self, name, start, checkout, overwrite, expected_tip) + } + + pub fn undo_branch_creation( + &self, + name: &str, + created: &BranchCreation, + previous_head: Option<&HistoryTip>, + ) -> IdeResult<()> { + let _scope = self.execution_scope(); + write::undo_branch_creation(self, name, created, previous_head) } /// Undo Commit: resets the current branch to the parent of `commit` (which must be /// HEAD and not a merge) keeping its changes staged; undoing the initial commit @@ -1303,20 +1771,60 @@ impl Repo { let _scope = self.execution_scope(); write::undo_commit(self, commit) } - /// Deletes a local branch (`git branch -d`, `-D` when `force`). /// Edit Commit Message without touching the index or the working tree; returns HEAD /// before and after. pub fn reword(&self, commit: &str, message: &str) -> IdeResult { let _scope = self.execution_scope(); - write::reword(self, commit, message).map(|(before, after)| HeadChange { before, after }) + commit_rewrite::reword(self, commit, message) + } + + /// Move selected file changes into a new commit immediately after the original. + pub fn extract_commit_changes( + &self, + commit: &str, + expected_head: &HistoryTip, + paths: &[PathBuf], + message: &str, + ) -> IdeResult { + let _scope = self.execution_scope(); + commit_rewrite::extract(self, commit, expected_head, paths, message) + } + + /// Removes selected file changes from a commit, replaying later commits on the replacement. + pub fn drop_commit_changes( + &self, + commit: &str, + expected_head: &HistoryTip, + paths: &[PathBuf], + cancel: &CancellationToken, + out: &dyn Fn(String), + ) -> IdeResult { + let _scope = self.execution_scope(); + commit_rewrite::drop_changes(self, commit, expected_head, paths, cancel, out) } /// Undoes a history rewrite: HEAD goes from `after` back to `before`, local changes kept. pub fn restore_head(&self, before: &str, after: &str) -> IdeResult<()> { - let _scope = self.execution_scope(); - write::restore_head(self, before, after) + self.restore_head_on_branch(before, after, None) } + pub fn restore_head_on_branch(&self, before: &str, after: &str, branch: Option<&str>) -> IdeResult<()> { + let _scope = self.execution_scope(); + write::restore_head(self, before, after, branch) + } + + pub fn restore_rebase_checkout( + &self, + before: &str, + after: &str, + branch: &str, + checkout: &HistoryTip, + ) -> IdeResult<()> { + let _scope = self.execution_scope(); + write::restore_rebase_checkout(self, before, after, branch, checkout) + } + + /// Deletes a local branch (`git branch -d`, `-D` when `force`). pub fn delete_branch(&self, branch: &str, force: bool) -> IdeResult<()> { let _scope = self.execution_scope(); write::delete_branch(self, branch, force) @@ -1326,7 +1834,17 @@ impl Repo { /// needs to undo it. pub fn delete_branch_restorable(&self, branch: &str) -> IdeResult { let _scope = self.execution_scope(); - write::delete_branch_restorable(self, branch) + write::delete_branch_restorable(self, branch, None) + } + /// Deletes a local branch selected for cleanup with its remote branch. + pub fn delete_tracking_branch(&self, branch: &str, tip: &str, upstream: &str) -> IdeResult { + let _scope = self.execution_scope(); + write::delete_branch_restorable(self, branch, Some((tip, upstream))) + } + /// Deletes a branch offered for cleanup after a merge, with a tip and HEAD ancestry check. + pub fn delete_merged_branch(&self, branch: &str, expected_tip: &str) -> IdeResult { + let _scope = self.execution_scope(); + write::delete_merged_branch(self, branch, expected_tip) } /// Recreates a deleted branch at its old tip, with its upstream. pub fn restore_branch(&self, deleted: &DeletedBranch) -> IdeResult<()> { @@ -1351,6 +1869,26 @@ impl Repo { let _scope = self.execution_scope(); write::rebase(self, onto) } + + pub fn rebase_branch( + &self, + plan: &BranchRebasePlan, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult { + let _scope = self.execution_scope(); + write::rebase_branch(self, plan, cancel, on_output) + } + /// Rebases the selected branch onto the original HEAD and leaves it checked out. + pub fn checkout_rebase( + &self, + plan: &CheckoutRebasePlan, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult { + let _scope = self.execution_scope(); + write::checkout_rebase(self, plan, cancel, on_output) + } /// `paths` (absolute) stashes only those files; empty stashes the whole working tree. /// `keep_index`: changes already staged stay in the index (and the working tree). pub fn stash_push( @@ -1361,24 +1899,50 @@ impl Repo { paths: &[PathBuf], ) -> IdeResult<()> { let _scope = self.execution_scope(); + let _stash_lock = write::lock_stashes(self)?; write::stash_push(self, message, include_untracked, keep_index, paths) } /// `reinstate_index`: also restore what was staged when the stash was made. - pub fn stash_apply(&self, index: u32, pop: bool, reinstate_index: bool) -> IdeResult<()> { + pub fn stash_apply(&self, index: u32, pop: bool, reinstate_index: bool) -> IdeResult { let _scope = self.execution_scope(); - write::stash_apply(self, index, pop, reinstate_index) + let _stash_lock = write::lock_stashes(self)?; + write::stash_apply(self, &format!("stash@{{{index}}}"), pop, reinstate_index) } /// Creates and checks out `branch` at the commit the stash was made on, applies the /// stash there (index included) and drops it. - pub fn stash_branch(&self, index: u32, branch: &str) -> IdeResult<()> { + pub fn stash_branch(&self, index: u32, branch: &str) -> IdeResult { let _scope = self.execution_scope(); - write::stash_branch(self, index, branch) + let _stash_lock = write::lock_stashes(self)?; + write::stash_branch(self, &format!("stash@{{{index}}}"), branch) + } + /// Restores the selected entry. Pop and branch creation remove it only after a successful restore. + pub fn unstash_selected( + &self, + stash: &Stash, + pop: bool, + reinstate_index: bool, + branch: Option<&str>, + ) -> IdeResult { + let _scope = self.execution_scope(); + write::unstash_selected(self, stash, pop, reinstate_index, branch) } /// Removes `stash@{index}` without applying it. pub fn stash_drop(&self, index: u32) -> IdeResult<()> { let _scope = self.execution_scope(); + let _stash_lock = write::lock_stashes(self)?; write::stash_drop(self, index) } + /// Removes the selected stash, returning the position from which it was removed. + pub fn drop_selected_stash(&self, stash: &Stash) -> IdeResult { + let _scope = self.execution_scope(); + write::drop_selected_stash(self, stash) + } + /// Removes the repository's stash reflog without changing the index or working files. + pub fn stash_clear(&self) -> IdeResult<()> { + let _scope = self.execution_scope(); + let _stash_lock = write::lock_stashes(self)?; + cli::run(self.root(), &["stash", "clear"], None).map(|_| ()) + } /// Deletes a branch on a remote (`git push --delete `); `branch` is the /// remote-tracking name, e.g. `origin/feature`. pub fn delete_remote_branch( @@ -1393,17 +1957,105 @@ impl Repo { /// Network operations stream progress lines through `on_output`. /// Fetches all remotes (pruning deleted branches). pub fn fetch(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { + self.fetch_with_tags(None, FetchTagsMode::Auto, cancel, on_output) + } + pub fn is_shallow(&self) -> IdeResult { + self.gix()?.is_shallow().map_err(repo::gx) + } + /// Fetches the ancestors missing from a shallow checkout using Git's default fetch remote. + pub fn unshallow(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { + self.unshallow_with_tags(FetchTagsMode::Auto, cancel, on_output) + } + + pub fn unshallow_with_tags( + &self, + tags: FetchTagsMode, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult<()> { let _scope = self.execution_scope(); - cli::run_streaming(&self.root, &["fetch", "--progress", "--all", "--prune"], cancel, on_output) + if !self.is_shallow()? { + return Ok(()); + } + let mut args = vec!["fetch", "--progress", "--unshallow"]; + args.extend(remotes::fetch_tag_args(tags, false)); + cli::run_streaming(&self.root, &args, cancel, on_output)?; + if self.is_shallow()? { + return Err(IdeError::invalid("The remote did not provide the full history")); + } + Ok(()) } /// Update Project: pulls the upstream by merge or rebase. Local changes are stashed /// and restored; the merge mode fast-forwards when possible whatever `pull.ff` says. pub fn pull(&self, rebase: bool, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { + self.pull_checked_branch(rebase, None, cancel, on_output) + } + + pub fn pull_checked_branch( + &self, + rebase: bool, + expected_branch: Option<&str>, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult<()> { + self.pull_checked_branch_with_tags(rebase, expected_branch, FetchTagsMode::Auto, cancel, on_output) + } + + pub fn pull_checked_branch_with_tags( + &self, + rebase: bool, + expected_branch: Option<&str>, + tags: FetchTagsMode, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult<()> { + self.pull_with_options(rebase, expected_branch, tags, false, cancel, on_output) + } + + pub fn pull_for_project_update( + &self, + rebase: bool, + tags: FetchTagsMode, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult<()> { + self.pull_with_options(rebase, None, tags, true, cancel, on_output) + } + + fn pull_with_options( + &self, + rebase: bool, + expected_branch: Option<&str>, + tags: FetchTagsMode, + update_project: bool, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult<()> { let _scope = self.execution_scope(); + let tag_config = remotes::pull_tag_config(self, tags)?; + let mut args: Vec<&str> = tag_config.iter().flat_map(|entry| ["-c", entry.as_str()]).collect(); let mode: &[&str] = if rebase { &["--rebase"] } else { &["--no-rebase", "--ff"] }; - let mut args = vec!["pull", "--progress"]; + if update_project { + args.extend(["-c", "submodule.recurse=false"]); + } + args.extend(["pull", "--progress"]); + if update_project { + args.push("--no-recurse-submodules"); + } args.extend_from_slice(mode); + match tags { + FetchTagsMode::Auto => {} + FetchTagsMode::Sync => args.push("--prune"), + FetchTagsMode::Always => args.push("--tags"), + FetchTagsMode::Never => args.push("--no-tags"), + } + if let Some(branch) = expected_branch { + write::require_checked_out_branch(self.root(), branch, cancel)?; + } preserve::around(self, "Local changes saved before update", || { + if let Some(branch) = expected_branch { + write::require_checked_out_branch(self.root(), branch, cancel)?; + } cli::run_streaming(&self.root, &args, cancel, on_output) }) } @@ -1417,6 +2069,7 @@ impl Repo { on_output: &dyn Fn(String), ) -> IdeResult<()> { self.push_with(PushOptions { force_with_lease, set_upstream, ..Default::default() }, cancel, on_output) + .map(drop) } /// [`Repo::push`] that also pushes tags (Push dialog › Push tags). pub fn push_with_tags( @@ -1428,6 +2081,7 @@ impl Repo { on_output: &dyn Fn(String), ) -> IdeResult<()> { self.push_with(PushOptions { force_with_lease, set_upstream, tags, ..Default::default() }, cancel, on_output) + .map(drop) } /// Pushes the current branch with the Push dialog's options. pub fn push_with( @@ -1435,10 +2089,34 @@ impl Repo { options: PushOptions, cancel: &CancellationToken, on_output: &dyn Fn(String), - ) -> IdeResult<()> { + ) -> IdeResult { let _scope = self.execution_scope(); write::push(self, options, cancel, on_output) } + /// Pushes the exact source and destination chosen in the Push dialog. + pub fn push_selected( + &self, + selection: &PushSelection, + inspected: Option<&PushInspection>, + options: PushOptions, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult { + let _scope = self.execution_scope(); + write::push_selected(self, selection, inspected, options, cancel, on_output) + } + /// Repeats a rejected push with the exact lease reviewed in the dialog. + pub fn force_push_rejected( + &self, + divergence: &ide_core::error::PushDivergence, + tags: Option, + no_verify: bool, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult { + let _scope = self.execution_scope(); + write::force_push_rejected(self, divergence, tags, no_verify, cancel, on_output) + } /// Whether the repository has an executable hook `name` (e.g. `pre-push`), wherever /// `core.hooksPath` puts it: the Push dialog then offers to skip it. pub fn has_hook(&self, name: &str) -> IdeResult { @@ -1463,6 +2141,7 @@ impl Repo { cancel, on_output, ) + .map(drop) } /// [`Repo::push_branch`] to remote branch `target` (None keeps the upstream's name) /// and/or remote `remote` (None keeps the upstream's remote). The Push dialog's @@ -1473,48 +2152,108 @@ impl Repo { options: PushBranchOptions<'_>, cancel: &CancellationToken, on_output: &dyn Fn(String), - ) -> IdeResult<()> { + ) -> IdeResult { let _scope = self.execution_scope(); write::push_branch(self, branch, options, cancel, on_output) } /// Update Project › Reset to the Remote Branch: the current branch is moved to its /// freshly fetched tracked branch; local commits are dropped, local changes kept. pub fn reset_to_upstream(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { - let _scope = self.execution_scope(); - write::reset_to_upstream(self, cancel, on_output) + self.reset_to_upstream_with_tags(FetchTagsMode::Auto, cancel, on_output) } - /// Branches › Update Selected: fetches each remote once and fast-forwards every - /// branch to its upstream, reporting the branches it could not update. + + pub fn reset_to_upstream_with_tags( + &self, + tags: FetchTagsMode, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult<()> { + let _scope = self.execution_scope(); + write::reset_to_upstream(self, tags, cancel, on_output) + } + /// Fast-forwards the requested branches to their upstreams, including branches + /// checked out in a linked worktree. Fetches each remote once. pub fn update_branches( &self, branches: &[String], cancel: &CancellationToken, on_output: &dyn Fn(String), + ) -> IdeResult> { + self.update_branches_with_tags(branches, FetchTagsMode::Auto, cancel, on_output) + } + + pub fn update_branches_with_tags( + &self, + branches: &[String], + tags: FetchTagsMode, + cancel: &CancellationToken, + on_output: &dyn Fn(String), ) -> IdeResult> { let _scope = self.execution_scope(); - write::update_branches(self, branches, cancel, on_output) + write::update_branches(self, branches, tags, cancel, on_output) } // ---- in-progress operations, history rewriting, tags ---- /// Continues the merge / rebase / cherry-pick / revert in progress; fails while /// conflicts are unresolved. pub fn continue_operation(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { - let _scope = self.execution_scope(); - ops::continue_op(self, false, cancel, on_output) + self.continue_operation_with(false, EmptyCherryPickAction::default(), cancel, on_output).map(|_| ()) } /// Stage and Retry: stages the changes of tracked files, then continues. pub fn stage_and_continue(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { + self.continue_operation_with(true, EmptyCherryPickAction::default(), cancel, on_output).map(|_| ()) + } + /// Continues the operation and reports the number of empty picks handled during it. + pub fn continue_operation_with( + &self, + stage: bool, + empty_action: EmptyCherryPickAction, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult { let _scope = self.execution_scope(); - ops::continue_op(self, true, cancel, on_output) + ops::continue_op(self, stage, |args| { + cherry_pick_plan::resume(self, args, None, empty_action, cancel, on_output) + }) + } + /// Finishes the merge reviewed in the conflict resolver, using its prepared message. + pub fn finish_merge( + &self, + branch: Option<&str>, + head: &str, + target: &str, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult<()> { + let _scope = self.execution_scope(); + ops::finish_merge(self, branch, head, target, cancel, on_output) } pub fn abort_operation(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { + self.abort_expected_operation(None, cancel, on_output) + } + /// Aborts the operation in progress if it matches the operation the caller confirmed. + pub fn abort_expected_operation( + &self, + expected: Option<&str>, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult<()> { let _scope = self.execution_scope(); - ops::abort_op(self, cancel, on_output) + ops::abort_op(self, expected, cancel, on_output) } /// Skips the current commit of a rebase / cherry-pick / revert. pub fn skip_operation(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { + self.skip_operation_with(EmptyCherryPickAction::default(), cancel, on_output).map(|_| ()) + } + /// Skips the current step and handles empty picks later in the sequence. + pub fn skip_operation_with( + &self, + empty_action: EmptyCherryPickAction, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult { let _scope = self.execution_scope(); - ops::skip_op(self, cancel, on_output) + ops::skip_op(self, |args| cherry_pick_plan::resume(self, args, None, empty_action, cancel, on_output)) } /// Cherry-picks `commits` in order (oldest first). Stops mid-way on conflicts. pub fn cherry_pick( @@ -1533,8 +2272,30 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { + let options = CherryPickOptions { record_origin, ..Default::default() }; + self.cherry_pick_with_options(commits, options, cancel, on_output).map(|_| ()) + } + /// Cherry-picks oldest first, adding Git's origin line to the specified commits. + pub fn cherry_pick_with_origins( + &self, + commits: &[String], + origins: &[String], + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult<()> { + let options = CherryPickOptions { record_origin_for: origins, ..Default::default() }; + self.cherry_pick_with_options(commits, options, cancel, on_output).map(|_| ()) + } + /// Cherry-picks oldest first and reports the number of empty picks handled. + pub fn cherry_pick_with_options( + &self, + commits: &[String], + options: CherryPickOptions<'_>, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult { let _scope = self.execution_scope(); - ops::cherry_pick(self, commits, record_origin, cancel, on_output) + cherry_pick_plan::start(self, commits, options, cancel, on_output) } /// Reverts `commits` in order (newest first) with git's default messages. pub fn revert(&self, commits: &[String], cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { @@ -1587,7 +2348,7 @@ impl Repo { remote: &str, cancel: &CancellationToken, on_output: &dyn Fn(String), - ) -> IdeResult<()> { + ) -> IdeResult { let _scope = self.execution_scope(); ops::push_tag(self, tag, remote, false, cancel, on_output) } @@ -1600,7 +2361,17 @@ impl Repo { on_output: &dyn Fn(String), ) -> IdeResult<()> { let _scope = self.execution_scope(); - ops::push_tag(self, tag, remote, true, cancel, on_output) + ops::push_tag(self, tag, remote, true, cancel, on_output).map(drop) + } + /// Deletes a locally removed tag on the configured remotes only at its original tip. + pub fn delete_tag_on_remotes( + &self, + deleted: &DeletedTag, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult<()> { + let _scope = self.execution_scope(); + ops::delete_tag_on_remotes(self, deleted, cancel, on_output) } pub fn tags(&self) -> IdeResult> { let _scope = self.execution_scope(); @@ -1637,19 +2408,48 @@ impl Repo { let rel = self.rel_paths(paths)?; Ok(patch::working_patch(self, &rel, reverse, true)?.0) } + /// Patch of the selected sides of the index, with paths relative to the export base. + pub fn create_staging_patch( + &self, + entries: &[StagingPatchEntry], + reverse: bool, + prefix: &str, + ) -> IdeResult { + let _scope = self.execution_scope(); + patch::staging_patch(self, entries, reverse, prefix) + } /// Patch of the changes made by `commits` (oldest first). pub fn create_commits_patch(&self, commits: &[String], reverse: bool) -> IdeResult { let _scope = self.execution_scope(); patch::commits_patch(self, commits, reverse) } + /// A binary-safe patch of the selected files between two revisions. + pub fn create_revisions_patch(&self, before: &str, after: &str, paths: &[PathBuf]) -> IdeResult { + let _scope = self.execution_scope(); + patch::revisions_patch(self, before, after, paths) + } pub fn patch_preview(&self, patch: &str) -> IdeResult> { let _scope = self.execution_scope(); patch::preview(self, patch) } + pub fn patch_file_diff( + &self, + patch: &str, + path: &str, + encoding: &dyn Fn(&Path, &[u8]) -> TextEncoding, + ) -> IdeResult { + let _scope = self.execution_scope(); + patch::file_diff::generate(self, patch, path, "", encoding) + } /// Applies a patch to the working tree, 3-way merging when it does not apply cleanly. pub fn apply_patch(&self, patch: &str) -> IdeResult { let _scope = self.execution_scope(); - patch::apply(self, patch) + patch::apply_for_review(self, patch, "") + } + /// Applies the file sections with the selected destination paths. + pub fn apply_selected_patch(&self, patch: &str, paths: &[String]) -> IdeResult { + let _scope = self.execution_scope(); + patch::apply_selected(self, patch, paths) } /// Saves the changes of `paths` under `shelf_dir` and reverts them. pub fn shelve(&self, shelf_dir: &Path, name: &str, paths: &[PathBuf]) -> IdeResult { @@ -1667,19 +2467,40 @@ impl Repo { let _scope = self.execution_scope(); ops::merge_sides(self) } + + /// Files with saved resolutions from an ongoing Git operation. + pub fn resolved_conflicts(&self) -> IdeResult> { + let _scope = self.execution_scope(); + conflict_resolution::resolved_paths(self) + } + + /// Restores the original conflict stages and worktree contents for resolved files. + pub fn revert_resolved_conflicts(&self, paths: &[PathBuf]) -> IdeResult<()> { + let _scope = self.execution_scope(); + conflict_resolution::revert_resolved(self, paths) + } + /// Resolves each selected path using the chosen index stage, including its mode or deletion. + pub fn accept_conflict_side(&self, paths: &[PathBuf], side: ConflictSide) -> IdeResult<()> { + let _scope = self.execution_scope(); + conflict_resolution::accept_side(self, paths, side) + } /// The versions of a conflicted file with the user's work as `ours`, as IDEA's merge /// dialog shows them (sides swapped during a rebase). pub fn merge_versions(&self, path: &Path, encoding: impl Into) -> IdeResult { let encoding = encoding.into(); let _scope = self.execution_scope(); - let (base, ours, theirs) = self.conflict_versions(path, encoding)?; let sides = self.merge_sides()?; + let blobs = self.conflict_blobs(path)?; + if blobs.iter().flatten().any(|bytes| text_encoding::is_binary(bytes, encoding)) { + return Ok(MergeVersions { binary: true, base: None, ours: None, theirs: None, sides, merged: None }); + } + let [base, ours, theirs] = decode_conflict_blobs(blobs, encoding); let (ours, theirs) = if sides.reversed { (theirs, ours) } else { (ours, theirs) }; let merged = match (&ours, &theirs) { (Some(o), Some(t)) => Some(ops::merge_file(self, o, base.as_deref().unwrap_or(""), t)?), _ => None, }; - Ok(MergeVersions { base, ours, theirs, sides, merged }) + Ok(MergeVersions { binary: false, base, ours, theirs, sides, merged }) } /// For conflict resolution: (base, ours, theirs) versions of a conflicted file. pub fn conflict_versions( @@ -1687,17 +2508,23 @@ impl Repo { path: &Path, encoding: impl Into, ) -> IdeResult<(Option, Option, Option)> { - let encoding = encoding.into(); let _scope = self.execution_scope(); + let [base, ours, theirs] = decode_conflict_blobs(self.conflict_blobs(path)?, encoding.into()); + Ok((base, ours, theirs)) + } + + fn conflict_blobs(&self, path: &Path) -> IdeResult<[Option>; 3]> { let rel = self.rel_path(path)?; let repo = self.gix()?; - let stage = |n: u8| -> IdeResult> { - Ok(repo::blob_at(&repo, &rel, &format!(":{n}"))?.map(|b| text_encoding::decode(&b, encoding).into_owned())) - }; - Ok((stage(1)?, stage(2)?, stage(3)?)) + let stage = |revision| repo::blob_at(&repo, &rel, revision); + Ok([stage(":1")?, stage(":2")?, stage(":3")?]) } } +fn decode_conflict_blobs(blobs: [Option>; 3], encoding: TextEncoding) -> [Option; 3] { + blobs.map(|blob| blob.map(|bytes| text_encoding::decode(&bytes, encoding).into_owned())) +} + /// What git started on this thread may do, and which executable it is. #[derive(Clone)] struct Grant { diff --git a/crates/ide-vcs/src/log_index.rs b/crates/ide-vcs/src/log_index.rs index 64e3a1c05..e1124682e 100644 --- a/crates/ide-vcs/src/log_index.rs +++ b/crates/ide-vcs/src/log_index.rs @@ -446,7 +446,7 @@ pub(crate) fn matches_user(query: &str, name: &str, email: &str) -> bool { /// git's subject (`%s`, `git log --oneline`): the message's first paragraph on one line. /// A whitespace-only line ends the paragraph, as in git; `\r\n` endings count as newlines. -fn subject(message: &gix::bstr::BStr) -> String { +pub(crate) fn subject(message: &gix::bstr::BStr) -> String { let lines = message.lines().map(|l| l.trim_end()).skip_while(|l| l.is_empty()); let paragraph: Vec = lines.take_while(|l| !l.is_empty()).map(|l| to_string(l.as_bstr())).collect(); // git skips leading whitespace (blank lines and the first line's indent) before the subject. diff --git a/crates/ide-vcs/src/manage.rs b/crates/ide-vcs/src/manage.rs index 6a178bd69..142ec93d1 100644 --- a/crates/ide-vcs/src/manage.rs +++ b/crates/ide-vcs/src/manage.rs @@ -5,7 +5,7 @@ use crate::cli::{self, run}; use ide_core::{CancellationToken, IdeError, IdeResult}; use serde::{Deserialize, Serialize}; use specta::Type; -use std::path::Path; +use std::path::{Path, PathBuf}; /// Merge dialog › Modify options (shared by the Pull dialog). #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] @@ -19,22 +19,45 @@ pub struct MergeOptions { pub squash: bool, #[serde(default)] pub no_commit: bool, + #[serde(default)] + pub no_verify: bool, + /// Merge histories whose commits have no common ancestor. + #[serde(default)] + pub allow_unrelated_histories: bool, /// `-m`: message of the merge commit (Merge dialog only). #[serde(default)] pub message: Option, } +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum MergeOutcome { + Done, + LocalChanges { files: Vec }, + Conflicts, + AlreadyUpToDate, + ReadyToCommit, + Squashed, +} + /// Rebase dialog options. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct RebaseOptions { - /// `--onto `: replay `upstream..HEAD` onto this revision instead. + /// Replay the selected commits onto this revision instead. #[serde(default)] pub onto: Option, + /// Switch to this local branch before rebasing it. + #[serde(default)] + pub branch: Option, #[serde(default)] pub rebase_merges: bool, #[serde(default)] pub keep_empty: bool, + #[serde(default)] + pub update_refs: bool, + #[serde(default)] + pub autosquash: Option, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] @@ -49,6 +72,10 @@ pub struct Worktree { pub main: bool, pub locked: bool, pub prunable: bool, + /// This worktree belongs to a repository checked out as a submodule. + #[serde(default)] + #[specta(optional)] + pub submodule: bool, } /// Manage Remotes edits. @@ -98,6 +125,9 @@ fn merge_flags(o: &MergeOptions) -> IdeResult> { if o.no_commit { flags.push("--no-commit"); } + if o.no_verify { + flags.push("--no-verify"); + } Ok(flags) } @@ -108,6 +138,9 @@ pub(crate) fn merge_args(branches: &[String], o: &MergeOptions) -> IdeResult = vec!["merge".into()]; args.extend(merge_flags(o)?.into_iter().map(String::from)); + if o.allow_unrelated_histories { + args.push("--allow-unrelated-histories".into()); + } match o.message.as_deref().map(str::trim).filter(|m| !m.is_empty()) { Some(m) => args.extend(["-m".into(), m.to_string()]), None => args.push("--no-edit".into()), @@ -119,7 +152,7 @@ pub(crate) fn merge_args(branches: &[String], o: &MergeOptions) -> IdeResult IdeResult> { +pub(crate) fn rebase_args(upstream: Option<&str>, o: &RebaseOptions) -> IdeResult> { let mut args: Vec = vec!["rebase".into()]; if o.rebase_merges { args.push("--rebase-merges".into()); @@ -127,26 +160,44 @@ pub(crate) fn rebase_args(upstream: &str, o: &RebaseOptions) -> IdeResult IdeResult> { +pub(crate) fn pull_args( + remote: &str, + branches: &[String], + rebase: Option, + o: &MergeOptions, +) -> IdeResult> { let mut args: Vec = vec!["pull".into(), "--progress".into()]; - if rebase { + if rebase == Some(true) { if o.no_ff || o.ff_only || o.squash || o.no_commit { return Err(IdeError::invalid("--rebase cannot be combined with merge options")); } args.push("--rebase".into()); - } else { + } else if rebase == Some(false) { args.push("--no-rebase".into()); - args.extend(merge_flags(o)?.into_iter().map(String::from)); } + args.extend(merge_flags(o)?.into_iter().map(String::from)); args.push(arg(remote, "remote")?); for b in branches { args.push(arg(b, "branch")?); @@ -171,6 +222,7 @@ pub(crate) fn parse_worktrees(text: &str) -> Vec { main: out.is_empty(), locked: false, prunable: false, + submodule: false, }) } "HEAD" => { @@ -208,6 +260,22 @@ pub(crate) fn parse_worktrees(text: &str) -> Vec { } impl Repo { + /// Git can list the repository's separate Git directory as the first worktree. + fn main_worktree_checkout(&self, reported: &Path) -> Option { + let repo = self.gix().ok()?; + let common = crate::repo::absolute(repo.common_dir()).ok()?; + if reported != common { + return None; + } + if self.git_dir == common { + return Some(self.root().to_path_buf()); + } + let configured = repo.config_snapshot().string("core.worktree")?; + let path = crate::repo::absolute(&common.join(gix::path::from_bstr(&configured).ok()?)).ok()?; + let main = Self::discover(&path).ok()??; + (main.root() == path && main.git_dir == common).then_some(path) + } + /// Merges `branches` into the current branch (Git › Merge…). pub fn merge_with(&self, branches: &[String], options: &MergeOptions) -> IdeResult<()> { let _scope = self.execution_scope(); @@ -216,20 +284,52 @@ impl Repo { crate::preserve::around(self, "Local changes saved before merge", || run(self.root(), &args, None).map(|_| ())) } - /// Rebases the current branch onto `upstream` (or `upstream..HEAD` onto `options.onto`). - pub fn rebase_with(&self, upstream: &str, options: &RebaseOptions) -> IdeResult<()> { + /// Tries the merge as requested. Smart Merge preserves local changes after user confirmation. + pub fn merge_attempt(&self, branches: &[String], options: &MergeOptions, smart: bool) -> IdeResult { + let _scope = self.execution_scope(); + let branches = branches + .iter() + .map(|branch| crate::write::unambiguous_branch_name(self, branch.trim()).to_owned()) + .collect::>(); + let args = merge_args(&branches, options)?; + let args: Vec<_> = args.iter().map(String::as_str).collect(); + crate::write::merge_attempt(self, &args, options, smart) + } + + /// Predicts which tracked local changes a branch merge may have to save. + pub fn merge_affected_files(&self, branch: &str) -> IdeResult> { + let _scope = self.execution_scope(); + crate::write::merge_affected_files(self, branch) + } + + /// Rebases the chosen branch or HEAD. Without an upstream, rebases from the root. + pub fn rebase_with(&self, upstream: Option<&str>, options: &RebaseOptions) -> IdeResult<()> { let _scope = self.execution_scope(); let args = rebase_args(upstream, options)?; + self.validate_rebase(options)?; let args: Vec<&str> = args.iter().map(String::as_str).collect(); crate::preserve::around(self, "Local changes saved before rebase", || run(self.root(), &args, None).map(|_| ())) } + pub(crate) fn validate_rebase(&self, options: &RebaseOptions) -> IdeResult<()> { + if self.operation()?.is_some() { + return Err(IdeError::invalid("another merge, rebase, cherry-pick or revert is in progress")); + } + if let Some(branch) = options.branch.as_deref() { + let name = format!("refs/heads/{}", branch.trim()); + if self.gix()?.try_find_reference(name.as_str()).map_err(crate::repo::gx)?.is_none() { + return Err(IdeError::invalid("Select an existing local branch to rebase.")); + } + } + Ok(()) + } + /// Git › Pull…: pulls `branches` of `remote` into the current branch. pub fn pull_from( &self, remote: &str, branches: &[String], - rebase: bool, + rebase: Option, options: &MergeOptions, cancel: &CancellationToken, on_output: &dyn Fn(String), @@ -270,11 +370,25 @@ impl Repo { pub fn worktrees(&self) -> IdeResult> { let _scope = self.execution_scope(); let out = run(self.root(), &["worktree", "list", "--porcelain"], None)?; - Ok(parse_worktrees(&out.stdout_str())) + let mut trees = parse_worktrees(&out.stdout_str()); + if let Some(main) = trees.first_mut().filter(|main| main.head.is_some()) { + if let Some(path) = self.main_worktree_checkout(&main.path) { + main.path = path.into(); + } + let parent = main.path.parent().and_then(|path| Self::discover(path).ok().flatten()); + let submodule = + parent.and_then(|parent| parent.file_mode_at(&main.path, Some(":0")).ok().flatten()).as_deref() + == Some("160000"); + if submodule { + for tree in &mut trees { + tree.submodule = true; + } + } + } + Ok(trees) } - /// Git › New Worktree…: checks out `commitish` at `path`, on a new branch `new_branch` - /// when given (otherwise `commitish` must be a branch not checked out elsewhere). + /// Checks out a local branch, a new branch, or a detached revision in a new worktree. pub fn add_worktree(&self, path: &Path, commitish: &str, new_branch: Option<&str>) -> IdeResult<()> { let _scope = self.execution_scope(); let path = path.to_string_lossy().into_owned(); @@ -285,6 +399,8 @@ impl Repo { args.push("--no-track".into()); } args.extend(["-b".into(), arg(b, "branch name")?]); + } else if commitish.starts_with("refs/tags/") { + args.push("--detach".into()); } args.extend(["--".into(), path, commitish]); let args: Vec<&str> = args.iter().map(String::as_str).collect(); @@ -316,6 +432,17 @@ impl Repo { args.extend(["--", &path]); run(self.root(), &args, None).map(|_| ()) } + + pub fn set_worktree_locked(&self, path: &Path, locked: bool) -> IdeResult<()> { + let _scope = self.execution_scope(); + let operation = if locked { "lock" } else { "unlock" }; + run(self.root(), &["worktree", operation, "--", &path.to_string_lossy()], None).map(|_| ()) + } + + pub fn prune_worktrees(&self) -> IdeResult<()> { + let _scope = self.execution_scope(); + run(self.root(), &["worktree", "prune", "--expire", "now"], None).map(|_| ()) + } } #[cfg(test)] @@ -324,8 +451,17 @@ mod tests { #[test] fn merge_args_follow_the_options() { - let o = MergeOptions { no_ff: true, message: Some("Merge it".into()), ..Default::default() }; - assert_eq!(merge_args(&["dev".into()], &o).unwrap(), ["merge", "--no-ff", "-m", "Merge it", "dev"]); + let o = MergeOptions { + no_ff: true, + no_verify: true, + allow_unrelated_histories: true, + message: Some("Merge it".into()), + ..Default::default() + }; + assert_eq!( + merge_args(&["dev".into()], &o).unwrap(), + ["merge", "--no-ff", "--no-verify", "--allow-unrelated-histories", "-m", "Merge it", "dev"] + ); assert_eq!( merge_args(&["a".into(), "b".into()], &MergeOptions::default()).unwrap(), ["merge", "--no-edit", "a", "b"] @@ -338,18 +474,37 @@ mod tests { #[test] fn rebase_and_pull_args() { - let o = RebaseOptions { onto: Some("main".into()), rebase_merges: true, keep_empty: false }; - assert_eq!(rebase_args("feature~3", &o).unwrap(), ["rebase", "--rebase-merges", "--onto", "main", "feature~3"]); + let o = RebaseOptions { onto: Some("main".into()), rebase_merges: true, ..Default::default() }; assert_eq!( - pull_args("origin", &["main".into()], false, &MergeOptions { ff_only: true, ..Default::default() }) + rebase_args(Some("feature~3"), &o).unwrap(), + ["rebase", "--rebase-merges", "--onto", "main", "feature~3"] + ); + let root = RebaseOptions { + onto: Some("main".into()), + branch: Some("topic".into()), + update_refs: true, + autosquash: Some(false), + ..Default::default() + }; + assert_eq!( + rebase_args(None, &root).unwrap(), + ["rebase", "--update-refs", "--no-autosquash", "--onto", "main", "--root", "topic"] + ); + assert!(rebase_args(Some("--quit"), &o).is_err()); + assert_eq!( + pull_args("origin", &["main".into()], Some(false), &MergeOptions { ff_only: true, ..Default::default() }) .unwrap(), ["pull", "--progress", "--no-rebase", "--ff-only", "origin", "main"] ); assert_eq!( - pull_args("origin", &[], true, &MergeOptions::default()).unwrap(), - ["pull", "--progress", "--rebase", "origin"] + pull_args("origin", &[], Some(true), &MergeOptions { no_verify: true, ..Default::default() }).unwrap(), + ["pull", "--progress", "--rebase", "--no-verify", "origin"] ); - assert!(pull_args("origin", &[], true, &MergeOptions { squash: true, ..Default::default() }).is_err()); + assert_eq!( + pull_args("origin", &["main".into()], None, &MergeOptions::default()).unwrap(), + ["pull", "--progress", "origin", "main"] + ); + assert!(pull_args("origin", &[], Some(true), &MergeOptions { squash: true, ..Default::default() }).is_err()); } #[test] diff --git a/crates/ide-vcs/src/ops.rs b/crates/ide-vcs/src/ops.rs index 335ebf724..7dd87f1e3 100644 --- a/crates/ide-vcs/src/ops.rs +++ b/crates/ide-vcs/src/ops.rs @@ -3,9 +3,13 @@ use crate::cli::{self, run}; use crate::repo::{gx, resolve}; -use crate::{ChangeKind, ChangedFile, FileLineStats, MergeSides, RebaseAction, RebaseEntry, Repo, ResetMode}; +use crate::{ + ApplyCommitOptions, ChangeKind, ChangedFile, FileLineStats, MergeSides, RebaseAction, RebaseEntry, Repo, ResetMode, +}; +use ide_core::workflow_settings::EmptyCherryPickAction; use ide_core::{CancellationToken, IdeError, IdeResult}; use std::collections::HashSet; +use std::io::Write; /// The in-progress operation git can continue / abort / skip. fn sequencer(r: &Repo) -> IdeResult<&'static str> { @@ -57,12 +61,17 @@ pub(crate) fn merge_sides(r: &Repo) -> IdeResult { } Some("cherry-pick") => sides.commit = read("CHERRY_PICK_HEAD").map(short), Some("revert") => sides.commit = read("REVERT_HEAD").map(short), - // Conflicts outside an operation come from restoring stashed changes (Smart - // Checkout, local changes put aside for a merge or update): stage 2 is the new HEAD, - // stage 3 the user's. None if !crate::write::unmerged_paths(r)?.is_empty() => { - sides.operation = Some("unstash".into()); - sides.reversed = true; + use crate::conflict_resolution::RestoreConflict; + let (name, reversed) = match crate::conflict_resolution::restore_conflict(r)? { + Some(RestoreConflict::ManualStash) => ("stash-apply", false), + Some(RestoreConflict::AutomaticShelf) => ("unshelve", true), + Some(RestoreConflict::PatchApply) => ("apply-patch", false), + // During automatic restoration stage 2 is the new HEAD, stage 3 the user's work. + None => ("unstash", true), + }; + sides.operation = Some(name.into()); + sides.reversed = reversed; } _ => {} } @@ -128,7 +137,7 @@ fn changed_paths(r: &Repo, args: &[&str]) -> IdeResult> { /// `stage` first stages the changes of tracked files (Stage and Retry). Without it a /// rebase stages only edits of files already staged (made while resolving them) and /// otherwise fails with [`UNSTAGED_CHANGES_PREVENT_REBASE`]. -pub(crate) fn continue_op(r: &Repo, stage: bool, cancel: &CancellationToken, out: &dyn Fn(String)) -> IdeResult<()> { +pub(crate) fn continue_op(r: &Repo, stage: bool, run_command: impl FnOnce(&[&str]) -> IdeResult) -> IdeResult { let op = sequencer(r)?; let unresolved = unmerged_paths(r)?; if !unresolved.is_empty() { @@ -155,102 +164,179 @@ pub(crate) fn continue_op(r: &Repo, stage: bool, cancel: &CancellationToken, out "revert" => &["revert", "--continue"], _ => &["am", "--continue"], }; - let result = cli::run_streaming(r.root(), args, cancel, out); + let result = run_command(args); let finished = finish_operation(r); - result.and(finished) + result.and_then(|value| finished.map(|()| value)) } -pub(crate) fn abort_op(r: &Repo, cancel: &CancellationToken, out: &dyn Fn(String)) -> IdeResult<()> { +pub(crate) fn commit_apply_message( + r: &Repo, + message: &str, + options: &ApplyCommitOptions, + cancel: &CancellationToken, + out: &dyn Fn(String), +) -> IdeResult<()> { + let mut file = tempfile::NamedTempFile::new_in(&r.git_dir)?; + file.write_all(message.as_bytes())?; + let path = file.path().to_str().ok_or_else(|| IdeError::invalid("Invalid commit message file path"))?; + let flags = crate::write::commit_metadata_flags( + options.sign_off, + options.run_hooks, + options.author.as_deref(), + options.author_date.as_deref(), + ); + let mut args = vec!["commit", "--cleanup=whitespace", "-F", path]; + args.extend(flags.iter().map(String::as_str)); + cli::run_streaming(r.root(), &args, cancel, out) +} + +pub(crate) fn abort_op( + r: &Repo, + expected: Option<&str>, + cancel: &CancellationToken, + out: &dyn Fn(String), +) -> IdeResult<()> { let op = sequencer(r)?; + if expected.is_some_and(|expected| expected != op) { + return Err(IdeError::invalid("Git operation changed before it could be aborted")); + } let result = cli::run_streaming(r.root(), &[op, "--abort"], cancel, out); let finished = finish_operation(r); result.and(finished) } -pub(crate) fn skip_op(r: &Repo, cancel: &CancellationToken, out: &dyn Fn(String)) -> IdeResult<()> { - let op = sequencer(r)?; - if op == "merge" { - return Err(IdeError::invalid("a merge cannot be skipped; abort it instead")); +pub(crate) fn finish_merge( + r: &Repo, + branch: Option<&str>, + head: &str, + target: &str, + cancel: &CancellationToken, + out: &dyn Fn(String), +) -> IdeResult<()> { + let (current_branch, current_head) = r.head()?; + let merge_head = std::fs::read_to_string(r.git_dir.join("MERGE_HEAD")).ok(); + if current_branch.as_deref() != branch + || current_head.as_deref() != Some(head) + || merge_head.as_deref().map(str::trim) != Some(target) + { + return Err(IdeError::invalid("The merge changed before it could be finished")); } - let result = cli::run_streaming(r.root(), &[op, "--skip"], cancel, out); + let result = cli::run_streaming(r.root(), &["merge", "--continue"], cancel, out); let finished = finish_operation(r); result.and(finished) } -/// Merge commits need a mainline (`-m`), which IDEA doesn't offer for cherry-pick / revert. -fn reject_merges(r: &Repo, commits: &[String], verb: &str) -> IdeResult<()> { - let repo = r.gix()?; - for c in commits { - let commit = repo.find_object(resolve(&repo, c)?).map_err(gx)?.peel_to_commit().map_err(gx)?; - if commit.parent_ids().count() > 1 { - let hex = commit.id.to_string(); - return Err(IdeError::invalid(format!("cannot {verb} merge commit {}", &hex[..8]))); - } +pub(crate) fn skip_op(r: &Repo, run_command: impl FnOnce(&[&str]) -> IdeResult) -> IdeResult { + let op = sequencer(r)?; + if op == "merge" { + return Err(IdeError::invalid("a merge cannot be skipped; abort it instead")); } - Ok(()) + let result = run_command(&[op, "--skip"]); + let finished = finish_operation(r); + result.and_then(|value| finished.map(|()| value)) } -/// Applies `commits` on top of HEAD, in the given order (pass oldest first); -/// `record_origin` adds "(cherry picked from commit …)" to their messages. -pub(crate) fn cherry_pick( +/// Merge commits need a mainline (`-m`), which IDEA doesn't offer for cherry-pick / revert. +pub(crate) fn checked_apply_commits(r: &Repo, commits: &[String], verb: &str) -> IdeResult> { + check_commits(commits)?; + let repo = r.gix()?; + commits + .iter() + .map(|c| { + let commit = repo.find_object(resolve(&repo, c)?).map_err(gx)?.peel_to_commit().map_err(gx)?; + let hex = commit.id.to_string(); + if commit.parent_ids().count() > 1 { + return Err(IdeError::invalid(format!("cannot {verb} merge commit {}", &hex[..8]))); + } + Ok(hex) + }) + .collect() +} + +pub(crate) fn apply_cherry_pick( r: &Repo, commits: &[String], record_origin: bool, + empty_action: EmptyCherryPickAction, cancel: &CancellationToken, out: &dyn Fn(String), -) -> IdeResult<()> { - check_commits(commits)?; - reject_merges(r, commits, "cherry-pick")?; +) -> IdeResult { let mut args = vec!["cherry-pick"]; if record_origin { args.push("-x"); } args.extend(commits.iter().map(String::as_str)); - apply_skipping_empty(r, "cherry-pick", &args, cancel, out) + apply_resolving_empty(r, "cherry-pick", &args, empty_action, cancel, out) } /// Creates commits undoing `commits`, in the given order (pass newest first). pub(crate) fn revert(r: &Repo, commits: &[String], cancel: &CancellationToken, out: &dyn Fn(String)) -> IdeResult<()> { - check_commits(commits)?; - reject_merges(r, commits, "revert")?; + let commits = checked_apply_commits(r, commits, "revert")?; let mut args = vec!["revert", "--no-edit"]; args.extend(commits.iter().map(String::as_str)); - apply_skipping_empty(r, "revert", &args, cancel, out) + apply_resolving_empty(r, "revert", &args, EmptyCherryPickAction::Skip, cancel, out).map(|_| ()) } -/// Runs a cherry-pick / revert sequence. A commit whose changes are already there leaves -/// nothing to commit: it is skipped and the rest of the sequence goes on. -fn apply_skipping_empty( +/// Resolves empty steps while leaving conflicts and other failures to the caller. +pub(crate) fn apply_resolving_empty( r: &Repo, verb: &str, args: &[&str], + action: EmptyCherryPickAction, cancel: &CancellationToken, out: &dyn Fn(String), -) -> IdeResult<()> { - let head_file = if verb == "revert" { "REVERT_HEAD" } else { "CHERRY_PICK_HEAD" }; - let said_nothing = std::cell::Cell::new(false); - let watch = |line: String| { - // git runs with LC_ALL=C; a single commit with nothing left to apply stops here. - said_nothing.set(said_nothing.get() || line.contains("nothing to commit")); - out(line) +) -> IdeResult { + let cherry_pick = verb == "cherry-pick"; + let head_file = if cherry_pick { "CHERRY_PICK_HEAD" } else { "REVERT_HEAD" }; + let is_empty = std::cell::Cell::new(false); + let run = |args: &[&str]| { + is_empty.set(false); + cli::run_streaming(r.root(), args, cancel, &|line| { + // Git runs with LC_ALL=C. An empty pick leaves a prepared commit message. + is_empty.set( + is_empty.get() + || line.contains("nothing to commit") + || line.contains("nothing added to commit but untracked files present") + || line.contains("previous cherry-pick is now empty"), + ); + out(line); + }) }; - let mut result = cli::run_streaming(r.root(), args, cancel, &watch); - if result.is_err() && said_nothing.get() && r.branch_info()?.operation.is_none() { - out("Skipped: its changes are already applied".into()); - return Ok(()); - } + let mut empty_count = 0; + let mut result = run(args); while result.is_err() && !cancel.is_cancelled() { - let Ok(stopped) = std::fs::read_to_string(r.git_dir.join(head_file)) else { break }; - let empty = unmerged_paths(r)?.is_empty() - && cli::run_raw(r.root(), &["diff", "--cached", "--quiet", "HEAD", "--"], None)?.code == Some(0); - if !empty { + let Ok(stopped) = std::fs::read_to_string(r.git_dir.join(head_file)) else { + if is_empty.get() && action == EmptyCherryPickAction::Skip && r.operation()?.is_none() { + out("Skipped: its changes are already applied".into()); + return Ok(empty_count + 1); + } + break; + }; + if (cherry_pick && !is_empty.get()) + || !unmerged_paths(r)?.is_empty() + || cli::run_raw(r.root(), &["diff", "--cached", "--quiet", "--"], None)?.code != Some(0) + { break; } let id = stopped.trim(); - out(format!("{} skipped: its changes are already applied", &id[..id.len().min(8)])); - result = cli::run_streaming(r.root(), &[verb, "--skip"], cancel, out); + let short = &id[..id.len().min(8)]; + empty_count += 1; + match action { + EmptyCherryPickAction::Skip => { + out(format!("{short} skipped: its changes are already applied")); + result = run(&[verb, "--skip"]); + } + EmptyCherryPickAction::CreateEmpty => { + cli::run_streaming(r.root(), &["commit", "--allow-empty"], cancel, out)?; + // The commit clears CHERRY_PICK_HEAD. A native multi-pick still has its todo. + if !r.git_dir.join("sequencer/todo").is_file() { + return Ok(empty_count); + } + result = run(&[verb, "--continue"]); + } + } } - result + result.map(|()| empty_count) } pub(crate) fn reset( @@ -329,7 +415,6 @@ pub(crate) fn interactive_rebase( let work = r.git_dir.join("openidea-rebase"); let _ = std::fs::remove_dir_all(&work); std::fs::create_dir_all(&work)?; - let quote = |p: &std::path::Path| format!("'{}'", p.to_string_lossy().replace('\\', "/").replace('\'', "'\\''")); let mut todo = String::new(); for (i, (e, id)) in entries.iter().zip(&ids).enumerate() { let verb = match e.action { @@ -344,7 +429,8 @@ pub(crate) fn interactive_rebase( let next_joins = entries.get(i + 1).is_some_and(|n| matches!(n.action, RebaseAction::Squash | RebaseAction::Fixup)); let message = e.message.as_deref().map(str::trim).filter(|m| !m.is_empty()); - let wants_message = matches!(e.action, RebaseAction::Reword | RebaseAction::Squash | RebaseAction::Pick); + let wants_message = + matches!(e.action, RebaseAction::Reword | RebaseAction::Squash | RebaseAction::Fixup | RebaseAction::Pick); if let Some(m) = message.filter(|_| wants_message) { if next_joins { return Err(IdeError::invalid( @@ -355,20 +441,34 @@ pub(crate) fn interactive_rebase( std::fs::write(&file, m)?; todo.push_str(&format!( "exec git commit --amend --allow-empty --no-verify --quiet --cleanup=whitespace -F {}\n", - quote(&file) + quote_for_shell(&file) )); } } + let args = ["rebase", "--interactive", "--no-autosquash", base.unwrap_or("--root")]; + run_rebase_todo(r, &work, &todo, &args, cancel, out) +} + +pub(crate) fn quote_for_shell(path: &std::path::Path) -> String { + format!("'{}'", path.to_string_lossy().replace('\\', "/").replace('\'', "'\\''")) +} + +pub(crate) fn run_rebase_todo( + r: &Repo, + work: &std::path::Path, + todo: &str, + args: &[&str], + cancel: &CancellationToken, + out: &dyn Fn(String), +) -> IdeResult<()> { let todo_file = work.join("todo"); std::fs::write(&todo_file, todo)?; - let editor = format!("cp {}", quote(&todo_file)); + let editor = format!("cp {}", quote_for_shell(&todo_file)); // Local changes are put aside and restored when the rebase is over, staged ones as // staged (git's --autostash would bring them all back unstaged). crate::preserve::save(r, "Local changes saved before rebase")?; - let mut args = vec!["rebase", "--interactive", "--no-autosquash"]; - args.push(base.unwrap_or("--root")); let env = [("GIT_SEQUENCE_EDITOR", std::ffi::OsStr::new(&editor))]; - let result = cli::run_streaming_env(r.root(), &args, &env, cancel, out); + let result = cli::run_streaming_env(r.root(), args, &env, cancel, out); // A stopped rebase still needs the message files for its remaining `exec` lines. let finished = finish_operation(r); result.and(finished) @@ -380,6 +480,7 @@ pub(crate) fn finish_operation(r: &Repo) -> IdeResult<()> { if r.branch_info()?.operation.is_some() { return Ok(()); } + crate::cherry_pick_plan::clear(r); let _ = std::fs::remove_dir_all(r.git_dir.join("openidea-rebase")); crate::preserve::restore(r) } @@ -444,14 +545,95 @@ pub(crate) fn push_tag( delete: bool, cancel: &CancellationToken, on_output: &dyn Fn(String), -) -> IdeResult<()> { +) -> IdeResult { let tag = tag_ref(name)?; - let remote = remote.trim(); + remote_push_urls(r, remote, cancel)?; + let spec = if delete { format!(":{tag}") } else { format!("{tag}:{tag}") }; + let mut report = crate::PushReport::new(Some(remote.to_owned())); + crate::push_report::run( + &mut report, + r.root(), + &["push", "--progress", "--porcelain", "--", remote, &spec], + cancel, + on_output, + )?; + Ok(report) +} + +pub(crate) fn remote_fetch_url(r: &Repo, remote: &str, cancel: &CancellationToken) -> IdeResult { + let output = cli::run_cancellable(r.root(), &["remote", "get-url", "--", remote], cancel)?; + output + .stdout_str() + .lines() + .next() + .filter(|url| !url.is_empty()) + .map(str::to_owned) + .ok_or_else(|| IdeError::invalid(format!("remote '{remote}' has no fetch URL"))) +} + +pub(crate) fn remote_push_urls(r: &Repo, remote: &str, cancel: &CancellationToken) -> IdeResult> { if remote.is_empty() || remote.starts_with('-') { return Err(IdeError::invalid(format!("invalid remote '{remote}'"))); } - let spec = if delete { format!(":{tag}") } else { format!("{tag}:{tag}") }; - cli::run_streaming(r.root(), &["push", "--progress", remote, &spec], cancel, on_output) + let output = cli::run_cancellable(r.root(), &["remote", "get-url", "--push", "--all", remote], cancel)?; + let urls: Vec<_> = output.stdout_str().lines().filter(|url| !url.is_empty()).map(str::to_owned).collect(); + if urls.is_empty() { + return Err(IdeError::invalid(format!("remote '{remote}' has no push URL"))); + } + Ok(urls) +} + +pub(crate) fn delete_tag_on_remotes( + r: &Repo, + deleted: &crate::DeletedTag, + cancel: &CancellationToken, + out: &dyn Fn(String), +) -> IdeResult<()> { + let tag = tag_ref(&deleted.name)?; + let expected = gix::ObjectId::from_hex(deleted.target.as_bytes()).map_err(gx)?.to_string(); + let lease = format!("--force-with-lease={tag}:{expected}"); + let deletion = format!(":{tag}"); + let mut failures = Vec::new(); + for remote in r.remotes()? { + out(format!("Checking tag {} on {}", deleted.name, remote.name)); + let urls = match remote_push_urls(r, &remote.name, cancel) { + Ok(urls) => urls, + Err(e) if cancel.is_cancelled() => return Err(e), + Err(e) => { + failures.push(format!("{}: {e}", remote.name)); + continue; + } + }; + let receive_pack = + if urls.len() > 1 { r.config_get(&format!("remote.{}.receivepack", remote.name))? } else { None }; + for url in &urls { + let push_target = if urls.len() == 1 { remote.name.as_str() } else { url.as_str() }; + let result = (|| { + let args = ["ls-remote", "--exit-code", "--refs", "--tags", "--", url, &tag]; + let refs = cli::run_cancellable_raw(r.root(), &args, cancel)?; + if !matches!(refs.code, Some(0 | 2)) { + return Err(cli::failure(&args, &refs.stderr, &refs.stdout, refs.code)); + } + if !refs.stdout_str().lines().any(|line| line.split_once('\t').is_some_and(|(_, name)| name == tag)) { + out(format!("Tag {} is already absent on {}", deleted.name, remote.name)); + return Ok(()); + } + let mut args = vec!["push", "--progress", &lease]; + if let Some(receive_pack) = receive_pack.as_deref() { + args.extend(["--receive-pack", receive_pack]); + } + args.extend(["--", push_target, &deletion]); + cli::run_streaming(r.root(), &args, cancel, out) + })(); + if let Err(e) = result { + if cancel.is_cancelled() { + return Err(e); + } + failures.push(format!("{}: {e}", remote.name)); + } + } + } + if failures.is_empty() { Ok(()) } else { Err(IdeError::invalid(failures.join("\n"))) } } /// Tag names, sorted. diff --git a/crates/ide-vcs/src/patch.rs b/crates/ide-vcs/src/patch.rs index 5f40ae750..df19466ac 100644 --- a/crates/ide-vcs/src/patch.rs +++ b/crates/ide-vcs/src/patch.rs @@ -2,37 +2,23 @@ //! and applying them (falling back to a 3-way merge that leaves conflicts for the //! merge UI), as Create Patch / Apply Patch / Shelve do in IDEA. -use crate::cli::{self, run, run_env}; +use crate::cli::{self, TempIndex, run, run_env}; use crate::repo::gx; -use crate::{ApplyOutcome, ChangeKind, ChangedFile, PatchFile, Repo}; +use crate::{ApplyOutcome, ChangeKind, ChangedFile, PatchFile, Repo, Repos, StagingPatchEntry, StagingPatchSide}; use ide_core::{IdeError, IdeResult}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::ffi::OsStr; -use std::path::PathBuf; -use std::sync::atomic::{AtomicU32, Ordering}; +use std::path::{Component, Path, PathBuf}; + +pub(crate) mod file_diff; +mod mapping; +pub use mapping::{ + MappedPatch, PatchDirectoryMatches, PatchDirectoryScope, PatchPathMapping, PatchPlacement, + discover_patch_directories, +}; const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"; -/// A throwaway index file in `.git`, removed on drop. -struct TempIndex(PathBuf); - -impl TempIndex { - fn new(r: &Repo) -> Self { - static SEQ: AtomicU32 = AtomicU32::new(0); - let n = SEQ.fetch_add(1, Ordering::Relaxed); - TempIndex(r.git_dir.join(format!("openidea-index-{}-{n}", std::process::id()))) - } - fn env(&self) -> [(&'static str, &OsStr); 1] { - [("GIT_INDEX_FILE", self.0.as_os_str())] - } -} - -impl Drop for TempIndex { - fn drop(&mut self) { - let _ = std::fs::remove_file(&self.0); - let _ = std::fs::remove_file(self.0.with_extension("lock")); - } -} - /// Binary-safe patch of the working-tree changes (staged or not, untracked files /// included) of `rel_paths` against HEAD, plus the files it touches (renames split /// into delete + add). The real index is left untouched. @@ -41,6 +27,16 @@ pub(crate) fn working_patch( rel_paths: &[String], reverse: bool, detect_renames: bool, +) -> IdeResult<(String, Vec)> { + working_patch_with_prefix(r, rel_paths, reverse, detect_renames, None) +} + +pub(crate) fn working_patch_with_prefix( + r: &Repo, + rel_paths: &[String], + reverse: bool, + detect_renames: bool, + prefix: Option<&str>, ) -> IdeResult<(String, Vec)> { if rel_paths.is_empty() { return Err(IdeError::invalid("no files selected")); @@ -66,11 +62,115 @@ pub(crate) fn working_patch( if reverse { diff.push("-R"); } + let prefixes = prefix.map(|prefix| [format!("--src-prefix=a/{prefix}"), format!("--dst-prefix=b/{prefix}")]); + if let Some(prefixes) = &prefixes { + diff.extend(prefixes.iter().map(String::as_str)); + } let patch = lossless_diff(r, &diff, &env)?; let names = run_env(r.root(), &["diff", "--cached", "--name-status", "-z", "--no-renames"], None, &env)?; Ok((patch, crate::ops::parse_name_status(&names.stdout_str()))) } +pub(crate) fn staging_patch(r: &Repo, entries: &[StagingPatchEntry], reverse: bool, prefix: &str) -> IdeResult { + use StagingPatchSide::{Both, Staged, Unstaged}; + let mut selected = BTreeMap::new(); + for entry in entries { + let path = r.given_rel_path(&entry.path.0)?; + let old = entry.renamed_from.as_ref().map(|old| r.given_rel_path(&old.0)).transpose()?; + if path.is_empty() || old.as_deref() == Some("") { + return Err(IdeError::invalid("no files selected")); + } + let (side, names) = selected.entry(path.clone()).or_insert_with(|| (entry.side, BTreeSet::new())); + if *side != entry.side { + *side = Both; + } + names.extend(old.into_iter().chain([path])); + } + if selected.is_empty() { + return Err(IdeError::invalid("no files selected")); + } + + let repo = r.gix()?; + let head = r.head()?.1.unwrap_or_else(|| repo.object_hash().empty_tree().to_string()); + let index = TempIndex::new(r); + let env = index.env(); + match std::fs::copy(repo.index_path(), index.path()) { + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + run_env(r.root(), &["read-tree", "--empty"], None, &env)?; + } + Err(error) => return Err(error.into()), + } + + // An intent-to-add entry lets Git diff an untracked file against an absent index + // version, without staging its content or changing the user's index. + let worktree: BTreeSet<_> = + selected.values().filter(|(side, _)| *side != Staged).flat_map(|(_, names)| names).collect(); + if !worktree.is_empty() { + let tracked = run_env(r.root(), &["ls-files", "--cached", "-z"], None, &env)?.stdout; + let tracked: HashSet<_> = tracked.split(|byte| *byte == 0).collect(); + let untracked: Vec<_> = worktree + .into_iter() + .filter(|path| !tracked.contains(path.as_bytes()) && r.root().join(path).symlink_metadata().is_ok()) + .cloned() + .collect(); + if !untracked.is_empty() { + cli::run_paths_env( + r.root(), + &["--literal-pathspecs", "add", "--intent-to-add", "--"], + &untracked, + None, + &env, + )?; + } + } + + // Git swaps custom prefixes along with the endpoints under -R. + let (a, b) = if reverse { ("b", "a") } else { ("a", "b") }; + let src = format!("--src-prefix={a}/{prefix}"); + let dst = format!("--dst-prefix={b}/{prefix}"); + let mut options = vec![ + "--literal-pathspecs", + "diff", + "--binary", + "--full-index", + "-M", + "--no-color", + "--no-ext-diff", + "--no-textconv", + "--ita-invisible-in-index", + &src, + &dst, + ]; + if reverse { + options.push("-R"); + } + let mut patch = String::new(); + let sides = if reverse { [Both, Unstaged, Staged] } else { [Staged, Unstaged, Both] }; + for side in sides { + let paths: Vec<_> = selected + .values() + .filter(|(selected, _)| *selected == side) + .flat_map(|(_, names)| names.iter().cloned()) + .collect::>() + .into_iter() + .collect(); + if paths.is_empty() { + continue; + } + let mut args = options.clone(); + if side == Staged { + args.push("--cached"); + } + if side != Unstaged { + args.push(&head); + } + args.push("--"); + patch.push_str(&selected_diff(r, args, &paths, prefix, &env)?); + } + Ok(patch) +} + /// The changes of `commits` (oldest first), each against its first parent. pub(crate) fn commits_patch(r: &Repo, commits: &[String], reverse: bool) -> IdeResult { if commits.is_empty() { @@ -96,11 +196,193 @@ pub(crate) fn commits_patch(r: &Repo, commits: &[String], reverse: bool) -> IdeR Ok(out) } +/// An automatic Shelf snapshot follows the same per-path layout as a manually created shelf. +pub(crate) fn shelf_tree_patch_with_prefix(r: &Repo, base: &str, tree: &str, prefix: &str) -> IdeResult { + lossless_diff( + r, + &[ + "diff", + "--binary", + "--full-index", + "--no-renames", + "--no-color", + "--no-ext-diff", + "--no-textconv", + &format!("--src-prefix=a/{prefix}"), + &format!("--dst-prefix=b/{prefix}"), + base, + tree, + "--", + ], + &[], + ) +} + +pub(crate) fn revisions_patch(r: &Repo, before: &str, after: &str, paths: &[PathBuf]) -> IdeResult { + if [before, after].iter().any(|rev| rev.trim().is_empty() || rev.starts_with('-')) { + return Err(IdeError::invalid("invalid revision")); + } + let paths = paths.iter().map(|path| r.given_rel_path(path)).collect::>>()?; + if paths.is_empty() || paths.iter().any(String::is_empty) { + return Err(IdeError::invalid("no files selected")); + } + let empty_tree = if before == EMPTY_TREE || after == EMPTY_TREE { + r.gix()?.object_hash().empty_tree().to_string() + } else { + String::new() + }; + let before = if before == EMPTY_TREE { empty_tree.as_str() } else { before }; + let after = if after == EMPTY_TREE { empty_tree.as_str() } else { after }; + let args = vec![ + "--literal-pathspecs", + "diff", + "--binary", + "--full-index", + "-M", + "--no-color", + "--no-ext-diff", + "--no-textconv", + "--src-prefix=a/", + "--dst-prefix=b/", + before, + after, + "--", + ]; + selected_diff(r, args, &paths, "", &[]) +} + +fn selected_diff<'a>( + r: &Repo, + mut args: Vec<&'a str>, + paths: &'a [String], + prefix: &str, + env: &[(&str, &OsStr)], +) -> IdeResult { + // The long-selection fallback keeps both sides of a rename in the same diff. + if cli::batch_paths(cli::base_command_line_len(&args), paths, cli::command_line_limit()).len() > 1 { + let diff = prefix_rename_headers(lossless_diff(r, &args, env)?, prefix); + let selected: HashSet<_> = paths.iter().map(|path| format!("{prefix}{path}")).collect(); + return Ok(sections(&diff) + .into_iter() + .filter(|(_, file)| { + selected.contains(file.path.as_str()) || file.old_path.as_deref().is_some_and(|p| selected.contains(p)) + }) + .map(|(section, _)| section) + .collect()); + } + args.extend(paths.iter().map(String::as_str)); + lossless_diff(r, &args, env).map(|patch| prefix_rename_headers(patch, prefix)) +} + +/// Git's --src-prefix and --dst-prefix cover file headers, but not rename metadata. +fn prefix_rename_headers(patch: String, prefix: &str) -> String { + if prefix.is_empty() { + return patch; + } + let mut out = String::with_capacity(patch.len()); + for line in patch.split_inclusive('\n') { + if let Some((tag, path)) = + ["rename from ", "rename to "].into_iter().find_map(|tag| line.strip_prefix(tag).map(|path| (tag, path))) + { + let path = git_path(path.trim_end_matches('\n')); + out.push_str(tag); + out.push_str(&crate::diff::quote_path(&format!("{prefix}{path}"))); + out.push('\n'); + } else { + out.push_str(line); + } + } + out +} + +pub(crate) fn sections(patch: &str) -> Vec<(&str, PatchFile)> { + let mut starts: Vec<_> = patch + .match_indices("diff --git ") + .filter(|(i, _)| *i == 0 || patch.as_bytes()[i - 1] == b'\n') + .map(|(i, _)| i) + .collect(); + if starts.is_empty() { + let (mut old, mut new) = (0u32, 0u32); + let mut offset = 0; + let mut lines = patch.split_inclusive('\n').peekable(); + while let Some(line) = lines.next() { + if old > 0 || new > 0 { + match line.as_bytes().first() { + Some(b'-') => old = old.saturating_sub(1), + Some(b'+') => new = new.saturating_sub(1), + Some(b' ') => { + old = old.saturating_sub(1); + new = new.saturating_sub(1); + } + _ => {} + } + } else if line.starts_with("--- ") && lines.peek().is_some_and(|l| l.starts_with("+++ ")) { + starts.push(offset); + } + if let Some(range) = line.strip_prefix("@@ ") { + let mut parts = range.split_whitespace(); + let count = |s: &str| s.split_once(',').map_or(1, |(_, n)| n.parse().unwrap_or(0)); + old = parts.next().map(count).unwrap_or(0); + new = parts.next().map(count).unwrap_or(0); + } + offset += line.len(); + } + } + starts + .iter() + .enumerate() + .filter_map(|(n, &start)| { + let section = &patch[start..starts.get(n + 1).copied().unwrap_or(patch.len())]; + parse_patch(section).into_iter().next().map(|file| (section, file)) + }) + .collect() +} + +/// Changes the base of an exported patch without modifying its hunks or binary payloads. +pub fn rebase_patch(patch: &str, root: &Path, prefix: &str, base: &Path) -> IdeResult { + if patch.is_empty() || (root == base && prefix.is_empty()) { + return Ok(patch.to_owned()); + } + let patch = normalized(patch)?; + let sections = sections(&patch); + let Some((first, _)) = sections.first() else { + return Err(IdeError::invalid("no file changes found in the patch")); + }; + let relative = |path: &str| { + let path = path + .strip_prefix(prefix) + .map(Path::new) + .filter(|path| valid_patch_path(path)) + .ok_or_else(|| IdeError::invalid("The patch contains a path outside its repository"))?; + root.join(path) + .strip_prefix(base) + .ok() + .filter(|path| valid_patch_path(path)) + .map(ide_core::ipc_path::to_ipc) + .ok_or_else(|| IdeError::invalid("The base directory must contain every selected path")) + }; + let mut output = String::with_capacity(patch.len()); + if let Some((preamble, _)) = patch.split_once(*first) { + output.push_str(preamble); + } + for (section, file) in sections { + let before = relative(file.old_path.as_deref().unwrap_or(&file.path))?; + let after = relative(&file.path)?; + mapping::rewrite_headers(&mut output, section, &before, &after, false); + } + Ok(output) +} + fn normalized(patch: &str) -> IdeResult { if patch.trim().is_empty() { return Err(IdeError::invalid("the patch is empty")); } - let mut p = patch.replace("\r\n", "\n"); + // Git emits LF headers even when the hunk payload contains CRLF lines. + let crlf_headers = patch + .split('\n') + .find(|line| line.starts_with("diff --git ") || line.starts_with("--- ")) + .is_some_and(|line| line.ends_with('\r')); + let mut p = if crlf_headers { patch.replace("\r\n", "\n") } else { patch.to_string() }; if !p.ends_with('\n') { p.push('\n'); } @@ -109,17 +391,25 @@ fn normalized(patch: &str) -> IdeResult { /// The files of a patch, whether each applies cleanly to the working tree. pub(crate) fn preview(r: &Repo, patch: &str) -> IdeResult> { + preview_with_prefix(r, patch, "") +} + +fn preview_with_prefix(r: &Repo, patch: &str, prefix: &str) -> IdeResult> { let patch = normalized(patch)?; let mut files = parse_patch(&patch); if files.is_empty() { return Err(IdeError::invalid("no file changes found in the patch")); } - let out = cli::run_raw(r.root(), &["apply", "--check", "--binary", "-"], Some(patch.as_bytes()))?; + let strip = strip_option(prefix); + let mut args = vec!["apply", "--check", "--binary"]; + args.extend(strip.as_deref()); + args.push("-"); + let out = cli::run_raw(r.root(), &args, Some(patch.as_bytes()))?; if out.code != Some(0) { let err = String::from_utf8_lossy(&out.stderr).into_owned(); let failing = failing_paths(&err); for f in &mut files { - let hit = |p: &str| failing.iter().any(|x| x == p); + let hit = |p: &str| failing.iter().any(|x| x == p.strip_prefix(prefix).unwrap_or(p)); f.applies = !(hit(&f.path) || f.old_path.as_deref().is_some_and(hit)); } // An error we could not attribute to a file: nothing applies cleanly. @@ -127,9 +417,30 @@ pub(crate) fn preview(r: &Repo, patch: &str) -> IdeResult> { files.iter_mut().for_each(|f| f.applies = false); } } + for file in &mut files { + if let Some(base) = file.old_path.as_deref().unwrap_or(&file.path).strip_prefix(prefix) { + file.missing_base = missing_patch_base(r.root(), file, base); + } + } Ok(files) } +fn valid_patch_path(path: &Path) -> bool { + !path.as_os_str().is_empty() + && path + .components() + .all(|part| matches!(part, std::path::Component::Normal(name) if !name.eq_ignore_ascii_case(".git"))) +} + +fn patch_file_exists(path: &Path) -> bool { + std::fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_file() || metadata.is_symlink()) +} + +fn missing_patch_base(root: &Path, file: &PatchFile, before: &str) -> bool { + let before = Path::new(before); + file.kind != ChangeKind::Added && valid_patch_path(before) && !patch_file_exists(&root.join(before)) +} + /// Paths named in `git apply` errors (`error: path: …`, `error: patch failed: path:12`). fn failing_paths(stderr: &str) -> Vec { let mut out = Vec::new(); @@ -150,19 +461,196 @@ fn failing_paths(stderr: &str) -> Vec { /// merge is attempted; conflicting files are left with conflict markers and index /// stages for the merge UI and returned in [`ApplyOutcome::conflicts`]. pub(crate) fn apply(r: &Repo, patch: &str) -> IdeResult { + apply_with_prefix(r, patch, "") +} + +/// Keep complete file sections, including rename metadata and binary payloads. +pub(crate) fn apply_selected(r: &Repo, patch: &str, paths: &[String]) -> IdeResult { + let patch = normalized(patch)?; + let selected: String = selected_sections(&patch, Some(paths))?.into_iter().map(|(section, _)| section).collect(); + apply_for_review(r, &selected, "") +} + +fn selected_sections<'a>(patch: &'a str, paths: Option<&[String]>) -> IdeResult> { + let mut sections = sections(patch); + let Some(paths) = paths else { return Ok(sections) }; + if paths.is_empty() { + return Err(IdeError::invalid("select files to apply from the patch")); + } + let paths: HashSet<_> = paths.iter().map(String::as_str).collect(); + let mut remaining = paths.clone(); + sections.retain(|(_, file)| { + remaining.remove(file.path.as_str()); + paths.contains(file.path.as_str()) + }); + if !remaining.is_empty() { + return Err(IdeError::invalid("the selection contains files outside the patch")); + } + Ok(sections) +} + +/// An apply plan with paths based at a common project directory. +pub struct ProjectPatch { + pub base: PathBuf, + pub groups: Vec, +} + +pub struct ProjectPatchGroup { + pub root: PathBuf, + prefix: String, + patch: String, +} + +impl ProjectPatchGroup { + pub fn preview(&self, r: &Repo) -> IdeResult> { + let _scope = r.execution_scope(); + preview_with_prefix(r, &self.patch, &self.prefix) + } + + pub fn apply(&self, r: &Repo) -> IdeResult { + let _scope = r.execution_scope(); + let outcome = apply_for_review(r, &self.patch, &self.prefix)?; + let based = |paths: Vec| paths.into_iter().map(|path| format!("{}{path}", self.prefix)).collect(); + Ok(ApplyOutcome { applied: based(outcome.applied), conflicts: based(outcome.conflicts) }) + } + + pub fn file_diff( + &self, + r: &Repo, + path: &str, + encoding: &dyn Fn(&Path, &[u8]) -> crate::TextEncoding, + ) -> IdeResult { + let _scope = r.execution_scope(); + file_diff::generate(r, &self.patch, path, &self.prefix, encoding) + } +} + +impl ProjectPatch { + /// Automatically use project paths when all files map and the patch spans repositories. + pub fn discover(repos: &Repos, project: &Path, patch: &str, multiple: bool) -> IdeResult> { + let patch = normalized(patch)?; + let files = sections(&patch); + let mut single = None; + for plan in project.ancestors().filter_map(|base| Self::route(repos, base, &files)) { + if plan.groups.len() > 1 { + return Ok(Some(plan)); + } + if !multiple && single.is_none() { + single = Some(plan); + } + } + Ok(single) + } + + pub fn at_base( + repos: &Repos, + project: &Path, + base: &Path, + patch: &str, + paths: Option<&[String]>, + ) -> IdeResult { + if !project.starts_with(base) || !base.is_absolute() { + return Err(IdeError::invalid("The patch base is outside the project")); + } + let patch = normalized(patch)?; + let files = selected_sections(&patch, paths)?; + Self::route(repos, base, &files) + .ok_or_else(|| IdeError::invalid("The patch paths do not match the project's Git repositories")) + } + + fn route(repos: &Repos, base: &Path, files: &[(&str, PatchFile)]) -> Option { + if files.is_empty() { + return None; + } + let resolve = |path: &str| { + let path = Path::new(path); + if path.as_os_str().is_empty() || !path.components().all(|c| matches!(c, Component::Normal(_))) { + return None; + } + let full = base.join(path); + let repo = repos.for_path(&full)?; + let relative_root = repo.root().strip_prefix(base).ok()?; + (full != repo.root()).then_some((repo.root(), relative_root)) + }; + let mut groups = BTreeMap::new(); + for (section, file) in files { + let (root, relative_root) = resolve(&file.path)?; + if let Some(old) = &file.old_path + && resolve(old)?.0 != root + { + return None; + } + let group = groups.entry(root).or_insert_with(|| ProjectPatchGroup { + root: root.to_owned(), + prefix: if relative_root.as_os_str().is_empty() { + String::new() + } else { + format!("{}/", ide_core::ipc_path::to_ipc(relative_root)) + }, + patch: String::new(), + }); + group.patch.push_str(section); + } + Some(Self { base: base.to_owned(), groups: groups.into_values().collect() }) + } +} + +pub(crate) fn strip_option(prefix: &str) -> Option { + (!prefix.is_empty()).then(|| format!("-p{}", 1 + prefix.bytes().filter(|&byte| byte == b'/').count())) +} + +pub(crate) fn apply_with_prefix(r: &Repo, patch: &str, prefix: &str) -> IdeResult { + apply_patch(r, patch, prefix, false) +} + +pub(crate) fn apply_for_review(r: &Repo, patch: &str, prefix: &str) -> IdeResult { + apply_patch(r, patch, prefix, true) +} + +fn apply_patch(r: &Repo, patch: &str, prefix: &str, identify_conflicts: bool) -> IdeResult { let patch = normalized(patch)?; let files = parse_patch(&patch); - let paths: Vec = files.iter().map(|f| f.path.clone()).collect(); - let check = cli::run_raw(r.root(), &["apply", "--check", "--binary", "-"], Some(patch.as_bytes()))?; + let paths = files + .iter() + .map(|f| { + if f.old_path.as_deref().is_some_and(|old| !old.starts_with(prefix)) { + return Err(IdeError::invalid("The patch contains a path outside its repository")); + } + f.path + .strip_prefix(prefix) + .map(str::to_owned) + .ok_or_else(|| IdeError::invalid("The patch contains a path outside its repository")) + }) + .collect::>>()?; + let strip = strip_option(prefix); + let mut args = vec!["apply", "--binary"]; + args.extend(strip.as_deref()); + let check = cli::run_raw(r.root(), &[args.as_slice(), &["--check", "-"]].concat(), Some(patch.as_bytes()))?; if check.code == Some(0) { - run(r.root(), &["apply", "--binary", "-"], Some(patch.as_bytes()))?; + run(r.root(), &[args.as_slice(), &["-"]].concat(), Some(patch.as_bytes()))?; return Ok(ApplyOutcome { applied: paths, conflicts: Vec::new() }); } - let out = cli::run_raw(r.root(), &["apply", "--3way", "--binary", "-"], Some(patch.as_bytes()))?; - let conflicts = unmerged(r)?; + let _guard = identify_conflicts.then(|| r.conflict_mutation.lock().unwrap_or_else(|error| error.into_inner())); + let record = identify_conflicts && unmerged(r)?.is_empty(); + if record { + crate::conflict_resolution::clear_restore_conflicts(r); + } + let out = cli::run_raw(r.root(), &[args.as_slice(), &["--3way", "-"]].concat(), Some(patch.as_bytes()))?; + let conflicts: Vec<_> = unmerged(r)? + .into_iter() + .filter(|path| { + paths.contains(path) + || files + .iter() + .any(|f| f.old_path.as_deref().and_then(|old| old.strip_prefix(prefix)) == Some(path.as_str())) + }) + .collect(); if out.code != Some(0) && conflicts.is_empty() { return Err(cli::failure(&["apply"], &out.stderr, &out.stdout, out.code)); } + if record && !conflicts.is_empty() { + crate::conflict_resolution::record_conflicts(r, crate::conflict_resolution::RestoreConflict::PatchApply); + } // `--3way` stages what it applied; keep the index as it was for the clean files. let clean: Vec = paths.iter().filter(|p| !conflicts.contains(p)).cloned().collect(); if !clean.is_empty() && r.has_head()? { @@ -176,7 +664,7 @@ fn unmerged(r: &Repo) -> IdeResult> { Ok(out.stdout_str().split('\0').filter(|s| !s.is_empty()).map(str::to_string).collect()) } -fn git_path(p: &str) -> String { +pub(super) fn git_path(p: &str) -> String { let Some(p) = p.strip_prefix('"').and_then(|p| p.strip_suffix('"')) else { return p.to_string() }; let mut bytes = Vec::new(); let mut chars = p.bytes().peekable(); @@ -225,6 +713,7 @@ fn strip_prefix(p: &str) -> Option { pub(crate) fn parse_patch(patch: &str) -> Vec { let mut out: Vec = Vec::new(); let mut cur: Option = None; + let mut before_path: Option = None; // From a `diff --git` header and no hunk seen yet: `---` belongs to it. let mut fresh_header = false; let (mut old_left, mut new_left) = (0u32, 0u32); @@ -236,6 +725,7 @@ pub(crate) fn parse_patch(patch: &str) -> Vec { removed: 0, binary: false, applies: true, + missing_base: false, }; for line in patch.lines() { if old_left > 0 || new_left > 0 { @@ -259,6 +749,7 @@ pub(crate) fn parse_patch(patch: &str) -> Vec { } if let Some(rest) = line.strip_prefix("diff --git ") { out.extend(cur.take()); + before_path = None; let path = rest .rsplit_once(" \"b/") .map(|(_, b)| git_path(&format!("\"{b}"))) @@ -273,9 +764,10 @@ pub(crate) fn parse_patch(patch: &str) -> Vec { cur = Some(new_file(String::new())); } fresh_header = false; + before_path = strip_prefix(rest); if let Some(c) = cur.as_mut() { - match strip_prefix(rest) { - Some(p) if c.path.is_empty() => c.path = p, + match &before_path { + Some(p) if c.path.is_empty() => c.path = p.clone(), Some(_) => {} None => c.kind = ChangeKind::Added, } @@ -283,7 +775,12 @@ pub(crate) fn parse_patch(patch: &str) -> Vec { } else if let Some(c) = cur.as_mut() { if let Some(rest) = line.strip_prefix("+++ ") { match strip_prefix(rest) { - Some(p) => c.path = p, + Some(p) => { + if let Some(old) = before_path.take().filter(|old| old != &p) { + c.old_path.get_or_insert(old); + } + c.path = p; + } None => c.kind = ChangeKind::Deleted, } } else if let Some(range) = line.strip_prefix("@@ ") { @@ -302,10 +799,12 @@ pub(crate) fn parse_patch(patch: &str) -> Vec { c.kind = ChangeKind::Added; } else if line.starts_with("deleted file mode") { c.kind = ChangeKind::Deleted; - } else if let Some(p) = line.strip_prefix("rename from ") { + } else if let Some(p) = line.strip_prefix("rename from ").or_else(|| line.strip_prefix("copy from ")) { c.old_path = Some(git_path(p)); - c.kind = ChangeKind::Renamed; - } else if let Some(p) = line.strip_prefix("rename to ") { + if line.starts_with("rename ") { + c.kind = ChangeKind::Renamed; + } + } else if let Some(p) = line.strip_prefix("rename to ").or_else(|| line.strip_prefix("copy to ")) { c.path = git_path(p); } else if line.starts_with("GIT binary patch") || line.starts_with("Binary files ") { c.binary = true; @@ -392,7 +891,7 @@ pub(crate) fn stage_converted_patch( let env = tmp.env(); let index = r.git_dir.join("index"); if index.exists() { - std::fs::copy(index, &tmp.0)?; + std::fs::copy(index, tmp.path())?; } else { run_env(r.root(), &["read-tree", "--empty"], None, &env)?; } diff --git a/crates/ide-vcs/src/patch/file_diff.rs b/crates/ide-vcs/src/patch/file_diff.rs new file mode 100644 index 000000000..e11c1c2af --- /dev/null +++ b/crates/ide-vcs/src/patch/file_diff.rs @@ -0,0 +1,164 @@ +use super::{normalized, selected_sections, strip_option, valid_patch_path}; +use crate::cli::{run, run_raw_env}; +use crate::text_encoding; +use crate::{ChangeKind, PatchDiffContent, PatchFileDiff, Repo, TextEncoding}; +use ide_core::{IdeError, IdeResult}; +use std::fs; +use std::io::Read; +use std::path::Path; + +const MAX_PREVIEW_BYTES: u64 = 4 << 20; + +pub(crate) fn generate( + repo: &Repo, + patch: &str, + path: &str, + prefix: &str, + encoding: &dyn Fn(&Path, &[u8]) -> TextEncoding, +) -> IdeResult { + let patch = normalized(patch)?; + let sections = selected_sections(&patch, Some(&[path.to_owned()]))?; + let (first_section, first) = §ions[0]; + let before = safe_path(first.old_path.as_deref().unwrap_or(path), prefix)?; + let after = safe_path(path, prefix)?; + for (_, file) in §ions { + if let Some(old) = &file.old_path { + safe_path(old, prefix)?; + } + } + let before_path = repo.root().join(before); + let after_path = repo.root().join(after); + let mut result = PatchFileDiff { + path: (&after_path).into(), + old_path: (before != after).then(|| (&before_path).into()), + content: PatchDiffContent::Binary, + }; + if sections.iter().any(|(_, file)| file.binary) { + return Ok(result); + } + let Some(local) = read_regular(repo.root(), before)? else { return Ok(result) }; + let view = |bytes: Option<&[u8]>, path: &Path| { + bytes.map_or(Some(None), |bytes| { + let charset = encoding(path, bytes); + (!text_encoding::is_binary(bytes, charset)) + .then(|| Some(text_encoding::decode(bytes, charset).into_owned())) + }) + }; + let Some(local_text) = view(local.as_deref(), &before_path) else { return Ok(result) }; + let body: String = sections.iter().map(|(section, _)| *section).collect(); + if body.len() as u64 > MAX_PREVIEW_BYTES { + return Err(too_large()); + } + let autocrlf = run(repo.root(), &["config", "--get", "core.autocrlf"], None) + .map(|result| result.stdout_str().trim().to_owned()) + .unwrap_or_else(|_| "false".to_owned()); + let autocrlf = format!("core.autocrlf={autocrlf}"); + + let sandbox = tempfile::tempdir()?; + if let Some(applied) = apply_in_sandbox(sandbox.path(), &body, prefix, before, after, local.as_deref(), &autocrlf)? + { + let Some(after_text) = view(applied.as_deref(), &after_path) else { return Ok(result) }; + result.content = if local_text == after_text && before == after { + PatchDiffContent::Raw { local: local_text, patch: body, applies: true } + } else { + PatchDiffContent::Text { before: local_text, after: after_text } + }; + return Ok(result); + } + + let base = if first.kind == ChangeKind::Added { Some(None) } else { original_blob(repo, first_section).map(Some) }; + if let Some(base) = base { + // The first attempt can leave a copied input in place. Use a fresh directory for the base. + let original = tempfile::tempdir()?; + if let Some(patched) = + apply_in_sandbox(original.path(), &body, prefix, before, after, base.as_deref(), &autocrlf)? + { + let Some(base) = view(base.as_deref(), &before_path) else { return Ok(result) }; + let Some(patched) = view(patched.as_deref(), &after_path) else { return Ok(result) }; + result.content = PatchDiffContent::Conflict { local: local_text, base, patched }; + return Ok(result); + } + } + result.content = PatchDiffContent::Raw { local: local_text, patch: body, applies: false }; + Ok(result) +} + +fn safe_path<'a>(path: &'a str, prefix: &str) -> IdeResult<&'a Path> { + path.strip_prefix(prefix) + .map(Path::new) + .filter(|path| valid_patch_path(path)) + .ok_or_else(|| IdeError::invalid("The patch contains a path outside its repository")) +} + +fn too_large() -> IdeError { + IdeError::invalid("Patch file is too large to preview") +} + +// Outer None means non-regular content, inner None means the file is absent. +fn read_regular(root: &Path, rel: &Path) -> IdeResult>>> { + let path = root.join(rel); + let metadata = match path.symlink_metadata() { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Some(None)), + Err(error) => return Err(error.into()), + }; + if !metadata.is_file() { + return Ok(None); + } + let resolved = dunce::canonicalize(&path)?; + if !resolved.starts_with(dunce::canonicalize(root)?) { + return Err(IdeError::invalid("The patch contains a path outside its repository")); + } + let mut bytes = Vec::new(); + fs::File::open(resolved)?.take(MAX_PREVIEW_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_PREVIEW_BYTES { + return Err(too_large()); + } + Ok(Some(Some(bytes))) +} + +fn apply_in_sandbox( + root: &Path, + patch: &str, + prefix: &str, + before: &Path, + after: &Path, + bytes: Option<&[u8]>, + autocrlf: &str, +) -> IdeResult>>> { + let worktree = root.join("worktree"); + fs::create_dir(&worktree)?; + if let Some(bytes) = bytes { + let path = worktree.join(before); + fs::create_dir_all(path.parent().expect("relative file path"))?; + fs::write(path, bytes)?; + } + let boundary = + std::env::join_paths([dunce::canonicalize(root)?]).map_err(|error| IdeError::invalid(error.to_string()))?; + let strip = strip_option(prefix); + let mut args = vec!["-c", autocrlf, "apply", "--binary"]; + args.extend(strip.as_deref()); + args.push("-"); + let output = run_raw_env(&worktree, &args, Some(patch.as_bytes()), &[("GIT_CEILING_DIRECTORIES", &boundary)])?; + if output.code != Some(0) { + return Ok(None); + } + read_regular(&worktree, after) +} + +fn original_blob(repo: &Repo, section: &str) -> Option> { + let oid = section + .lines() + .take_while(|line| !line.starts_with("@@")) + .find_map(|line| line.strip_prefix("index ")?.split_once("..").map(|(oid, _)| oid)); + let oid = oid.filter(|oid| { + (4..=64).contains(&oid.len()) + && oid.bytes().all(|byte| byte.is_ascii_hexdigit()) + && oid.bytes().any(|byte| byte != b'0') + })?; + let size = run(repo.root(), &["cat-file", "-s", oid], None).ok()?; + if size.stdout_str().trim().parse::().map_or(true, |size| size > MAX_PREVIEW_BYTES) { + return None; + } + run(repo.root(), &["cat-file", "blob", oid], None).ok().map(|blob| blob.stdout) +} diff --git a/crates/ide-vcs/src/patch/mapping.rs b/crates/ide-vcs/src/patch/mapping.rs new file mode 100644 index 000000000..500c0b7d3 --- /dev/null +++ b/crates/ide-vcs/src/patch/mapping.rs @@ -0,0 +1,294 @@ +use super::{ + ProjectPatchGroup, missing_patch_base, normalized, patch_file_exists, selected_sections, valid_patch_path, +}; +use crate::diff::quote_path; +use crate::{ApplyOutcome, ChangeKind, PatchFile, PatchFileDiff, Repo, Repos, TextEncoding}; +use ide_core::{IdeError, IdeResult, IpcPath, ipc_path::to_ipc}; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::collections::{BTreeMap, HashMap}; +use std::path::{Component, Path, PathBuf}; + +mod candidates; +pub use candidates::{PatchDirectoryMatches, PatchDirectoryScope, discover_patch_directories}; + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PatchPathMapping { + pub path: String, + pub directory: Option, + pub strip: u32, + pub file: Option, +} + +#[derive(Debug, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PatchPlacement { + pub path: String, + pub target: Option, + pub error: Option, +} + +pub struct MappedPatch { + pub files: Vec, + pub placements: Vec, + pub groups: Vec, +} + +pub struct MappedPatchGroup { + pub group: ProjectPatchGroup, + entries: Vec<(usize, String)>, +} + +struct Destination { + root: PathBuf, + full: PathBuf, + before: String, + after: String, +} + +impl MappedPatchGroup { + pub fn preview(&self, repo: &Repo, files: &mut [PatchFile]) -> IdeResult<()> { + let preview = self.group.preview(repo)?; + if preview.len() != self.entries.len() { + return Err(IdeError::invalid("The mapped patch contains inconsistent file headers")); + } + for (file, (index, _)) in preview.into_iter().zip(&self.entries) { + files[*index].applies = file.applies; + } + Ok(()) + } + + pub fn file_diff(&self, repo: &Repo, encoding: &dyn Fn(&Path, &[u8]) -> TextEncoding) -> IdeResult { + let (_, path) = &self.entries[0]; + self.group.file_diff(repo, path, encoding) + } + + pub fn apply(&self, repo: &Repo) -> IdeResult { + let outcome = self.group.apply(repo)?; + let absolute = |paths: Vec| paths.into_iter().map(|path| to_ipc(&repo.root().join(path))).collect(); + Ok(ApplyOutcome { applied: absolute(outcome.applied), conflicts: absolute(outcome.conflicts) }) + } +} + +impl MappedPatch { + pub fn new( + repos: &Repos, + repo_root: Option<&Path>, + base: Option<&Path>, + patch: &str, + paths: Option<&[String]>, + mappings: &[PatchPathMapping], + ) -> IdeResult { + let default = match repo_root { + Some(root) => repos.at_root(root), + None => repos.primary(), + } + .ok_or_else(|| IdeError::unavailable("The patch repository is not in the project"))?; + let patch = normalized(patch)?; + let sections = selected_sections(&patch, paths)?; + if sections.is_empty() { + return Err(IdeError::invalid("no file changes found in the patch")); + } + let mappings: HashMap<_, _> = mappings.iter().map(|mapping| (mapping.path.as_str(), mapping)).collect(); + let destinations: Vec<_> = sections + .iter() + .map(|(section, file)| { + if let Some(target) = mappings.get(file.path.as_str()).and_then(|m| m.file.as_deref()) { + return file_destination(repos, file, section, target); + } + destination(repos, default, base, file, mappings.get(file.path.as_str()).copied()) + }) + .collect(); + let mut owners = HashMap::new(); + let mut duplicates = std::collections::HashSet::new(); + for ((_, file), destination) in sections.iter().zip(&destinations) { + if let Ok(destination) = destination { + let target = to_ipc(&destination.full); + let target = if cfg!(windows) { target.to_lowercase() } else { target }; + if owners.insert(target.clone(), &file.path).is_some_and(|owner| owner != &file.path) { + duplicates.insert(target); + } + } + } + + let mut files = Vec::new(); + let mut placements = Vec::new(); + let mut groups = BTreeMap::new(); + for ((section, mut file), destination) in sections.into_iter().zip(destinations) { + let mut placement = PatchPlacement { path: file.path.clone(), target: None, error: None }; + file.applies = false; + match destination { + Ok(destination) => { + file.missing_base = missing_patch_base(&destination.root, &file, &destination.before); + let target = to_ipc(&destination.full); + let key = if cfg!(windows) { target.to_lowercase() } else { target }; + placement.target = Some(destination.full.into()); + if duplicates.contains(&key) { + placement.error = Some("Multiple patch files target the same path".into()); + } else { + let group = groups.entry(destination.root.clone()).or_insert_with(|| MappedPatchGroup { + group: ProjectPatchGroup { + root: destination.root, + prefix: String::new(), + patch: String::new(), + }, + entries: Vec::new(), + }); + rewrite_headers( + &mut group.group.patch, + section, + &destination.before, + &destination.after, + mappings.get(file.path.as_str()).is_some_and(|m| m.file.is_some()), + ); + group.entries.push((files.len(), destination.after)); + } + } + Err(error) => placement.error = Some(error.message), + } + placements.push(placement); + files.push(file); + } + Ok(Self { files, placements, groups: groups.into_values().collect() }) + } + + pub fn require_destinations(&self) -> IdeResult<()> { + if let Some(placement) = self.placements.iter().find(|placement| placement.error.is_some()) { + return Err(IdeError::invalid(format!( + "{}: {}", + placement.path, + placement.error.as_deref().unwrap_or_default() + ))); + } + if let Some(file) = self.files.iter().find(|file| file.missing_base) { + return Err(IdeError::invalid(format!("{}: missing base file", file.path))); + } + Ok(()) + } +} + +fn file_destination(repos: &Repos, file: &PatchFile, section: &str, target: &Path) -> IdeResult { + if file.kind == ChangeKind::Added { + return Err(IdeError::invalid("A new file does not need a base file")); + } + if !valid_patch_path(Path::new(&file.path)) + || file.old_path.as_deref().is_some_and(|path| !valid_patch_path(Path::new(path))) + { + return Err(IdeError::invalid("The patch contains a path outside its repository")); + } + let repo = repos + .for_path(target) + .ok_or_else(|| IdeError::invalid("The patch destination is outside the project's Git repositories"))?; + let relative = target + .strip_prefix(repo.root()) + .ok() + .filter(|path| valid_patch_path(path)) + .ok_or_else(|| IdeError::invalid("Choose an existing file inside a Git repository"))?; + if !patch_file_exists(target) { + return Err(IdeError::invalid("Choose an existing file inside a Git repository")); + } + if file.old_path.is_some() + && !file.binary + && file.added == 0 + && file.removed == 0 + && !section.lines().any(|line| line.starts_with("old mode ")) + { + return Err(IdeError::invalid("This patch only renames or copies the file")); + } + let path = to_ipc(relative); + Ok(Destination { root: repo.root().to_owned(), full: target.to_owned(), before: path.clone(), after: path }) +} + +fn destination( + repos: &Repos, + default: &Repo, + base: Option<&Path>, + file: &PatchFile, + mapping: Option<&PatchPathMapping>, +) -> IdeResult { + let directory = mapping.and_then(|m| m.directory.as_deref()).or(base).unwrap_or_else(|| default.root()); + if !directory.is_absolute() + || directory.components().any(|part| match part { + Component::ParentDir => true, + Component::Normal(name) => name.eq_ignore_ascii_case(".git"), + _ => false, + }) + { + return Err(IdeError::invalid("Choose an absolute directory inside a Git repository")); + } + let strip = mapping.map_or(0, |m| m.strip) as usize; + let resolve = |path: &str| { + let path = Path::new(path); + if !valid_patch_path(path) { + return Err(IdeError::invalid("The patch contains a path outside its repository")); + } + let path: PathBuf = path.components().skip(strip).collect(); + if path.as_os_str().is_empty() { + return Err(IdeError::invalid("The patch path has no file name after removing directories")); + } + Ok(directory.join(path)) + }; + let full = resolve(&file.path)?; + let before = resolve(file.old_path.as_deref().unwrap_or(&file.path))?; + let repo = if base.is_none() && mapping.and_then(|m| m.directory.as_ref()).is_none() { + default + } else { + repos + .for_path(&full) + .map(|repo| repo.as_ref()) + .ok_or_else(|| IdeError::invalid("The patch destination is outside the project's Git repositories"))? + }; + let rel = |path: &Path| { + path.strip_prefix(repo.root()) + .ok() + .filter(|path| !path.as_os_str().is_empty()) + .map(to_ipc) + .ok_or_else(|| IdeError::invalid("Both paths of a rename or copy must be in the same Git repository")) + }; + if (base.is_some() || mapping.and_then(|m| m.directory.as_ref()).is_some()) + && repos.for_path(&before).is_some_and(|other| other.root() != repo.root()) + { + return Err(IdeError::invalid("Both paths of a rename or copy must be in the same Git repository")); + } + let after = rel(&full)?; + Ok(Destination { root: repo.root().to_path_buf(), before: rel(&before)?, full, after }) +} + +/// Change names in the file header only. Hunks and Git's binary payload stay byte-for-byte intact. +pub(super) fn rewrite_headers(out: &mut String, section: &str, before: &str, after: &str, same_file: bool) { + let old = quote_path(&format!("a/{before}")); + let new = quote_path(&format!("b/{after}")); + let mut offset = 0; + for line in section.split_inclusive('\n') { + if line.starts_with("@@") || line.starts_with("GIT binary patch") { + break; + } + if same_file + && ["rename ", "copy ", "similarity index ", "dissimilarity index "] + .iter() + .any(|prefix| line.starts_with(prefix)) + { + offset += line.len(); + continue; + } + let replacement = if line.starts_with("diff --git ") { + Some(format!("diff --git {old} {new}\n")) + } else if line.starts_with("--- ") && !line.starts_with("--- /dev/null") { + Some(format!("--- {old}\n")) + } else if line.starts_with("+++ ") && !line.starts_with("+++ /dev/null") { + Some(format!("+++ {new}\n")) + } else { + ["rename from ", "rename to ", "copy from ", "copy to "] + .into_iter() + .find(|prefix| line.starts_with(prefix)) + .map(|prefix| { + let path = if prefix.ends_with("from ") { before } else { after }; + format!("{prefix}{}\n", quote_path(path)) + }) + }; + out.push_str(replacement.as_deref().unwrap_or(line)); + offset += line.len(); + } + out.push_str(§ion[offset..]); +} diff --git a/crates/ide-vcs/src/patch/mapping/candidates.rs b/crates/ide-vcs/src/patch/mapping/candidates.rs new file mode 100644 index 000000000..aee5359ac --- /dev/null +++ b/crates/ide-vcs/src/patch/mapping/candidates.rs @@ -0,0 +1,247 @@ +use super::{ + Destination, PatchPathMapping, ProjectPatchGroup, destination, file_destination, missing_patch_base, normalized, + rewrite_headers, selected_sections, valid_patch_path, +}; +use crate::{ChangeKind, PatchFile, Repo, Repos}; +use ide_core::{IdeResult, IpcPath, ipc_path::to_ipc}; +use serde::Serialize; +use specta::Type; +use std::collections::{HashMap, HashSet}; +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; + +const MENU_LIMIT: usize = 8; +const CHECK_LIMIT: usize = 32; + +#[derive(Debug, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PatchDirectoryCandidate { + pub directory: IpcPath, + pub source: IpcPath, + pub strip: u32, + pub applies: Option, +} + +#[derive(Debug, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PatchDirectoryMatches { + pub path: String, + pub candidates: Vec, +} + +struct Match { + candidate: PatchDirectoryCandidate, + target: Destination, +} + +pub struct PatchDirectoryScope<'a> { + pub repo: &'a Repo, + pub base: Option<&'a Path>, + pub only_repository: bool, + pub automatic: bool, +} + +/// Match missing base files and additions to existing path suffixes. Check the resulting +/// mappings with Git before adopting any inferred destination. +pub fn discover_patch_directories( + repos: &Repos, + scope: PatchDirectoryScope<'_>, + patch: &str, + overrides: &[PatchPathMapping], + indexed_files: impl FnOnce(&HashSet<&OsStr>) -> Vec, + existing_directories: impl FnOnce(&HashSet<&OsStr>) -> Vec, +) -> IdeResult<(Vec, Vec)> { + let PatchDirectoryScope { repo: default, base, automatic, .. } = scope; + let patch = normalized(patch)?; + let sections = selected_sections(&patch, None)?; + let overrides: HashMap<_, _> = overrides.iter().map(|mapping| (mapping.path.as_str(), mapping)).collect(); + let mut occupied = HashSet::new(); + let mut missing = Vec::new(); + for (section, file) in §ions { + let before = Path::new(file.old_path.as_deref().unwrap_or(&file.path)); + let original = destination(repos, default, base, file, None); + if valid_patch_path(before) { + let needs_base = if file.kind == ChangeKind::Added { + new_file_anchors(before).next().is_some() + && !original.as_ref().is_ok_and(|route| route.full.parent().is_some_and(Path::is_dir)) + } else { + original.as_ref().map_or(true, |route| missing_patch_base(&route.root, file, &route.before)) + }; + if needs_base { + missing.push((*section, file, before)); + } + } + let mapping = overrides.get(file.path.as_str()).copied(); + let active = match mapping { + Some(mapping) => match mapping.file.as_deref() { + Some(path) => file_destination(repos, file, section, path), + None => destination(repos, default, base, file, Some(mapping)), + }, + None => original, + }; + if let Ok(route) = active { + occupied.extend(path_keys(&route)); + } + } + + let names: HashSet<_> = missing + .iter() + .filter(|(_, file, _)| file.kind != ChangeKind::Added) + .filter_map(|(_, _, before)| before.file_name()) + .collect(); + let dir_names: HashSet<_> = missing + .iter() + .filter(|(_, file, _)| file.kind == ChangeKind::Added) + .flat_map(|(_, _, path)| new_file_anchors(path)) + .filter_map(Path::file_name) + .collect(); + let indexed = indexed_files(&names); + let dirs = existing_directories(&dir_names); + let indexed = by_name(&indexed); + let dirs = by_name(&dirs); + + let mut checks_left = CHECK_LIMIT; + let mut matches = Vec::new(); + let mut inferred = Vec::new(); + let mut seen = HashSet::new(); + for (section, file, before) in missing { + // Several sections for the same path have no single hunk context to rank on. + if !seen.insert(file.path.as_str()) { + inferred.retain(|(mapping, _): &(PatchPathMapping, Destination)| mapping.path != file.path); + continue; + } + let mut choices = if file.kind == ChangeKind::Added { + new_file_anchors(before) + .flat_map(|anchor| named_paths(&dirs, anchor).map(move |path| (anchor, path))) + .filter_map(|(anchor, path)| candidate_for(repos, &scope, file, anchor, path)) + .collect::>() + } else { + named_paths(&indexed, before).filter_map(|path| candidate_for(repos, &scope, file, before, path)).collect() + }; + choices.sort_by(|a, b| { + a.candidate.strip.cmp(&b.candidate.strip).then(a.candidate.source.cmp(&b.candidate.source)) + }); + let mut locations = HashSet::new(); + choices.retain(|entry| locations.insert(entry.candidate.source.clone())); + let truncated = choices.len() > MENU_LIMIT; + choices.truncate(MENU_LIMIT); + for entry in choices.iter_mut().take(checks_left) { + checks_left -= 1; + let Some(repo) = repos.at_root(&entry.target.root) else { continue }; + let mut rewritten = String::new(); + rewrite_headers(&mut rewritten, section, &entry.target.before, &entry.target.after, false); + let group = ProjectPatchGroup { root: entry.target.root.clone(), prefix: String::new(), patch: rewritten }; + entry.candidate.applies = group.preview(repo).ok().map(|files| files.iter().all(|file| file.applies)); + } + choices.sort_by_key(|entry| (entry.candidate.applies != Some(true), entry.candidate.strip)); + let best = choices.first(); + if automatic + && !truncated + && !overrides.contains_key(file.path.as_str()) + && let Some(best) = best + && best.candidate.applies == Some(true) + && choices.iter().skip(1).all(|entry| { + entry.candidate.strip > best.candidate.strip + || (file.kind != ChangeKind::Added && entry.candidate.applies == Some(false)) + }) + { + let mapping = mapping_for(file, &best.candidate); + if let Ok(route) = destination(repos, default, base, file, Some(&mapping)) + && path_keys(&route).all(|key| !occupied.contains(&key)) + { + inferred.push((mapping, route)); + } + } + if !choices.is_empty() { + matches.push(PatchDirectoryMatches { + path: file.path.clone(), + candidates: choices.into_iter().map(|entry| entry.candidate).collect(), + }); + } + } + let mut owners = HashMap::new(); + for (_, route) in &inferred { + for key in path_keys(route) { + *owners.entry(key).or_insert(0) += 1; + } + } + let automatic = inferred + .into_iter() + .filter(|(_, route)| path_keys(route).all(|key| owners[&key] == 1)) + .map(|(mapping, _)| mapping) + .collect(); + Ok((matches, automatic)) +} + +/// A new file can be inside new subfolders. Match any existing ancestor that retains +/// at least two components, so a generic name such as "src" cannot move an addition. +fn new_file_anchors(path: &Path) -> impl Iterator { + path.ancestors().skip(1).take_while(|dir| dir.parent().is_some_and(|parent| !parent.as_os_str().is_empty())) +} + +fn by_name(paths: &[PathBuf]) -> HashMap<&OsStr, Vec<&Path>> { + let mut grouped: HashMap<_, Vec<_>> = HashMap::new(); + for path in paths { + if let Some(name) = path.file_name() { + grouped.entry(name).or_default().push(path.as_path()); + } + } + grouped +} + +fn named_paths<'a>(paths: &'a HashMap<&OsStr, Vec<&'a Path>>, path: &Path) -> impl Iterator { + path.file_name().and_then(|name| paths.get(name)).into_iter().flatten().copied() +} + +fn path_keys(route: &Destination) -> impl Iterator + '_ { + let key = |path: &str| { + let absolute = to_ipc(&route.root.join(path)); + if cfg!(windows) { absolute.to_lowercase() } else { absolute } + }; + let after = key(&route.after); + let before = key(&route.before); + let differs = before != after; + std::iter::once(after).chain(differs.then_some(before)) +} + +fn mapping_for(file: &PatchFile, candidate: &PatchDirectoryCandidate) -> PatchPathMapping { + PatchPathMapping { + path: file.path.clone(), + directory: Some(candidate.directory.clone()), + strip: candidate.strip, + file: None, + } +} + +fn candidate_for( + repos: &Repos, + scope: &PatchDirectoryScope<'_>, + file: &PatchFile, + anchor: &Path, + local: &Path, +) -> Option { + let added = file.kind == ChangeKind::Added; + let common = anchor.components().rev().zip(local.components().rev()).take_while(|(a, b)| a == b).count(); + if common < if added { 2 } else { 1 } { + return None; + } + let mapping = PatchPathMapping { + path: file.path.clone(), + directory: Some(local.ancestors().nth(common)?.into()), + strip: u32::try_from(anchor.components().count() - common).ok()?, + file: None, + }; + let target = destination(repos, scope.repo, scope.base, file, Some(&mapping)).ok()?; + if (scope.only_repository && target.root != scope.repo.root()) + || missing_patch_base(&target.root, file, &target.before) + { + return None; + } + let candidate = PatchDirectoryCandidate { + source: if added { target.full.as_path() } else { local }.into(), + directory: mapping.directory?, + strip: mapping.strip, + applies: None, + }; + Some(Match { candidate, target }) +} diff --git a/crates/ide-vcs/src/preserve.rs b/crates/ide-vcs/src/preserve.rs index 97839a717..0c7c9c600 100644 --- a/crates/ide-vcs/src/preserve.rs +++ b/crates/ide-vcs/src/preserve.rs @@ -1,64 +1,415 @@ -//! Local changes put aside around merge, rebase and pull, and brought back once the +//! Local changes put aside around checkout, merge, rebase and pull, and brought back once the //! operation is over: staged changes as staged (git's `--autostash` brings everything //! back unstaged). An operation that stops on conflicts keeps them aside until it is //! continued, skipped, aborted or concluded by a commit. -use crate::Repo; use crate::cli::{self, run}; -use crate::write::unmerged_paths; +use crate::shelf::SavedShelves; +use crate::write::{drop_restored_stash, selected_stash_index, unmerged_paths}; +use crate::{Repo, Stash}; use ide_core::{IdeError, IdeResult}; +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, HashSet}; +use std::io::Write; +use std::path::PathBuf; -/// `.git/` holds the id of the stash the changes went to. +/// `.git/` holds the saved entry to restore. Older versions stored only a stash commit id. const MARKER: &str = "openidea-saved-changes"; -/// Stashes the local changes of tracked files, if any. +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum Saved { + Shelves(SavedShelves), + Shelf { directory: PathBuf, entry: String, snapshot: String }, + Stash(Stash), +} + +/// Saves the local changes of tracked files, if any. pub(crate) fn save(r: &Repo, message: &str) -> IdeResult<()> { - let marker = r.git_dir.join(MARKER); - if marker.exists() { + let _stash_lock = crate::write::lock_stashes(r)?; + save_locked(r, message).map(|_| ()) +} + +fn save_locked(r: &Repo, message: &str) -> IdeResult> { + if r.git_dir.join(MARKER).exists() { // Changes saved by an operation still in progress stay where they are; those of // one concluded outside the IDE come back first. - if r.branch_info()?.operation.is_some() { - return Ok(()); + restore_saved(r, None)?; + if r.git_dir.join(MARKER).exists() { + return Ok(None); } - restore(r)?; } if run(r.root(), &["status", "--porcelain", "--untracked-files=no"], None)?.stdout_str().trim().is_empty() { - return Ok(()); + return Ok(None); } - let before = stash_top(r); - run(r.root(), &["stash", "push", "-q", "-m", message], None)?; - // A stash that succeeds without a new entry found nothing it saves: the status above also - // lists submodules at another commit or with changes inside, which a stash leaves in place. - let Some(id) = stash_top(r).filter(|id| Some(id) != before.as_ref()) else { return Ok(()) }; - std::fs::write(marker, id)?; + let Some(stash) = stash_local_changes(r, message)? else { return Ok(None) }; + let saved = Saved::Stash(stash); + write_marker(r, &saved)?; + let options = r.automatic_shelf.read().unwrap_or_else(|poison| poison.into_inner()).clone(); + let (Some(options), Saved::Stash(stash)) = (options, &saved) else { return Ok(Some(saved)) }; + let shelves = match crate::shelf::capture_stash(r, options, message, stash) { + Ok(shelves) => Saved::Shelves(shelves), + Err(error) => return Err(rolled_back(error, restore_entry(r, saved, false))), + }; + if let Err(error) = write_marker(r, &shelves) { + if let Saved::Shelves(entries) = &shelves { + entries.discard(); + } + return Err(rolled_back(error, restore_entry(r, saved, false))); + } + if let Err(error) = selected_stash_index(r, stash) + .and_then(|index| index.map_or(Ok(()), |index| crate::write::stash_drop(r, index))) + { + return Err(rolled_back(error, restore_entry(r, shelves, false))); + } + Ok(Some(shelves)) +} + +/// The error that stopped saving, with the rollback's error when that failed too. +fn rolled_back(error: IdeError, rollback: IdeResult) -> IdeError { + match rollback { + Ok(_) => error, + Err(rollback) => IdeError::invalid(format!("{}\n{}", error.message, rollback.message)), + } +} + +fn write_marker(r: &Repo, saved: &Saved) -> IdeResult<()> { + let saved = serde_json::to_vec(saved).map_err(|e| IdeError::internal(e.to_string()))?; + let mut temporary = tempfile::NamedTempFile::new_in(&r.git_dir)?; + temporary.write_all(&saved)?; + temporary.persist(r.git_dir.join(MARKER)).map_err(|error| error.error)?; Ok(()) } -fn stash_top(r: &Repo) -> Option { - run(r.root(), &["rev-parse", "-q", "--verify", "refs/stash"], None).ok().map(|o| o.stdout_str().trim().to_owned()) +/// Separates a failed switch from a failed restore after a successful switch. +pub(crate) fn checkout( + r: &Repo, + message: &str, + switch: impl FnOnce() -> IdeResult<()>, +) -> IdeResult>> { + let _stash_lock = crate::write::lock_stashes(r)?; + let saved = save_locked(r, message)?.ok_or_else(|| { + IdeError::invalid(if r.git_dir.join(MARKER).exists() { + "Local changes from an unfinished Git operation are still put aside. Finish or abort it first." + } else { + "could not save the local changes" + }) + })?; + let switched = switch(); + if switched.is_ok() + && matches!(&saved, Saved::Shelves(shelves) if shelves.batch.as_deref().is_some_and(crate::shelf::is_active_batch)) + { + return Ok(Ok(Vec::new())); + } + let restored = restore_entry(r, saved, switched.is_ok()); + match (switched, restored) { + (Ok(()), restored) => Ok(restored), + (Err(switch), Err(restore)) => Err(IdeError::invalid(format!("{}\n{}", switch.message, restore.message))), + (Err(error), Ok(_)) => Err(error), + } +} + +// The caller holds the common stash lock until the new entry is identified. +fn stash_local_changes(r: &Repo, message: &str) -> IdeResult> { + let previous = r.stashes()?.into_iter().next(); + let output = run(r.root(), &["stash", "push", "-m", message], None)?.stdout_str(); + // A stash that succeeds without a new entry found nothing it saves: the status above also + // lists submodules at another commit or with changes inside, which a stash leaves in place. + if output.lines().any(|line| line == "No local changes to save") { + return Ok(None); + } + crate::conflict_resolution::clear_restore_conflicts(r); + let error = || IdeError::invalid("Could not identify the stash containing the saved local changes"); + let message = output + .lines() + .find_map(|line| line.strip_prefix("Saved working directory and index state ")) + .ok_or_else(error)?; + let mut matches = r + .stashes()? + .into_iter() + .take_while(|stash| previous.as_ref().is_none_or(|prev| !prev.same_entry(stash))) + .filter(|stash| stash.message == message); + let stash = matches.next().ok_or_else(error)?; + if matches.next().is_some() { + return Err(error()); + } + Ok(Some(stash)) +} + +fn apply_snapshot(r: &Repo, snapshot: &str, allow_unstaged: bool) -> IdeResult> { + let with_index = ["stash", "apply", "-q", "--index", snapshot]; + let mut out = cli::run_raw(r.root(), &with_index, None)?; + if out.code != Some(0) { + let conflicts = unmerged_paths(r)?; + if !conflicts.is_empty() { + return Ok(conflicts); + } + if !allow_unstaged { + return Err(cli::failure(&with_index, &out.stderr, &out.stdout, out.code)); + } + let staged = merge_saved_index(r, snapshot).unwrap_or_else(|error| { + tracing::debug!(%error, "cannot merge saved index"); + None + }); + let args = ["stash", "apply", "-q", snapshot]; + out = cli::run_raw(r.root(), &args, None)?; + if out.code != Some(0) { + let conflicts = unmerged_paths(r)?; + return if conflicts.is_empty() { + Err(cli::failure(&args, &out.stderr, &out.stdout, out.code)) + } else { + Ok(conflicts) + }; + } + if let Some((before, merged)) = staged { + // Update only the index, keeping unrelated entries and the merged working copy. + run(r.root(), &["read-tree", "-m", "-i", &before, &merged], None)?; + } + } + Ok(Vec::new()) +} + +/// `stash apply --index` applies a patch without a three-way fallback. The patch +/// can fail on context even when both the staged and working changes merge cleanly. +fn merge_saved_index(r: &Repo, snapshot: &str) -> IdeResult> { + let base = format!("{snapshot}^1"); + let saved = format!("{snapshot}^2"); + let patch = crate::patch::shelf_tree_patch_with_prefix(r, &base, &saved, "")?; + if patch.is_empty() { + return Ok(None); + } + let before = run(r.root(), &["write-tree"], None)?.stdout_str().trim().to_owned(); + let index = cli::TempIndex::new(r); + let env = index.env(); + cli::run_env(r.root(), &["read-tree", &before], None, &env)?; + cli::run_env(r.root(), &["apply", "--cached", "--3way", "--whitespace=nowarn", "-"], Some(patch.as_bytes()), &env)?; + let merged = cli::run_env(r.root(), &["write-tree"], None, &env)?.stdout_str().trim().to_owned(); + Ok((before != merged).then_some((before, merged))) +} + +fn restore_entry(r: &Repo, saved: Saved, allow_unstaged: bool) -> IdeResult> { + std::fs::remove_file(r.git_dir.join(MARKER))?; + match saved { + Saved::Stash(stash) => { + let conflicts = apply_snapshot(r, &stash.id, allow_unstaged)?; + if conflicts.is_empty() { + drop_restored_stash(r, &stash)?; + } + Ok(conflicts) + } + Saved::Shelf { directory, entry, snapshot } => { + let restored = restore_shelf(r, &directory, &entry, &snapshot, allow_unstaged); + if restored.as_ref().is_ok_and(|files| !files.is_empty()) { + crate::conflict_resolution::record_conflicts( + r, + crate::conflict_resolution::RestoreConflict::AutomaticShelf, + ); + } + restored + } + Saved::Shelves(shelves) => { + let restored = restore_shelves(r, &shelves, allow_unstaged); + if restored.is_ok() { + shelves.remove_archive(); + } + if restored.as_ref().is_ok_and(|files| !files.is_empty()) { + crate::conflict_resolution::record_conflicts( + r, + crate::conflict_resolution::RestoreConflict::AutomaticShelf, + ); + } + restored + } + } +} + +fn restore_shelves(r: &Repo, shelves: &SavedShelves, allow_unstaged: bool) -> IdeResult> { + let pending = shelves.pending()?; + if pending.is_empty() { + return Ok(Vec::new()); + } + let owned: Vec<_> = pending.iter().map(|entry| crate::patch::parse_patch(&entry.patch)).collect(); + if owned.iter().any(Vec::is_empty) { + return Err(IdeError::invalid("no file changes found in the patch")); + } + shelves.unpack(r)?; + let conflicts = if pending.len() == shelves.entries.len() && pending.iter().all(|entry| entry.intact) { + apply_snapshot(r, &shelves.snapshot, allow_unstaged)? + } else { + let patch: String = pending.iter().map(|entry| entry.patch.as_str()).collect(); + restore_selected(r, &shelves.snapshot, &patch, &shelves.prefix, allow_unstaged)? + }; + let local = |file: &crate::PatchFile| file.path.strip_prefix(&shelves.prefix).unwrap_or(&file.path).to_owned(); + let owned: Vec<_> = owned.iter().map(|files| files.iter().map(local).collect::>()).collect(); + // A rename conflict may have a path that does not appear in any original shelf. + if conflicts.iter().all(|path| owned.iter().flatten().any(|file| file == path)) { + for (entry, files) in pending.iter().zip(owned) { + if files.iter().all(|file| !conflicts.contains(file)) { + crate::shelf::delete(&shelves.directory, &entry.id)?; + } + } + } + Ok(conflicts) +} + +/// Keep the index state of the remaining files when a shelf or some of its paths were removed. +fn restore_selected( + r: &Repo, + snapshot: &str, + patch: &str, + prefix: &str, + allow_unstaged: bool, +) -> IdeResult> { + let base = format!("{snapshot}^1"); + let working = crate::patch::shelf_tree_patch_with_prefix(r, &base, snapshot, prefix)?; + let staged = crate::patch::shelf_tree_patch_with_prefix(r, &base, &format!("{snapshot}^2"), prefix)?; + let originals: HashMap<_, _> = crate::patch::sections(&staged) + .into_iter() + .chain(crate::patch::sections(&working)) + .map(|(section, file)| (file.path, section)) + .collect(); + let selected = crate::patch::sections(patch); + if selected.iter().any(|(section, file)| originals.get(&file.path) != Some(section)) { + return Ok(crate::patch::apply_with_prefix(r, patch, prefix)?.conflicts); + } + let paths: HashSet<_> = selected.into_iter().map(|(_, file)| file.path).collect(); + let select = |source: &str| -> String { + crate::patch::sections(source) + .into_iter() + .filter(|(_, file)| paths.contains(&file.path)) + .map(|(section, _)| section) + .collect() + }; + let indexed = snapshot_tree(r, &base, &select(&staged), prefix)?; + let worktree = snapshot_tree(r, &base, &select(&working), prefix)?; + let commit = |tree: &str, parents: &[&str]| -> IdeResult { + let mut args = vec![ + "-c", + "user.name=OpenIDEA", + "-c", + "user.email=openidea@localhost", + "commit-tree", + tree, + "--no-gpg-sign", + "-m", + "Saved local changes", + ]; + for parent in parents { + args.extend(["-p", parent]); + } + Ok(run(r.root(), &args, None)?.stdout_str().trim().to_owned()) + }; + let indexed = commit(&indexed, &[&base])?; + let snapshot = commit(&worktree, &[&base, &indexed])?; + apply_snapshot(r, &snapshot, allow_unstaged) +} + +fn snapshot_tree(r: &Repo, base: &str, patch: &str, prefix: &str) -> IdeResult { + let index = cli::TempIndex::new(r); + let env = index.env(); + cli::run_env(r.root(), &["read-tree", base], None, &env)?; + if !patch.is_empty() { + let strip = crate::patch::strip_option(prefix); + let mut args = vec!["apply", "--cached", "--binary", "--whitespace=nowarn"]; + args.extend(strip.as_deref()); + args.push("-"); + cli::run_env(r.root(), &args, Some(patch.as_bytes()), &env)?; + } + Ok(cli::run_env(r.root(), &["write-tree"], None, &env)?.stdout_str().trim().to_owned()) +} + +fn restore_shelf( + r: &Repo, + directory: &std::path::Path, + entry: &str, + snapshot: &str, + allow_unstaged: bool, +) -> IdeResult> { + match crate::shelf::pending_snapshot(directory, entry, snapshot)? { + None => Ok(Vec::new()), + Some(false) => Ok(crate::shelf::unshelve(r, directory, entry, true)?.conflicts), + Some(true) => { + crate::shelf::materialize_snapshot(r, directory, entry)?; + let conflicts = apply_snapshot(r, snapshot, allow_unstaged)?; + if conflicts.is_empty() { + crate::shelf::delete(directory, entry)?; + } + Ok(conflicts) + } + } } /// Brings the saved changes back once no operation is in progress. Fails when they come /// back with conflicts (they then also stay in the stash). pub(crate) fn restore(r: &Repo) -> IdeResult<()> { + restore_locked(r, None) +} + +pub(crate) fn finish_batch(r: &Repo, batch: &str) -> IdeResult<()> { + restore_locked(r, Some(batch)) +} + +fn restore_locked(r: &Repo, batch: Option<&str>) -> IdeResult<()> { + if !r.git_dir.join(MARKER).exists() { + return Ok(()); + } + let _stash_lock = crate::write::lock_stashes(r)?; + restore_saved(r, batch) +} + +fn restore_saved(r: &Repo, batch: Option<&str>) -> IdeResult<()> { let marker = r.git_dir.join(MARKER); - let Ok(saved) = std::fs::read_to_string(&marker) else { return Ok(()) }; - if r.branch_info()?.operation.is_some() { + let saved = match std::fs::read_to_string(&marker) { + Ok(saved) => saved, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error.into()), + }; + if r.operation()?.is_some() || !unmerged_paths(r)?.is_empty() { return Ok(()); } - let _ = std::fs::remove_file(&marker); let saved = saved.trim(); - let stashes = run(r.root(), &["stash", "list", "--format=%H"], None)?.stdout_str(); - let Some(index) = stashes.lines().position(|id| id.trim() == saved) else { return Ok(()) }; - let entry = format!("stash@{{{index}}}"); - if cli::run_raw(r.root(), &["stash", "pop", "-q", "--index", &entry], None)?.code == Some(0) { + let parsed = if saved.starts_with('{') { + Some(serde_json::from_str::(saved).map_err(|e| IdeError::internal(e.to_string()))?) + } else { + None + }; + let saved_batch = match &parsed { + Some(Saved::Shelves(shelves)) => shelves.batch.as_deref(), + _ => None, + }; + let restore = match batch { + Some(batch) => saved_batch == Some(batch), + None => !saved_batch.is_some_and(crate::shelf::is_active_batch), + }; + if !restore { return Ok(()); } - // The staged part no longer applies as it was: bring everything back unstaged. - if unmerged_paths(r)?.is_empty() && cli::run_raw(r.root(), &["stash", "pop", "-q", &entry], None)?.code == Some(0) { + let saved = match parsed { + Some(Saved::Stash(stash)) => selected_stash_index(r, &stash)?.map(|_| Saved::Stash(stash)), + Some(shelf) => Some(shelf), + None => { + let mut matches = r.stashes()?.into_iter().filter(|stash| stash.id == saved); + let stash = matches.next(); + if matches.next().is_some() { + return Err(IdeError::invalid("Could not identify the stash containing the saved local changes")); + } + stash.map(Saved::Stash) + } + }; + let Some(saved) = saved else { + std::fs::remove_file(marker)?; return Ok(()); + }; + let message = match &saved { + Saved::Stash(_) => "local changes were restored with conflicts; resolve them (a copy stays in the stash)", + Saved::Shelf { .. } | Saved::Shelves(_) => { + "Local changes were restored with conflicts. A copy stays on the Shelf." + } + }; + if !restore_entry(r, saved, true)?.is_empty() { + return Err(IdeError::invalid(message)); } - Err(IdeError::invalid("local changes were restored with conflicts; resolve them (a copy stays in the stash)")) + Ok(()) } /// Runs `op` with the local changes put aside, and brings them back if it finished. diff --git a/crates/ide-vcs/src/push_preview.rs b/crates/ide-vcs/src/push_preview.rs new file mode 100644 index 000000000..80f72daa3 --- /dev/null +++ b/crates/ide-vcs/src/push_preview.rs @@ -0,0 +1,489 @@ +use gix::bstr::{BStr, ByteSlice}; +use ide_core::error::ErrorKind; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use serde::{Deserialize, Serialize}; +use specta::Type; + +use crate::{ + OutgoingCommits, Repo, cli, + ops::{remote_fetch_url, remote_push_urls}, + refs, +}; + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PushSelection { + /// A local branch. A detached source has no branch and requires a commit ID. + pub branch: Option, + pub revision: Option, + pub remote: String, + pub target: String, + /// A configured non-branch destination, for example a Gerrit review ref. + #[serde(default)] + pub special_ref: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DefaultPushTarget { + pub selection: PushSelection, + pub set_upstream: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +pub struct CommitPushTarget { + pub branch: Option, + pub destination: Option, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)] +pub struct PushTargetChoices { + pub branch: Option, + pub destination: Option, + pub destinations: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PushInspection { + pub state: PushTargetState, + pub local_tip: String, + /// An empty value expects the branch to be absent. Null means no tip was available. + pub remote_tip: Option, + pub remote_commits: u32, + pub remote_checked: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum PushTargetState { + Ready, + Diverged, + FetchRequired, +} + +impl PushSelection { + pub(crate) fn refs(&self, repo: &Repo, cancel: &CancellationToken) -> IdeResult<(Option, String, String)> { + let source = self.branch.as_ref().map(|branch| format!("refs/heads/{branch}")); + let target = self.target_ref(repo, cancel)?; + if let Some(source) = source.as_deref() { + cli::run_cancellable(repo.root(), &["check-ref-format", source], cancel)?; + } + let rev = if let Some(source) = source.as_deref() { + self.revision.as_deref().unwrap_or(source) + } else { + self.revision + .as_deref() + .filter(|rev| gix::ObjectId::from_hex(rev.as_bytes()).is_ok()) + .ok_or_else(|| IdeError::invalid("A detached push requires a commit ID."))? + }; + let local_tip = commit_id(repo, rev, cancel)?; + Ok((source, target, local_tip)) + } + + fn target_ref(&self, repo: &Repo, cancel: &CancellationToken) -> IdeResult { + let target = if self.special_ref { + if !self.target.starts_with("refs/") { + return Err(IdeError::invalid("Invalid push destination")); + } + self.target.clone() + } else { + format!("refs/heads/{}", self.target) + }; + cli::run_cancellable(repo.root(), &["check-ref-format", &target], cancel)?; + Ok(target) + } +} + +fn commit_id(repo: &Repo, rev: &str, cancel: &CancellationToken) -> IdeResult { + let rev = format!("{rev}^{{commit}}"); + let output = cli::run_cancellable(repo.root(), &["rev-parse", "--verify", "--end-of-options", &rev], cancel)?; + Ok(output.stdout_str().trim().to_owned()) +} + +impl Repo { + /// Prefer the checked-out branch if it contains the selected commit, then another + /// containing local branch. A tag or remote branch alone is a detached source. + pub fn commit_push_target(&self, revision: &str, cancel: &CancellationToken) -> IdeResult { + let choices = self.resolve_push_targets(None, Some(revision), cancel, false)?; + Ok(CommitPushTarget { branch: choices.branch, destination: choices.destination }) + } + + /// The destination shown by Push and used by Commit and Push for a local source. + pub fn default_push_target(&self, branch: Option<&str>) -> IdeResult> { + self.resolve_push_targets(branch, None, &CancellationToken::new(), false).map(|choices| choices.destination) + } + + /// Resolve one source and its configured destination on every available remote. + pub fn push_target_choices( + &self, + branch: Option<&str>, + commit: Option<&str>, + cancel: &CancellationToken, + ) -> IdeResult { + self.resolve_push_targets(branch, commit, cancel, true) + } + + fn commit_push_source(&self, revision: &str, cancel: &CancellationToken) -> IdeResult<(Option, String)> { + let revision = commit_id(self, revision, cancel)?; + let refs = cli::run_cancellable( + self.root(), + &[ + "for-each-ref", + &format!("--contains={revision}"), + "--sort=version:refname", + "--format=%(HEAD)%(refname:lstrip=2)", + "refs/heads/", + ], + cancel, + )? + .stdout_str(); + let local = || refs.lines().filter_map(|line| line.strip_prefix(' ')); + let branch = refs + .lines() + .find_map(|line| line.strip_prefix('*')) + .or_else(|| local().find(|name| matches!(*name, "main" | "master"))) + .or_else(|| local().next()); + Ok((branch.map(str::to_owned), revision)) + } + + fn resolve_push_targets( + &self, + branch: Option<&str>, + commit: Option<&str>, + cancel: &CancellationToken, + alternatives: bool, + ) -> IdeResult { + let repo = self.gix()?; + let selected = commit.map(|commit| self.commit_push_source(commit, cancel)).transpose()?; + let branch = selected.as_ref().map_or(branch, |(branch, _)| branch.as_deref()); + let head = repo.head_name().map_err(crate::repo::gx)?; + let source = if let Some(branch) = branch { + let reference = + repo.try_find_reference(format!("refs/heads/{branch}").as_str()).map_err(crate::repo::gx)?; + let Some(reference) = reference else { return Ok(PushTargetChoices::default()) }; + Some(reference.name().to_owned()) + } else if selected.is_none() { + head.clone() + } else { + None + }; + let revision = selected + .map(|(_, revision)| revision) + .or_else(|| if source.is_some() { None } else { repo.head_id().ok().map(|tip| tip.to_string()) }); + let branch = source.as_ref().map(|name| name.as_ref().shorten().to_str_lossy().into_owned()); + if source.is_none() && revision.is_none() { + return Ok(PushTargetChoices::default()); + } + let names = repo.remote_names(); + let remote = default_push_remote(&repo, &names, branch.as_deref()); + let make = |remote: &BStr| -> IdeResult { + if let Some(source) = &source { + let remote = repo.find_remote(remote).map_err(crate::repo::gx)?; + let mut target = branch_push_target(&repo, source.as_ref(), &remote)?; + if let Some(revision) = &revision { + target.selection.revision = Some(revision.clone()); + target.set_upstream = false; + } + return Ok(target); + } + detached_push_target( + &repo, + revision.as_deref().expect("a detached source has a revision"), + remote, + head.as_ref().map(|head| head.as_ref().shorten()), + ) + }; + let destination = remote.map(make).transpose()?; + let destinations = + if alternatives { names.iter().filter_map(|name| make(name.as_bstr()).ok()).collect() } else { Vec::new() }; + Ok(PushTargetChoices { branch, destination, destinations }) + } +} + +fn default_push_remote<'names>( + repo: &gix::Repository, + names: &'names gix::remote::Names, + branch: Option<&str>, +) -> Option<&'names BStr> { + let preferred = branch.and_then(|branch| repo.branch_remote_name(branch, gix::remote::Direction::Push)); + let remote = match preferred.as_ref().map(|name| name.as_bstr()) { + Some(name) if name != "." => names.iter().find(|candidate| candidate.as_bstr() == name), + _ => names.iter().find(|name| name.as_bstr() == "origin").or_else(|| names.iter().next()), + }; + remote.map(|name| name.as_bstr()) +} + +fn branch_push_target( + repo: &gix::Repository, + source: &gix::refs::FullNameRef, + configured: &gix::Remote<'_>, +) -> IdeResult { + let remote = configured.name().ok_or_else(|| IdeError::invalid("Unknown push remote"))?.as_bstr(); + let branch = source.shorten().to_str_lossy().into_owned(); + let upstream_remote = repo.branch_remote_name(branch.as_str(), gix::remote::Direction::Fetch); + let upstream = + repo.branch_remote_ref_name(source, gix::remote::Direction::Fetch).transpose().map_err(crate::repo::gx)?; + let remote_name = remote.to_str_lossy().into_owned(); + let specs = configured.refspecs(gix::remote::Direction::Push); + let target = configured_destination(repo, source, &branch, specs) + .or_else(|| { + (upstream_remote.as_ref().map(|upstream| upstream.as_bstr()) == Some(remote)) + .then_some(upstream.as_ref()) + .flatten() + .map(|name| name.as_bstr().to_str_lossy().into_owned()) + }) + .unwrap_or_else(|| source.as_bstr().to_str_lossy().into_owned()); + let tracking_prefix = format!("refs/remotes/{remote_name}/"); + let (target, special_ref) = + if let Some(short) = target.strip_prefix("refs/heads/").or_else(|| target.strip_prefix(&tracking_prefix)) { + (short.to_owned(), false) + } else { + let special = target.starts_with("refs/"); + (target, special) + }; + let tracking = format!("refs/remotes/{remote_name}/{target}"); + let set_upstream = !special_ref + && upstream.is_none() + && repo.try_find_reference(tracking.as_str()).map_err(crate::repo::gx)?.is_none(); + Ok(DefaultPushTarget { + selection: PushSelection { branch: Some(branch), revision: None, remote: remote_name, target, special_ref }, + set_upstream, + }) +} + +fn push_tracking_tip(remote: &gix::Remote<'_>, target: &str) -> Option<(String, gix::ObjectId)> { + use gix::remote::Direction::{Fetch, Push}; + let fetch_url = remote.url(Fetch)?; + let mut push_urls = remote.urls(Push); + if push_urls.next()? != fetch_url || push_urls.next().is_some() { + return None; + } + let target_ref = format!("refs/heads/{target}"); + let null = remote.repo().object_hash().null(); + let group = + gix::refspec::MatchGroup { specs: remote.refspecs(Fetch).iter().map(gix::refspec::RefSpec::to_ref).collect() }; + let matches = group.match_lhs(std::iter::once(gix::refspec::match_group::Item { + full_ref_name: target_ref.as_str().into(), + target: &null, + object: None, + })); + let mut destinations = matches.mappings.iter().filter_map(|mapping| mapping.rhs.as_deref()); + let tracking = destinations.next()?; + if destinations.any(|other| other != tracking) { + return None; + } + let mut reference = remote.repo().try_find_reference(tracking).ok()??; + let name = crate::repo::to_string(reference.name().as_bstr()); + let tip = reference.peel_to_id().ok()?.detach(); + Some((name, tip)) +} + +pub(crate) fn outgoing_commits( + repo: &gix::Repository, + remotes: &gix::remote::Names, + source: &gix::refs::FullNameRef, + local: gix::ObjectId, + counted_upstream: Option<(gix::ObjectId, u32)>, +) -> Option { + let name = source.shorten().to_str_lossy(); + let remote = repo.find_remote(default_push_remote(repo, remotes, Some(&name))?).ok()?; + let target = branch_push_target(repo, source, &remote).ok()?.selection; + if target.special_ref { + return None; + } + let (reference, tip) = push_tracking_tip(&remote, &target.target)?; + let count = if tip == local { + 0 + } else if let Some((_, count)) = counted_upstream.filter(|(upstream, _)| *upstream == tip) { + count + } else { + crate::refs::count_commits(repo, local, tip).ok()? + }; + Some(OutgoingCommits { remote: target.remote, branch: target.target, reference, count }) +} + +impl Repo { + /// Compare the selected source with the destination actually used by Git push. + pub fn inspect_push( + &self, + selection: &PushSelection, + live: bool, + cancel: &CancellationToken, + ) -> IdeResult { + let _scope = self.execution_scope(); + let (source, target, local_tip) = selection.refs(self, cancel)?; + let urls = remote_push_urls(self, &selection.remote, cancel)?; + let mut result = PushInspection { + state: PushTargetState::Ready, + local_tip, + remote_tip: None, + remote_commits: 0, + remote_checked: selection.special_ref, + }; + if selection.special_ref { + return Ok(result); + } + if urls.len() != 1 { + return Ok(result); + } + + let mut advertised = None; + if live { + match cli::run_with_saved_credentials_raw( + self.root(), + &["ls-remote", "--exit-code", "--refs", "--", &urls[0], &target], + cancel, + ) { + Ok(output) if output.code == Some(2) => { + result.remote_checked = true; + result.remote_tip = Some(String::new()); + return Ok(result); + } + Ok(output) if output.code == Some(0) => { + advertised = output + .stdout_str() + .lines() + .filter_map(|line| line.split_once('\t')) + .find(|(_, name)| *name == target) + .and_then(|(id, _)| gix::ObjectId::from_hex(id.as_bytes()).ok()) + .map(|id| id.to_string()); + result.remote_checked = advertised.is_some(); + } + Err(error) if error.kind == ErrorKind::Cancelled => return Err(error), + _ => {} + } + } + // Neither a fetch ref nor its observation describes a separate push endpoint. + let tip = advertised.or_else(|| { + if remote_fetch_url(self, &selection.remote, cancel).ok()? != urls[0] { + return None; + } + let repo = self.gix().ok()?; + let remote = repo.find_remote(selection.remote.as_str()).ok()?; + let (_, tracked) = push_tracking_tip(&remote, &selection.target)?; + let tracked = tracked.to_string(); + let observed = source.as_deref().and_then(|source| { + let reference = repo.find_reference(source).ok()?; + let tracking = refs::configured_upstream(&repo, reference.name())?; + if tracking.remote != selection.remote || tracking.branch != selection.target { + return None; + } + self.observed_incoming_tip(selection.branch.as_deref()?, &tracking, &tracked, &urls[0]) + }); + Some(observed.unwrap_or(tracked)) + }); + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let Some(tip) = tip else { return Ok(result) }; + if let Err(error) = commit_id(self, &tip, cancel) { + if error.kind == ErrorKind::Cancelled { + return Err(error); + } + result.state = PushTargetState::FetchRequired; + result.remote_tip = Some(tip); + return Ok(result); + } + let range = format!("{}...{tip}", result.local_tip); + let counts = cli::run_cancellable(self.root(), &["rev-list", "--left-right", "--count", &range], cancel)?; + let counts = counts.stdout_str(); + if let Some((ahead, behind)) = counts.trim().split_once('\t') + && ahead.parse::().is_ok_and(|ahead| ahead > 0) + && let Ok(behind) = behind.parse::() + && behind > 0 + { + result.state = PushTargetState::Diverged; + result.remote_commits = behind; + } + result.remote_tip = Some(tip); + Ok(result) + } + + pub fn fetch_push_target( + &self, + selection: &PushSelection, + cancel: &CancellationToken, + out: &dyn Fn(String), + ) -> IdeResult<()> { + let _scope = self.execution_scope(); + let target = selection.target_ref(self, cancel)?; + let urls = remote_push_urls(self, &selection.remote, cancel)?; + let [url] = urls.as_slice() else { + return Err(IdeError::invalid("The remote has multiple push URLs.")); + }; + if &remote_fetch_url(self, &selection.remote, cancel)? == url { + // The configured fetch refspec maps this branch to its remote-tracking ref. + cli::run_streaming( + self.root(), + &["fetch", "--progress", "--no-tags", "--no-write-fetch-head", "--", &selection.remote, &target], + cancel, + out, + ) + } else { + // A separate push endpoint must not change the fetch endpoint's tracking refs. + cli::run_cancellable( + self.root(), + &["fetch", "--no-tags", "--no-write-fetch-head", "--", url, &target], + cancel, + ) + .map(|_| ()) + } + } +} + +fn detached_push_target( + repo: &gix::Repository, + revision: &str, + remote: &BStr, + current_branch: Option<&BStr>, +) -> IdeResult { + let remote = remote.to_str_lossy().into_owned(); + let mut target = current_branch.map_or_else(|| "detached".to_owned(), |branch| branch.to_str_lossy().into_owned()); + let mut suffix = 2; + loop { + let tracking = format!("refs/remotes/{remote}/{target}"); + if current_branch.is_some() || repo.try_find_reference(tracking.as_str()).map_err(crate::repo::gx)?.is_none() { + return Ok(DefaultPushTarget { + selection: PushSelection { + branch: None, + revision: Some(revision.to_owned()), + remote, + target, + special_ref: false, + }, + set_upstream: false, + }); + } + target = format!("detached{suffix}"); + suffix += 1; + } +} + +fn configured_destination( + repo: &gix::Repository, + source: &gix::refs::FullNameRef, + branch: &str, + specs: &[gix::refspec::RefSpec], +) -> Option { + let mut wildcards = Vec::new(); + for spec in specs.iter().map(gix::refspec::RefSpec::to_ref) { + let (Some(lhs), Some(rhs)) = (spec.source(), spec.destination()) else { continue }; + if lhs == "HEAD" || lhs == branch || lhs == source.as_bstr() { + return Some(rhs.to_str_lossy().into_owned()); + } + if lhs.contains(&b'*') { + wildcards.push(spec); + } + } + let null_id = repo.object_hash().null(); + gix::refspec::MatchGroup { specs: wildcards } + .match_lhs(std::iter::once(gix::refspec::match_group::Item { + full_ref_name: source.as_bstr(), + target: &null_id, + object: None, + })) + .mappings + .into_iter() + .find_map(|m| m.rhs.map(|rhs| rhs.to_str_lossy().into_owned())) +} diff --git a/crates/ide-vcs/src/push_report.rs b/crates/ide-vcs/src/push_report.rs new file mode 100644 index 000000000..dca9f49a2 --- /dev/null +++ b/crates/ide-vcs/src/push_report.rs @@ -0,0 +1,58 @@ +use crate::cli; +use ide_core::error::{ErrorData, ErrorKind, PushRefResult, PushRefStatus, PushReport}; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use std::path::Path; + +pub(crate) fn run( + report: &mut PushReport, + root: &Path, + args: &[&str], + cancel: &CancellationToken, + on_output: &dyn Fn(String), +) -> IdeResult<()> { + let mut refs = Vec::new(); + let result = cli::run_streaming_stdout(root, args, cancel, on_output, &mut |line| { + if let Some(result) = parse_ref(line) { + refs.push(result); + } + }); + report.refs.extend(refs.into_iter().map(|(reference, status, summary)| { + let commits = (status == PushRefStatus::FastForward).then(|| count_commits(root, &summary, cancel)).flatten(); + PushRefResult { reference, status, commits } + })); + result.map_err(|error| with_partial_push(error, report)) +} + +pub(crate) fn with_partial_push(mut error: IdeError, report: &PushReport) -> IdeError { + if error.kind != ErrorKind::Cancelled && report.refs.iter().any(|update| update.status != PushRefStatus::UpToDate) { + error.data = Some(ErrorData::PushPartiallyApplied { report: Box::new(report.clone()) }); + } + error +} + +fn parse_ref(line: &str) -> Option<(String, PushRefStatus, String)> { + let (flag, fields) = line.split_once('\t')?; + let status = match flag { + " " => PushRefStatus::FastForward, + "+" => PushRefStatus::Forced, + "*" => PushRefStatus::Created, + "=" => PushRefStatus::UpToDate, + "-" => PushRefStatus::Deleted, + _ => return None, + }; + let (refs, summary) = fields.split_once('\t')?; + let (_, reference) = refs.split_once(':')?; + if !reference.starts_with("refs/") || reference.bytes().any(|byte| byte.is_ascii_whitespace()) { + return None; + } + Some((reference.to_owned(), status, summary.trim().to_owned())) +} + +fn count_commits(root: &Path, range: &str, cancel: &CancellationToken) -> Option { + let (from, to) = range.split_once("..")?; + let is_hex = |name: &str| (4..=64).contains(&name.len()) && name.bytes().all(|byte| byte.is_ascii_hexdigit()); + if !is_hex(from) || !is_hex(to) { + return None; + } + cli::run_cancellable(root, &["rev-list", "--count", range, "--"], cancel).ok()?.stdout_str().trim().parse().ok() +} diff --git a/crates/ide-vcs/src/rebase_editor.rs b/crates/ide-vcs/src/rebase_editor.rs new file mode 100644 index 000000000..7c4b392f5 --- /dev/null +++ b/crates/ide-vcs/src/rebase_editor.rs @@ -0,0 +1,408 @@ +use crate::{RebaseAction, RebaseOptions, Repo, cli, log_index::subject, manage::rebase_args, ops, repo::resolve}; +use gix::bstr::ByteSlice; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::cell::{Cell, RefCell}; +use std::collections::{BTreeMap, HashSet}; +use std::ffi::OsStr; +use std::fs; + +#[derive(Deserialize, Serialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum RebaseEditorOperation { + Start { upstream: Option, options: RebaseOptions }, + Continue { stage: bool }, + Skip, +} + +#[derive(Clone, Copy, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum RebaseEditKind { + Plan, + Message, +} + +#[derive(Serialize, Type)] +pub struct RebaseEdit { + pub kind: RebaseEditKind, + pub text: String, + pub plan: Option>, +} + +#[derive(Deserialize, Type)] +pub struct RebaseEditorReply { + pub text: String, + #[serde(default)] + pub rewords: BTreeMap, +} + +impl From for RebaseEditorReply { + fn from(text: String) -> Self { + Self { text, rewords: BTreeMap::new() } + } +} + +#[derive(Clone, Copy, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum RebaseFixupMessage { + Replace, + Edit, +} + +#[derive(Serialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum RebaseTodoRow { + Commit { + line: usize, + action: RebaseAction, + #[serde(rename = "fixupMessage", skip_serializing_if = "Option::is_none")] + fixup_message: Option, + id: String, + revision: String, + author: String, + summary: String, + message: String, + }, + UpdateRef { + line: usize, + reference: String, + }, +} + +// Git removes the saved drafts when it removes its rebase state. +const EDITOR_MARKER: &str = "rebase-merge/openidea-editor"; +const EDITOR_COMMENT: &str = "\u{1}"; +const EDITOR_COMMENT_CONFIG: &str = "core.commentChar=\u{1}"; +const SCISSORS: &str = "------------------------ >8 ------------------------"; + +#[derive(Deserialize, Serialize)] +struct SavedEditor { + rewords: BTreeMap, +} + +// Blank lines keep the editor tied to the host's output pipe and are dropped by the reader. +const EDITOR: &str = r#"set -e +dir=$OPENIDEA_GIT_EDITOR_DIR +cp -- "$2" "$dir/input" +printf '\n%s:%s\n' "$OPENIDEA_GIT_EDITOR_SIGNAL" "$1" +while [ -d "$dir" ] && [ ! -f "$dir/reply" ] && [ ! -f "$dir/cancel" ]; do + sleep 0.1 + printf '\n' +done +[ ! -f "$dir/cancel" ] || exit 1 +cp -- "$dir/reply" "$2" +rm -- "$dir/reply" +"#; + +impl Repo { + pub fn rebase_editor_operation( + &self, + operation: RebaseEditorOperation, + cancel: &CancellationToken, + out: &dyn Fn(String), + edit: &dyn Fn(RebaseEdit) -> Option, + ) -> IdeResult<()> { + if let RebaseEditorOperation::Start { upstream, options } = operation { + return self.rebase_with_editor(upstream.as_deref(), &options, cancel, out, edit); + } + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let _scope = self.execution_scope(); + if self.operation()?.as_deref() != Some("rebase") { + return Err(IdeError::invalid("No rebase in progress")); + } + let run = |args: &[&str]| { + if self.git_dir.join(EDITOR_MARKER).is_file() { + self.run_rebase_editor(args, false, cancel, out, edit) + } else { + cli::run_streaming(self.root(), args, cancel, out) + } + }; + match operation { + RebaseEditorOperation::Start { .. } => unreachable!(), + RebaseEditorOperation::Continue { stage } => ops::continue_op(self, stage, run), + RebaseEditorOperation::Skip => ops::skip_op(self, run), + } + } + + /// Lets Git generate and execute its own interactive plan, including merge instructions. + pub fn rebase_with_editor( + &self, + upstream: Option<&str>, + options: &RebaseOptions, + cancel: &CancellationToken, + out: &dyn Fn(String), + edit: &dyn Fn(RebaseEdit) -> Option, + ) -> IdeResult<()> { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let _scope = self.execution_scope(); + let mut args = rebase_args(upstream, options)?; + self.validate_rebase(options)?; + args.insert(1, "--interactive".into()); + let args: Vec<_> = args.iter().map(String::as_str).collect(); + crate::preserve::around(self, "Local changes saved before rebase", || { + self.run_rebase_editor(&args, true, cancel, out, edit) + }) + } + + fn run_rebase_editor( + &self, + args: &[&str], + starting: bool, + cancel: &CancellationToken, + out: &dyn Fn(String), + edit: &dyn Fn(RebaseEdit) -> Option, + ) -> IdeResult<()> { + let session = tempfile::Builder::new().prefix("openidea-git-editor-").tempdir()?; + let dir = session.path(); + let script = dir.join("editor.sh"); + fs::write(&script, EDITOR)?; + let sequence = format!("sh {} plan", ops::quote_for_shell(&script)); + let message = format!("sh {} message", ops::quote_for_shell(&script)); + let signal = dir.file_name().and_then(OsStr::to_str).unwrap_or("openidea-git-editor"); + let dir_env = dir.to_string_lossy().replace('\\', "/"); + let env = [ + ("GIT_SEQUENCE_EDITOR", OsStr::new(&sequence)), + ("GIT_EDITOR", OsStr::new(&message)), + ("OPENIDEA_GIT_EDITOR_DIR", OsStr::new(&dir_env)), + ("OPENIDEA_GIT_EDITOR_SIGNAL", OsStr::new(signal)), + ]; + let declined = Cell::new(false); + let pipe_failed = Cell::new(false); + let editor_error = RefCell::new(None); + let marker = self.git_dir.join(EDITOR_MARKER); + let saved = fs::read(&marker).unwrap_or_default(); + let editor = serde_json::from_slice::(&saved).ok(); + // Older sessions used the repository's own comment convention in their saved state. + let private_comments = starting || editor.is_some(); + let drafts = RefCell::new( + editor.map(|editor| editor.rewords).or_else(|| serde_json::from_slice(&saved).ok()).unwrap_or_default(), + ); + let comment = todo_comment(self); + let mut command = Vec::with_capacity(args.len() + 2); + if private_comments { + command.extend(["-c", EDITOR_COMMENT_CONFIG]); + } + command.extend_from_slice(args); + // Once the editor has declined, let Git handle the exit and clean up its rebase state. + let should_cancel = || pipe_failed.get() || (!declined.get() && cancel.is_cancelled()); + let result = cli::run_streaming_env_until(self.root(), &command, &env, &should_cancel, &|line| { + let prompt = line.strip_prefix(signal).and_then(|suffix| match suffix { + ":plan" => Some(RebaseEditKind::Plan), + ":message" => Some(RebaseEditKind::Message), + _ => None, + }); + let Some(kind) = prompt else { + out(line); + return; + }; + let reply = (|| -> IdeResult<()> { + let input = dir.join("input"); + let text = fs::read_to_string(&input)?; + fs::remove_file(input)?; + let is_plan = matches!(kind, RebaseEditKind::Plan); + let plan_comment = if private_comments { EDITOR_COMMENT } else { &comment }; + let plan = if is_plan { simple_plan(self, &text, plan_comment, cancel) } else { None }; + let prepared = if is_plan { None } else { reword_for_git_step(self, &drafts.borrow()) }; + let answer = prepared.map(RebaseEditorReply::from).or_else(|| { + let text = match (private_comments, is_plan) { + (true, true) => display_todo_comments(&text, &comment), + (true, false) => message_body(&text), + _ => text, + }; + edit(RebaseEdit { kind, text, plan }) + }); + if let Some(mut answer) = answer { + let pending = dir.join("reply.tmp"); + if is_plan && private_comments { + // Help and notes have no effect on the replay. The saved todo remains + // readable by Git using the repository's own comment convention. + answer.text = answer + .text + .split_inclusive('\n') + .filter(|line| !todo_line(line).starts_with(&comment)) + .collect(); + } + fs::write(&pending, &answer.text)?; + if is_plan { + let approved = approved_rewords(self, &answer.text, &answer.rewords); + let editor = SavedEditor { rewords: approved }; + let bytes = serde_json::to_vec(&editor).map_err(|e| IdeError::internal(e.to_string()))?; + fs::write(&marker, bytes)?; + drafts.replace(editor.rewords); + } + fs::rename(&pending, dir.join("reply"))?; + } else { + declined.set(true); + fs::write(dir.join("cancel"), [])?; + } + Ok(()) + })(); + if let Err(error) = reply { + *editor_error.borrow_mut() = Some(error); + if fs::write(dir.join("cancel"), []).is_err() { + pipe_failed.set(true); + } + } + }); + if let Some(error) = editor_error.into_inner() { + return Err(error); + } + if declined.get() { + return Err(IdeError::cancelled()); + } + result + } +} + +fn todo_line(line: &str) -> &str { + line.trim_start_matches([' ', '\t']) +} + +fn todo_comment(r: &Repo) -> String { + r.gix() + .ok() + .and_then(|repo| { + let config = repo.config_snapshot(); + config + .string("core.commentString") + .or_else(|| config.string("core.commentChar")) + .map(|comment| comment.to_str_lossy().into_owned()) + }) + .filter(|comment| !comment.is_empty() && comment != "auto" && !comment.starts_with(char::is_alphabetic)) + .unwrap_or_else(|| "#".into()) +} + +fn display_todo_comments(text: &str, comment: &str) -> String { + let mut display = String::with_capacity(text.len()); + for line in text.split_inclusive('\n') { + let command = todo_line(line); + if let Some(note) = command.strip_prefix(EDITOR_COMMENT) { + display.push_str(&line[..line.len() - command.len()]); + display.push_str(comment); + display.push_str(note); + } else { + display.push_str(line); + } + } + display +} + +fn message_body(text: &str) -> String { + text.split_inclusive('\n') + .take_while(|line| line.strip_prefix(EDITOR_COMMENT).is_none_or(|note| note.trim() != SCISSORS)) + .filter(|line| !line.starts_with(EDITOR_COMMENT)) + .collect() +} + +struct CommitCommand<'a> { + action: RebaseAction, + revision: &'a str, + fixup_message: Option, +} + +fn commit_command(line: &str) -> Option> { + let mut words = line.split_ascii_whitespace(); + let action = match words.next()? { + "p" | "pick" => RebaseAction::Pick, + "r" | "reword" => RebaseAction::Reword, + "e" | "edit" => RebaseAction::Edit, + "s" | "squash" => RebaseAction::Squash, + "f" | "fixup" => RebaseAction::Fixup, + "d" | "drop" => RebaseAction::Drop, + _ => return None, + }; + let first = words.next()?; + let fixup_message = match (action, first) { + (RebaseAction::Fixup, "-C") => Some(RebaseFixupMessage::Replace), + (RebaseAction::Fixup, "-c") => Some(RebaseFixupMessage::Edit), + _ => None, + }; + let revision = if fixup_message.is_some() { words.next()? } else { first }; + revision.bytes().all(|b| b.is_ascii_hexdigit()).then_some(CommitCommand { action, revision, fixup_message }) +} + +fn approved_rewords(r: &Repo, text: &str, proposed: &BTreeMap) -> BTreeMap { + let mut approved = BTreeMap::new(); + if proposed.is_empty() { + return approved; + } + let Ok(repo) = r.gix() else { return approved }; + let mut seen = HashSet::new(); + for CommitCommand { action, revision, .. } in text.lines().filter_map(commit_command) { + let Ok(id) = resolve(&repo, revision) else { continue }; + let key = id.to_string(); + let Some(message) = proposed.get(&key).filter(|message| !message.trim().is_empty()) else { continue }; + if !seen.insert(id) { + approved.remove(&key); + } else if action == RebaseAction::Reword { + approved.insert(key, message.clone()); + } + } + approved +} + +fn reword_for_git_step(r: &Repo, drafts: &BTreeMap) -> Option { + if drafts.is_empty() { + return None; + } + // Git records the original object here even when HEAD already names the rewritten commit. + let done = fs::read_to_string(r.git_dir.join("rebase-merge/done")).ok()?; + let CommitCommand { action, revision, .. } = + commit_command(done.lines().rev().find(|line| !line.trim().is_empty())?)?; + if action != RebaseAction::Reword { + return None; + } + drafts.get(revision).cloned().or_else(|| { + let id = resolve(&r.gix().ok()?, revision).ok()?; + drafts.get(&id.to_string()).cloned() + }) +} + +fn simple_plan(r: &Repo, text: &str, comment: &str, cancel: &CancellationToken) -> Option> { + let repo = r.gix().ok()?; + let mut todo = Vec::new(); + let mut seen = HashSet::new(); + let mut seen_refs = HashSet::new(); + for (line, source) in text.lines().enumerate() { + let source = todo_line(source); + if source.is_empty() || source.starts_with(comment) { + continue; + } + if cancel.is_cancelled() { + return None; + } + let mut words = source.split_ascii_whitespace(); + if matches!(words.next(), Some("update-ref" | "u")) { + let reference = words.next().filter(|reference| reference.starts_with("refs/"))?; + if words.next().is_some() || !seen_refs.insert(reference) { + return None; + } + todo.push(RebaseTodoRow::UpdateRef { line, reference: reference.to_owned() }); + continue; + } + let CommitCommand { action, revision, fixup_message } = commit_command(source)?; + let id = resolve(&repo, revision).ok()?; + if !seen.insert(id) { + return None; + } + let commit = repo.find_commit(id).ok()?; + let raw = commit.message_raw_sloppy(); + let author = commit.author().ok()?.name.trim().to_str_lossy().into_owned(); + todo.push(RebaseTodoRow::Commit { + line, + action, + fixup_message, + id: id.to_string(), + revision: revision.to_owned(), + author, + summary: subject(raw), + message: raw.to_str_lossy().trim_end().to_owned(), + }); + } + (!todo.is_empty()).then_some(todo) +} diff --git a/crates/ide-vcs/src/refs.rs b/crates/ide-vcs/src/refs.rs index 833e35c2d..2b995ca25 100644 --- a/crates/ide-vcs/src/refs.rs +++ b/crates/ide-vcs/src/refs.rs @@ -1,8 +1,10 @@ //! HEAD, branches, upstream tracking and stashes via gitoxide. use crate::repo::{gx, to_string}; -use crate::{Branch, BranchInfo, Repo, Stash}; +use crate::{Branch, BranchInfo, HistoryTip, RebaseState, Repo, Stash, TrackedTip, UpstreamTracking}; +use gix::bstr::ByteSlice; use ide_core::IdeResult; +use std::io::{BufRead, BufReader}; // Filter symbolic refs before shortening; `refname:short` also strips remote `/HEAD` suffixes. pub(crate) const DIRECT_BRANCH_FORMAT: &str = "--format=%(if)%(symref)%(then)%(else)%(refname:lstrip=2)%(end)"; @@ -12,27 +14,54 @@ pub(crate) fn branch_info(r: &Repo) -> IdeResult { let head_ref = repo.head_name().map_err(gx)?; let head = head_ref.as_ref().map(|n| to_string(n.as_ref().shorten())); let head_commit = repo.head_id().ok().map(|id| id.detach()); + let upstream_tracking = head_ref.as_ref().and_then(|name| configured_upstream(&repo, name.as_ref())); let mut info = BranchInfo { head, head_commit: head_commit.map(|id| id.to_string()), upstream: None, + upstream_tracking, + tracked_tip: None, ahead: 0, behind: 0, + outgoing: None, operation: operation(&repo), + rebase: None, }; + if info.operation.as_deref() == Some("rebase") { + info.rebase = rebase_state(repo.path()); + } + let mut counted_upstream = None; if let Some(name) = head_ref.as_ref() && let Some((upstream_name, upstream_id)) = upstream_of(&repo, name.as_ref()) { info.upstream = Some(upstream_name); + info.tracked_tip = + info.upstream_tracking.clone().map(|tracking| TrackedTip { tracking, commit: upstream_id.to_string() }); if let Some(local) = head_commit { let (a, b) = ahead_behind(&repo, local, upstream_id)?; info.ahead = a; info.behind = b; + counted_upstream = Some((upstream_id, a)); } } + if let (Some(name), Some(local)) = (head_ref.as_ref(), head_commit) { + info.outgoing = + crate::push_preview::outgoing_commits(&repo, &repo.remote_names(), name.as_ref(), local, counted_upstream); + } Ok(info) } +pub(crate) fn rebase_dir(git_dir: &std::path::Path) -> Option { + ["rebase-merge", "rebase-apply"].into_iter().map(|dir| git_dir.join(dir)).find(|dir| dir.is_dir()) +} + +fn rebase_state(git_dir: &std::path::Path) -> Option { + let dir = rebase_dir(git_dir)?; + let read = |name| std::fs::read_to_string(dir.join(name)).ok().map(|value| value.trim().to_owned()); + let branch = read("head-name")?.strip_prefix("refs/heads/").map(str::to_owned); + Some(RebaseState { original: HistoryTip { branch, commit: read("orig-head")? }, onto: read("onto")? }) +} + pub(crate) fn head(repo: &gix::Repository) -> IdeResult<(Option, Option)> { let name = repo.head_name().map_err(gx)?.map(|n| to_string(n.as_ref().shorten())); Ok((name, repo.head_id().ok().map(|id| id.to_string()))) @@ -40,25 +69,48 @@ pub(crate) fn head(repo: &gix::Repository) -> IdeResult<(Option, Option< pub(crate) fn operation(repo: &gix::Repository) -> Option { use gix::state::InProgress::*; - let op = match repo.state()? { - ApplyMailbox | ApplyMailboxRebase => "am", - Bisect => "bisect", - CherryPick | CherryPickSequence => "cherry-pick", - Merge => "merge", - Rebase | RebaseInteractive => "rebase", - Revert | RevertSequence => "revert", + let op = match repo.state() { + Some(ApplyMailbox | ApplyMailboxRebase) => "am", + Some(Bisect) => "bisect", + Some(CherryPick | CherryPickSequence) => "cherry-pick", + Some(Merge) => "merge", + Some(Rebase | RebaseInteractive) => "rebase", + Some(Revert | RevertSequence) => "revert", + None => { + // Committing a resolved step can clear its HEAD marker while Git still has a todo. + let path = repo.path().join("sequencer/todo"); + if !path.is_file() { + return None; + } + let mut first = String::new(); + BufReader::new(std::fs::File::open(path).ok()?).read_line(&mut first).ok()?; + match first.split_whitespace().next()? { + "pick" => "cherry-pick", + "revert" => "revert", + _ => return None, + } + } }; Some(op.to_string()) } /// Short upstream name (`origin/main`) and its commit. A branch whose tracking ref is gone (the /// remote branch was deleted and pruned) tracks nothing, as in IDEA. -fn upstream_of(repo: &gix::Repository, branch: &gix::refs::FullNameRef) -> Option<(String, gix::ObjectId)> { +pub(crate) fn upstream_of(repo: &gix::Repository, branch: &gix::refs::FullNameRef) -> Option<(String, gix::ObjectId)> { let tracking = repo.branch_remote_tracking_ref_name(branch, gix::remote::Direction::Fetch)?.ok()?; let id = repo.try_find_reference(tracking.as_ref()).ok()??.peel_to_id().ok()?.detach(); Some((to_string(tracking.as_ref().shorten()), id)) } +pub(crate) fn configured_upstream(repo: &gix::Repository, name: &gix::refs::FullNameRef) -> Option { + let direction = gix::remote::Direction::Fetch; + let remote = repo.branch_remote_name(name.shorten(), direction)?; + let branch = repo.branch_remote_ref_name(name, direction)?.ok()?; + let branch = branch.as_bstr().strip_prefix(b"refs/heads/")?.as_bstr(); + (remote.as_bstr() != ".") + .then(|| UpstreamTracking { remote: to_string(remote.as_bstr()), branch: to_string(branch) }) +} + /// Commits in `local` not in `upstream`, and vice versa. pub(crate) fn ahead_behind( repo: &gix::Repository, @@ -68,16 +120,17 @@ pub(crate) fn ahead_behind( if local == upstream { return Ok((0, 0)); } - let count = |tip: gix::ObjectId, hide: gix::ObjectId| -> IdeResult { - let walk = repo.rev_walk([tip]).with_hidden([hide]).all().map_err(gx)?; - let mut n = 0u32; - for info in walk { - info.map_err(gx)?; - n += 1; - } - Ok(n) - }; - Ok((count(local, upstream)?, count(upstream, local)?)) + Ok((count_commits(repo, local, upstream)?, count_commits(repo, upstream, local)?)) +} + +pub(crate) fn count_commits(repo: &gix::Repository, tip: gix::ObjectId, hide: gix::ObjectId) -> IdeResult { + let walk = repo.rev_walk([tip]).with_hidden([hide]).all().map_err(gx)?; + let mut n = 0u32; + for info in walk { + info.map_err(gx)?; + n += 1; + } + Ok(n) } fn commit_time_ms(repo: &gix::Repository, id: gix::ObjectId) -> f64 { @@ -88,6 +141,7 @@ pub(crate) fn branches(r: &Repo) -> IdeResult> { let repo = r.gix()?; let head_name = repo.head_name().map_err(gx)?; let platform = repo.references().map_err(gx)?; + let remotes = repo.remote_names(); let mut out = Vec::new(); for reference in platform.local_branches().map_err(gx)? { @@ -103,17 +157,24 @@ pub(crate) fn branches(r: &Repo) -> IdeResult> { remote: false, current, upstream: None, + tracked_tip: None, ahead: 0, behind: 0, + outgoing: None, last_commit_ms: commit_time_ms(&repo, id), commit: id.to_string(), }; + let mut counted_upstream = None; if let Some((up, up_id)) = upstream_of(&repo, full.as_ref()) { branch.upstream = Some(up); + branch.tracked_tip = configured_upstream(&repo, full.as_ref()) + .map(|tracking| TrackedTip { tracking, commit: up_id.to_string() }); let (a, b) = ahead_behind(&repo, id, up_id)?; branch.ahead = a; branch.behind = b; + counted_upstream = Some((up_id, a)); } + branch.outgoing = crate::push_preview::outgoing_commits(&repo, &remotes, full.as_ref(), id, counted_upstream); out.push(branch); } for reference in platform.remote_branches().map_err(gx)? { @@ -129,8 +190,10 @@ pub(crate) fn branches(r: &Repo) -> IdeResult> { remote: true, current: false, upstream: None, + tracked_tip: None, ahead: 0, behind: 0, + outgoing: None, last_commit_ms: commit_time_ms(&repo, id), commit: id.to_string(), }); @@ -159,13 +222,20 @@ pub(crate) fn stashes(r: &Repo) -> IdeResult> { let line = line.map_err(gx)?; let time_ms = line.signature.time.seconds as f64 * 1000.0; let id = line.new_oid.to_owned(); - let base = repo.find_commit(id).ok().and_then(|c| c.parent_ids().next().map(|p| p.to_string())); + let (base, untracked) = repo + .find_commit(id) + .map(|commit| { + let mut parents = commit.parent_ids(); + (parents.next().map(|p| p.to_string()), parents.nth(1).map(|p| p.to_string())) + }) + .unwrap_or_default(); out.push(Stash { index: index as u32, message: to_string(line.message.as_ref()), time_ms, id: id.to_string(), base, + untracked, }); } Ok(out) diff --git a/crates/ide-vcs/src/remotes.rs b/crates/ide-vcs/src/remotes.rs index 94ebc5808..f3038157c 100644 --- a/crates/ide-vcs/src/remotes.rs +++ b/crates/ide-vcs/src/remotes.rs @@ -3,9 +3,13 @@ use crate::cli; use crate::{ChangedFile, Repo}; +use gix::bstr::ByteSlice; +use ide_core::error::ErrorKind; +use ide_core::workflow_settings::FetchTagsMode; use ide_core::{CancellationToken, IdeError, IdeResult}; use serde::{Deserialize, Serialize}; use specta::Type; +use std::collections::HashSet; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -18,6 +22,27 @@ pub struct Remote { pub resolved_url: Option, } +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +pub struct FetchReport { + pub remotes: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +pub struct FetchRemoteResult { + pub remote: String, + pub pruned: Vec, + pub error: Option, +} + +fn pruned_ref(line: &str) -> Option<&str> { + // Git emits human-readable status in the C locale, including when submodule fetch is enabled. + let deleted = line.trim_ascii_start().strip_prefix('-')?.trim_ascii_start().strip_prefix("[deleted]")?; + let (from, to) = deleted.split_once("->")?; + let to = to.trim_ascii(); + (from.trim_ascii() == "(none)" && !to.is_empty() && !to.bytes().any(|byte| byte.is_ascii_whitespace())) + .then_some(to) +} + fn check_rev(rev: &str) -> IdeResult<()> { if rev.trim().is_empty() || rev.starts_with('-') { Err(IdeError::invalid(format!("invalid revision `{rev}`"))) @@ -30,9 +55,9 @@ fn check_rev(rev: &str) -> IdeResult<()> { pub(crate) fn parse_remotes(text: &str) -> Vec { let mut out: Vec = Vec::new(); for line in text.lines() { - let mut parts = line.split_whitespace(); - let (Some(name), Some(url), kind) = (parts.next(), parts.next(), parts.next()) else { continue }; - if kind.is_some_and(|k| k != "(fetch)") || out.iter().any(|r| r.name == name) { + let Some((name, url)) = line.split_once('\t') else { continue }; + let Some(url) = url.strip_suffix(" (fetch)") else { continue }; + if out.iter().any(|r| r.name == name) { continue; } out.push(Remote { name: name.to_owned(), url: url.to_owned(), resolved_url: None }); @@ -40,7 +65,44 @@ pub(crate) fn parse_remotes(text: &str) -> Vec { out } +pub(crate) fn fetch_tag_args(mode: FetchTagsMode, prune: bool) -> Vec<&'static str> { + let mut args = Vec::new(); + if prune || mode == FetchTagsMode::Sync { + args.push("--prune"); + } + args.extend(match mode { + FetchTagsMode::Auto => &[][..], + FetchTagsMode::Sync => &["--prune-tags"][..], + FetchTagsMode::Always => &["--tags", "--no-prune-tags"][..], + FetchTagsMode::Never => &["--no-tags", "--no-prune-tags"][..], + }); + args +} + +/// Pull forwards --tags and --prune, but reads tag pruning from Git configuration. +pub(crate) fn pull_tag_config(r: &Repo, mode: FetchTagsMode) -> IdeResult> { + let prune = match mode { + FetchTagsMode::Auto => return Ok(Vec::new()), + FetchTagsMode::Sync => "true", + FetchTagsMode::Always | FetchTagsMode::Never => "false", + }; + let mut config = vec![format!("fetch.pruneTags={prune}")]; + let repo = r.gix()?; + if let Some(remote) = repo.head_name().map_err(crate::repo::gx)?.and_then(|head| { + let branch = head.as_ref().shorten().to_str_lossy(); + repo.branch_remote_name(branch.as_ref(), gix::remote::Direction::Fetch) + }) { + config.push(format!("remote.{}.pruneTags={prune}", remote.as_bstr().to_str_lossy())); + } + Ok(config) +} + impl Repo { + /// Whether any remotes are configured, even before their branches have been fetched. + pub fn has_remotes(&self) -> IdeResult { + Ok(!self.gix()?.remote_names().is_empty()) + } + /// Configured remotes with their fetch URLs. pub fn remotes(&self) -> IdeResult> { let _scope = self.execution_scope(); @@ -48,6 +110,160 @@ impl Repo { Ok(parse_remotes(&out.stdout_str())) } + /// Refreshes only the selected remote's tracking branches. + pub fn fetch_remote(&self, remote: &str, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { + self.fetch_with_tags(Some(remote), FetchTagsMode::Auto, cancel, on_output) + } + + /// Fetches the named remote, or all remotes, using the project's tag policy. + pub fn fetch_with_tags( + &self, + remote: Option<&str>, + mode: FetchTagsMode, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult<()> { + let _scope = self.execution_scope(); + let mut args = vec!["fetch", "--progress"]; + args.extend(fetch_tag_args(mode, true)); + if let Some(remote) = remote { + if !self.gix()?.remote_names().iter().any(|name| name.as_bstr() == remote) { + return Err(IdeError::invalid("Unknown remote")); + } + args.extend(["--", remote]); + } else { + args.push("--all"); + } + cli::run_streaming(self.root(), &args, cancel, on_output) + } + + /// Interactive fetch. Each remote is attempted even if another fails, so the caller can + /// report both the actual deletions and the failures for this repository. + pub fn fetch_report( + &self, + remote: Option<&str>, + mode: FetchTagsMode, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult { + self.fetch_remotes_report(remote, mode, None, cancel, on_output) + } + + /// Fetches the project's remotes without asking for new credentials. + pub fn fetch_in_background( + &self, + skip: &[String], + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult { + self.fetch_remotes_report(None, FetchTagsMode::Auto, Some(skip), cancel, on_output) + } + + fn fetch_remotes_report( + &self, + remote: Option<&str>, + mode: FetchTagsMode, + background_skip: Option<&[String]>, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult { + let _scope = self.execution_scope(); + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let mut remotes = if let Some(remote) = remote { + if !self.gix()?.remote_names().iter().any(|name| name.as_bstr() == remote) { + return Err(IdeError::invalid("Unknown remote")); + } + vec![remote.to_owned()] + } else { + self.fetch_all_remotes()? + }; + if let Some(skip) = background_skip { + remotes.retain(|name| !skip.contains(name)); + } + + let mut results = Vec::with_capacity(remotes.len()); + let mut base_args = vec!["fetch", "--progress"]; + base_args.extend(fetch_tag_args(mode, true)); + for (i, remote) in remotes.iter().enumerate() { + let mut args = base_args.clone(); + if i > 0 { + args.push("--append"); + } + if remotes.len() > 1 { + on_output(format!("Fetching {remote}")); + } + args.extend(["--", remote]); + let mut pruned = Vec::new(); + let mut capture = |line: &str| { + if let Some(reference) = pruned_ref(line) { + pruned.push(reference.to_owned()); + } + }; + let result = cli::run_streaming_stderr( + self.root(), + &args, + cancel, + on_output, + &mut capture, + background_skip.is_some(), + ); + let error = result.err(); + if error.as_ref().is_some_and(|error| error.kind == ErrorKind::Cancelled) { + return Err(IdeError::cancelled()); + } + if error.is_some() && !pruned.is_empty() { + // Git can print a deletion before discovering that the ref could not be removed. + let repo = self.gix(); + pruned.retain(|name| { + repo.as_ref().is_ok_and(|repo| repo.try_find_reference(name.as_str()).is_ok_and(|r| r.is_none())) + }); + } + results.push(FetchRemoteResult { remote: remote.clone(), pruned, error }); + } + Ok(FetchReport { remotes: results }) + } + + fn fetch_all_remotes(&self) -> IdeResult> { + // Keep Git's configuration order since multiple remotes can update the same tags. + let args = ["config", "--null", "--get-regexp", r"^remote\..+\.[^.]+$"]; + let output = cli::run_raw(self.root(), &args, None)?; + if output.code != Some(0) && !(output.code == Some(1) && output.stderr.is_empty()) { + return Err(cli::failure(&args, &output.stderr, b"", output.code)); + } + let config = output.stdout_str(); + let mut remotes = Vec::new(); + let mut seen = HashSet::new(); + let mut skipped = HashSet::new(); + for item in config.split('\0') { + let (key, value) = item.split_once('\n').map_or((item, None), |(key, value)| (key, Some(value))); + let Some((name, setting)) = key.strip_prefix("remote.").and_then(|key| key.rsplit_once('.')) else { + continue; + }; + if name.starts_with('/') { + continue; + } + if seen.insert(name) { + remotes.push(name); + } + if !matches!(setting, "skipfetchall" | "skipdefaultupdate") { + continue; + } + let skip = value + .map(gix::config::Boolean::try_from) + .transpose() + .map_err(|error| IdeError::invalid(format!("{key}: {error}")))? + .is_none_or(gix::config::Boolean::is_true); + if skip { + skipped.insert(name); + } else { + skipped.remove(name); + } + } + Ok(remotes.into_iter().filter(|name| !skipped.contains(name)).map(str::to_owned).collect()) + } + /// Whether `rev` names a commit present in the object database. pub fn has_commit(&self, rev: &str) -> bool { let _scope = self.execution_scope(); @@ -105,12 +321,12 @@ mod tests { #[test] fn remotes_take_fetch_urls_once() { let text = "origin\tgit@github.com:me/app.git (fetch)\norigin\tgit@github.com:me/app.git (push)\n\ - upstream\thttps://github.com/org/app (fetch)\nupstream\tno_push (push)\n"; + upstream/test\tC:/Git Remote/app.git (fetch)\nupstream/test\tno_push (push)\n"; assert_eq!( parse_remotes(text), [ Remote { name: "origin".into(), url: "git@github.com:me/app.git".into(), resolved_url: None }, - Remote { name: "upstream".into(), url: "https://github.com/org/app".into(), resolved_url: None }, + Remote { name: "upstream/test".into(), url: "C:/Git Remote/app.git".into(), resolved_url: None }, ] ); } diff --git a/crates/ide-vcs/src/repo.rs b/crates/ide-vcs/src/repo.rs index 9831c6991..3f21f8245 100644 --- a/crates/ide-vcs/src/repo.rs +++ b/crates/ide-vcs/src/repo.rs @@ -6,6 +6,14 @@ use ide_core::{IdeError, IdeResult}; use std::path::{Component, Path, PathBuf}; use std::time::SystemTime; +#[derive(serde::Serialize, serde::Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct DiffEntry { + pub mode: String, + /// The recorded commit for a gitlink, independent of the parent's object database. + pub gitlink: Option, +} + /// Converts any displayable gitoxide error into an [`IdeError`]. pub(crate) fn gx(e: impl std::fmt::Display) -> IdeError { IdeError::internal(format!("git: {e}")) @@ -78,8 +86,12 @@ pub(crate) fn discover(path: &Path) -> IdeResult> { inner: std::sync::Mutex::new(cache), ignored: Default::default(), cli_status: Default::default(), + automatic_shelf: Default::default(), log_index: Default::default(), log_signatures: Default::default(), + conflict_mutation: Default::default(), + amend_recovery: Default::default(), + incoming_observations: Default::default(), })) } @@ -149,6 +161,41 @@ impl Repo { blob_at(&repo, &indexed, rev) } + pub fn diff_entry_at(&self, path: &Path, rev: &str) -> IdeResult> { + let _scope = self.execution_scope(); + let repo = self.gix()?; + let given = self.given_rel_path(path)?; + let indexed = self.index_spelling(given.clone()); + if rev == "WT" { + if let Some(mode) = worktree_mode(self.root(), &indexed)? { + return Ok(Some(DiffEntry { mode, gitlink: None })); + } + let at_index = entry_at(&repo, &indexed, ":0")?.is_some_and(|(mode, _)| mode.is_commit()); + let at_head = + || entry_at(&repo, &given, "HEAD").map(|entry| entry.is_some_and(|(mode, _)| mode.is_commit())); + if !at_index && !at_head()? { + return Ok(None); + } + let gitlink = self + .initialized_submodule(Path::new(&indexed)) + .and_then(|path| Self::discover(&path).ok().flatten().filter(|child| child.root() == path)) + .and_then(|child| child.head().ok()?.1); + return Ok(Some(DiffEntry { mode: "160000".into(), gitlink })); + } + let entry = if !rev.starts_with(':') && indexed != given { + match entry_at(&repo, &given, rev)? { + Some(entry) => Some(entry), + None => entry_at(&repo, &indexed, rev)?, + } + } else { + entry_at(&repo, &indexed, rev)? + }; + Ok(entry.map(|(mode, id)| DiffEntry { + mode: format!("{:o}", mode.value()), + gitlink: mode.is_commit().then(|| id.to_string()), + })) + } + /// `path` relative to the worktree, spelled as given. pub(crate) fn given_rel_path(&self, path: &Path) -> IdeResult { let rel = if path.is_absolute() { @@ -283,6 +330,14 @@ pub(crate) fn worktree_mode(root: &Path, rel: &str) -> IdeResult> /// The entry's mode of `rel` at `rev` as git prints it (`100644`, `100755`, `120000`, /// `160000`…), `None` when the path is absent there. Same `rev` rules as [`blob_at`]. pub(crate) fn mode_at(repo: &gix::Repository, rel: &str, rev: &str) -> IdeResult> { + Ok(entry_at(repo, rel, rev)?.map(|(mode, _)| format!("{:o}", mode.value()))) +} + +fn entry_at( + repo: &gix::Repository, + rel: &str, + rev: &str, +) -> IdeResult> { if let Some(stage) = rev.strip_prefix(':') { let stage = match stage { "" | "0" => gix::index::entry::Stage::Unconflicted, @@ -295,16 +350,16 @@ pub(crate) fn mode_at(repo: &gix::Repository, rel: &str, rev: &str) -> IdeResult let Some(entry) = index.entry_by_path_and_stage(BStr::new(rel.as_bytes()), stage) else { return Ok(None); }; - return Ok(entry.mode.to_tree_entry_mode().map(|m| format!("{:o}", m.value()))); + return Ok(entry.mode.to_tree_entry_mode().map(|mode| (mode, entry.id))); } let Some(tree) = tree_of(repo, rev)? else { return Ok(None) }; let Some(entry) = tree.lookup_entry_by_path(Path::new(rel)).map_err(gx)? else { return Ok(None); }; - if !entry.mode().is_blob_or_symlink() { + if !entry.mode().is_blob_or_symlink() && !entry.mode().is_commit() { return Ok(None); } - Ok(Some(format!("{:o}", entry.mode().value()))) + Ok(Some((entry.mode(), entry.oid().to_owned()))) } /// Blob content of `rel` at `rev`. `rev` is a revision (`HEAD`, a branch, an id) or @@ -343,7 +398,7 @@ pub(crate) fn blob_at(repo: &gix::Repository, rel: &str, rev: &str) -> IdeResult /// A blob's bytes. Partial clones (`--filter=blob:none`) lack blobs until git /// fetches them on demand, which gix doesn't do, so a missing one is read /// through the git CLI. -fn blob_data(repo: &gix::Repository, id: gix::ObjectId) -> IdeResult> { +pub(crate) fn blob_data(repo: &gix::Repository, id: gix::ObjectId) -> IdeResult> { match repo.find_object(id) { Ok(obj) => Ok(obj.detach().data), Err(e) => { diff --git a/crates/ide-vcs/src/roots.rs b/crates/ide-vcs/src/roots.rs index 51af6a4b9..86728b8aa 100644 --- a/crates/ide-vcs/src/roots.rs +++ b/crates/ide-vcs/src/roots.rs @@ -2,7 +2,10 @@ //! root plus those nested below it (separate clones side by side, submodules). use crate::{Backend, FileStatus, Repo}; -use ide_core::IdeResult; +use ide_core::{IdeError, IdeResult, IpcPath}; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -19,6 +22,14 @@ pub struct Repos { primary: Option, } +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ProjectUpdateTarget { + pub root: IpcPath, + pub parent: Option, + pub detached_submodule: bool, +} + impl Repos { /// Discovers repositories in independent project folders of a workspace. pub fn discover_roots(roots: &[PathBuf], skip: &dyn Fn(&Path) -> bool) -> IdeResult { @@ -68,6 +79,26 @@ impl Repos { } } } + // Declared submodules remain Git roots under ignored folders or beyond the + // filesystem scan's depth. An uninitialized submodule has no Git worktree. + let mut next = 0; + while next < repos.len() { + let parent = &repos[next]; + let children = parent.initialized_submodules().unwrap_or_else(|error| { + tracing::debug!(root = %parent.root().display(), %error, "cannot list Git submodules"); + Vec::new() + }); + for path in children { + if path.starts_with(project_root) + && !repos.iter().any(|r| r.root() == path) + && let Ok(Some(repo)) = Repo::discover(&path) + && repo.root() == path + { + repos.push(repo); + } + } + next += 1; + } Ok(Self::new(repos, project_root)) } @@ -120,6 +151,53 @@ impl Repos { &self.repos } + /// Selects the roots that Update Project operates on. Detached children are + /// included with their selected superproject and read its updated pointer. + pub fn project_update_plan(&self, roots: &[Option]) -> IdeResult> { + let selected: BTreeSet<&Path> = if roots.is_empty() { + self.repos.iter().map(|repo| repo.root()).collect() + } else { + roots + .iter() + .map(|root| { + match root { + Some(root) => self.at_root(root), + None => self.primary(), + } + .map(|repo| repo.root()) + .ok_or_else(|| IdeError::unavailable("The selected repository is no longer part of the project")) + }) + .collect::>()? + }; + let mut parents = BTreeMap::new(); + for parent in &self.repos { + for path in parent.initialized_submodules().unwrap_or_default() { + parents.insert(path, parent.root()); + } + } + let mut included = BTreeSet::new(); + let mut targets = Vec::new(); + for repo in &self.repos { + let root = repo.root(); + let parent = parents.get(root).copied(); + let is_selected = selected.contains(root); + if !is_selected && !parent.is_some_and(|p| included.contains(p)) { + continue; + } + let (branch, head) = repo.head()?; + let detached_submodule = branch.is_none() && head.is_some() && parent.is_some(); + if is_selected || detached_submodule { + included.insert(root); + targets.push(ProjectUpdateTarget { + root: root.into(), + parent: parent.map(Into::into), + detached_submodule, + }); + } + } + Ok(targets) + } + /// The repository of the project root, else the first one. pub fn primary(&self) -> Option<&Arc> { self.primary.map(|i| &self.repos[i]) @@ -169,22 +247,32 @@ impl Repos { /// The reads go through [`Backend`], the Changes-view surface — repositories of a /// future second backend slot in here once `Repos` learns to hold them. pub fn status(&self) -> IdeResult> { - let groups: Vec<(Arc, Vec)> = self.repos.iter().map(|repo| (repo.clone(), Vec::new())).collect(); - self.read_status(groups, false) + self.read_status(self.all_status_groups(), |repo, _| (repo as &dyn Backend).status()) + } + + /// Ignored entries for the staging tree. Commit and status consumers read the regular status. + pub fn ignored_files(&self) -> IdeResult> { + self.read_status(self.all_status_groups(), |repo, _| repo.ignored_files()) + } + + fn all_status_groups(&self) -> Vec<(Arc, Vec)> { + self.repos.iter().map(|repo| (repo.clone(), Vec::new())).collect() } /// [`status`](Self::status) for `paths` only: each path goes to its innermost repository, /// so a repository without one is not read at all and a nested repository keeps its own /// files (the enclosing one's "untracked folder" entry for them is dropped). pub fn status_paths(&self, paths: &[PathBuf]) -> IdeResult> { - self.read_status(self.group(paths), true) + self.read_status(self.group(paths), |repo, mine| (repo as &dyn Backend).status_paths(mine)) } - /// Reads one status per repository: the whole working tree, or `scoped` the paths it was - /// given. A nested repository reports its own files, so the enclosing one's "untracked - /// folder" entry for it is dropped. A repository that cannot be read is left out; fails - /// only when all fail. - fn read_status(&self, groups: Vec<(Arc, Vec)>, scoped: bool) -> IdeResult> { + /// A nested repository reports its own files. When a repository cannot be read, + /// the operation can still display the other repositories' results. + fn read_status( + &self, + groups: Vec<(Arc, Vec)>, + status: impl Fn(&Repo, &[PathBuf]) -> IdeResult>, + ) -> IdeResult> { let mut out = Vec::new(); let mut first_error = None; let mut read = 0; @@ -195,8 +283,7 @@ impl Repos { .map(|r| r.root()) .filter(|r| *r != repo.root() && r.starts_with(repo.root())) .collect(); - let backend = repo.as_ref() as &dyn Backend; - let status = match if scoped { backend.status_paths(&mine) } else { backend.status() } { + let status = match status(&repo, &mine) { Ok(status) => { read += 1; status @@ -210,10 +297,11 @@ impl Repos { // A file belongs to its innermost repository: the nested one reports what lies // inside it, including files the enclosing one still tracks there (#4990). out.extend(status.into_iter().filter(|f| { - let untracked_root = - f.unstaged == Some(crate::ChangeKind::Untracked) && nested.iter().any(|n| f.path.0 == *n); + let skipped_root = + matches!(f.unstaged, Some(crate::ChangeKind::Untracked | crate::ChangeKind::Ignored)) + && nested.iter().any(|n| f.path.0 == *n); let in_nested = nested.iter().any(|n| f.path.0 != *n && f.path.0.starts_with(n)); - !untracked_root && !in_nested + !skipped_root && !in_nested })); } match first_error { @@ -248,6 +336,49 @@ mod tests { assert!(ok, "git init in {}", dir.display()); } + #[test] + fn ignored_files_use_git_rules_without_listing_other_repositories_twice() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + let nested = root.join("nested"); + git_init(&root); + git_init(&nested); + std::fs::write(root.join(".gitignore"), "*.tmp\n!visible.tmp\ncache/\nnested/\n").unwrap(); + std::fs::write(root.join(".git/info/exclude"), "/private.txt\n").unwrap(); + std::fs::write(nested.join(".gitignore"), "/nested-private.txt\n").unwrap(); + std::fs::create_dir(root.join("cache")).unwrap(); + std::fs::create_dir(root.join("plain-folder")).unwrap(); + for path in [ + "space name.tmp", + "visible.tmp", + "tracked.tmp", + "cache/child.txt", + "plain-folder/child.tmp", + "private.txt", + "nested/nested-private.txt", + ] { + std::fs::write(root.join(path), "fixture\n").unwrap(); + } + assert!( + Command::new("git").args(["add", "-f", "--", "tracked.tmp"]).current_dir(&root).status().unwrap().success() + ); + let repos = Repos::discover(&root, &|_| false).unwrap(); + let files = repos.ignored_files().unwrap(); + assert!(files.iter().all(|file| file.unstaged == Some(crate::ChangeKind::Ignored) && file.staged.is_none())); + let listed: BTreeSet<_> = files.iter().map(|file| (file.path.0.clone(), file.rel_path.as_str())).collect(); + assert_eq!( + listed, + BTreeSet::from([ + (root.join("cache"), "cache/"), + (root.join("plain-folder/child.tmp"), "plain-folder/child.tmp"), + (root.join("private.txt"), "private.txt"), + (root.join("space name.tmp"), "space name.tmp"), + (nested.join("nested-private.txt"), "nested-private.txt"), + ]) + ); + assert!(repos.status().unwrap().iter().all(|file| file.unstaged != Some(crate::ChangeKind::Ignored))); + } + #[test] fn directory_mappings_exclude_and_add_repositories() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-vcs/src/shelf.rs b/crates/ide-vcs/src/shelf.rs index d92d2bfc5..c1cd08f1f 100644 --- a/crates/ide-vcs/src/shelf.rs +++ b/crates/ide-vcs/src/shelf.rs @@ -2,14 +2,117 @@ //! `.idea/shelf`. Each shelved change list is `//shelved.patch` plus //! `//shelf.json` with its name, date and files. -use crate::cli::{run_env, run_paths}; -use crate::{ApplyOutcome, ChangeKind, Repo, ShelvedChangeList}; +use crate::cli::{run, run_env, run_paths}; +use crate::{ApplyOutcome, ChangeKind, ChangedFile, Repo, ShelvedChangeList, Stash}; use ide_core::{IdeError, IdeResult}; use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::io::Write; use std::path::{Path, PathBuf}; const PATCH: &str = "shelved.patch"; const INFO: &str = "shelf.json"; +const GROUPED: &str = "repositories"; +const SNAPSHOT: &str = "snapshot"; +const SNAPSHOT_PACK: &str = "snapshot.pack"; + +/// Correlates a single project-wide Git operation across its individual repository commands. +#[derive(Clone)] +pub struct ShelfBatch { + id: String, + base: PathBuf, +} + +thread_local! { + static SHELF_BATCH: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +impl ShelfBatch { + pub fn new(id: String, base: PathBuf) -> Self { + Self { id, base } + } + + pub fn run(self, op: impl FnOnce() -> T) -> T { + struct RestoreBatch(Option); + impl Drop for RestoreBatch { + fn drop(&mut self) { + SHELF_BATCH.with(|slot| slot.replace(self.0.take())); + } + } + let _restore = RestoreBatch(SHELF_BATCH.with(|slot| slot.replace(Some(self)))); + op() + } +} + +pub(crate) fn is_active_batch(id: &str) -> bool { + SHELF_BATCH.with(|slot| slot.borrow().as_ref().is_some_and(|batch| batch.id == id)) +} + +#[derive(Clone)] +pub(crate) struct AutomaticShelf { + pub directory: PathBuf, + pub changelist_root: Option, +} + +#[derive(Serialize, Deserialize)] +pub(crate) struct SavedShelves { + pub directory: PathBuf, + pub entries: Vec, + pub snapshot: String, + archive: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub batch: Option, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub prefix: String, +} + +pub(crate) struct PendingShelf { + pub id: String, + pub patch: String, + pub intact: bool, +} + +impl SavedShelves { + fn archive_path(&self) -> IdeResult { + if !self.archive.starts_with(".snapshot-") || self.archive.contains(['/', '\\']) { + return Err(IdeError::invalid("Invalid automatic Shelf archive")); + } + Ok(self.directory.join(&self.archive)) + } + + pub(crate) fn unpack(&self, r: &Repo) -> IdeResult<()> { + let pack = std::fs::read(self.archive_path()?)?; + run(r.root(), &["unpack-objects", "-q"], Some(&pack))?; + Ok(()) + } + + pub(crate) fn pending(&self) -> IdeResult> { + let mut pending = Vec::new(); + for id in &self.entries { + if let Some((patch, intact)) = owned_patch(&self.directory, id, &self.archive)? { + pending.push(PendingShelf { id: id.clone(), patch, intact }); + } + } + Ok(pending) + } + + fn clean_entries(&self) { + for id in &self.entries { + let _ = delete(&self.directory, id); + } + } + + pub(crate) fn discard(&self) { + self.clean_entries(); + self.remove_archive(); + } + + pub(crate) fn remove_archive(&self) { + if let Ok(path) = self.archive_path() { + let _ = std::fs::remove_file(path); + } + } +} #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -21,6 +124,184 @@ struct Info { files: Vec, #[serde(default)] repo: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + repositories: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + group: Option, +} + +#[derive(Serialize, Deserialize)] +struct ShelfRepository { + root: ide_core::IpcPath, + prefix: String, + paths: Vec, +} + +/// A captured part of a mixed-repository shelf, ready to save before any files are reverted. +pub struct ShelfCapture { + repo: PathBuf, + prefix: String, + patch: String, + files: Vec, +} + +impl ShelfCapture { + pub fn capture(r: &Repo, base: &Path, paths: &[PathBuf]) -> IdeResult { + let _scope = r.execution_scope(); + let repo = r.root().to_path_buf(); + let prefix = repository_prefix(&repo, base)?; + let (patch, files) = + crate::patch::working_patch_with_prefix(r, &r.rel_paths(paths)?, false, false, Some(&prefix))?; + Ok(Self { repo, prefix, patch, files }) + } + + pub fn repository(&self) -> &Path { + &self.repo + } + + pub fn revert(&self, r: &Repo) -> IdeResult<()> { + let _scope = r.execution_scope(); + if r.root() != self.repo { + return Err(IdeError::invalid("The shelf repository has changed")); + } + if self.files.is_empty() { + return Ok(()); + } + let paths: Vec<_> = self.files.iter().map(|file| file.path.clone()).collect(); + let (current, _) = crate::patch::working_patch_with_prefix(r, &paths, false, false, Some(&self.prefix))?; + if current != self.patch { + return Err(IdeError::invalid("Files changed while shelving. The captured changes are on the Shelf.")); + } + revert_files(r, &self.files) + } +} + +fn repository_prefix(repo: &Path, base: &Path) -> IdeResult { + let relative = + repo.strip_prefix(base).map_err(|_| IdeError::invalid("The shelf repositories have no common directory"))?; + Ok(if relative.as_os_str().is_empty() { + String::new() + } else { + format!("{}/", ide_core::ipc_path::to_ipc(relative)) + }) +} + +pub fn save_combined(shelf: &Path, base: &Path, name: &str, captures: &[ShelfCapture]) -> IdeResult { + let name = name.trim(); + if name.is_empty() { + return Err(IdeError::invalid("name must not be empty")); + } + let patch: String = captures.iter().map(|capture| capture.patch.as_str()).collect(); + let files = changed_files(&patch); + if files.is_empty() { + return Err(IdeError::invalid("no changes to shelve")); + } + if files.iter().map(|file| &file.path).collect::>().len() != files.len() { + return Err(IdeError::invalid("A file belongs to more than one repository in this shelf")); + } + crate::changelists::ensure_ignored(shelf, &["*"])?; + let repositories = captures + .iter() + .filter(|capture| !capture.files.is_empty()) + .map(|capture| ShelfRepository { + root: capture.repo.as_path().into(), + prefix: capture.prefix.clone(), + paths: capture.files.iter().map(|file| format!("{}{}", capture.prefix, file.path)).collect(), + }) + .collect(); + let info = Info { + name: name.to_owned(), + time_ms: now_ms(), + branch: None, + repo: Some(base.into()), + files, + repositories, + group: None, + }; + write_entry(shelf, info, &patch, None) +} + +/// A patch selection with its original repository and the common path prefix to strip when applying it. +pub struct ShelfSelection { + pub repo: Option, + prefix: String, + patch: String, +} + +impl ShelfSelection { + pub fn apply(&self, r: &Repo) -> IdeResult { + let _scope = r.execution_scope(); + let mut outcome = crate::patch::apply_with_prefix(r, &self.patch, &self.prefix)?; + for path in outcome.applied.iter_mut().chain(outcome.conflicts.iter_mut()) { + *path = format!("{}{path}", self.prefix); + } + Ok(outcome) + } + + pub fn diff_files(&self, r: &Repo) -> IdeResult> { + diff_from_patch(r, &self.patch, &self.prefix) + } + + pub fn export(&self, fallback_root: &Path, base: &Path) -> IdeResult { + let root = self.repo.as_deref().unwrap_or(fallback_root); + crate::patch::rebase_patch(&self.patch, root, &self.prefix, base) + } +} + +pub fn selections(shelf: &Path, id: &str, path: Option<&str>) -> IdeResult> { + let mut selections = Vec::new(); + for member in members(shelf, id)? { + let dir = entry_dir(shelf, &member)?; + let patch = std::fs::read_to_string(dir.join(PATCH))?; + let patch = match path { + Some(path) => sections_for_path(&patch, path), + None => patch, + }; + if !patch.is_empty() { + selections.extend(selections_in_entry(&dir, patch)?); + } + } + if selections.is_empty() { + return Err(IdeError::not_found("shelved file not found")); + } + Ok(selections) +} + +fn selections_in_entry(dir: &Path, patch: String) -> IdeResult> { + let info = read_info(dir); + let Some(info) = info else { + if dir.join(GROUPED).is_file() { + return Err(IdeError::invalid("shelf metadata is missing")); + } + return Ok(vec![ShelfSelection { repo: None, prefix: String::new(), patch }]); + }; + if info.repositories.is_empty() { + if dir.join(GROUPED).is_file() { + return Err(IdeError::invalid("shelf metadata is missing")); + } + return Ok(vec![ShelfSelection { repo: info.repo, prefix: String::new(), patch }]); + } + let mut owners = HashMap::new(); + for (index, repository) in info.repositories.iter().enumerate() { + for path in &repository.paths { + if owners.insert(path, index).is_some() { + return Err(IdeError::invalid("A file belongs to more than one repository in this shelf")); + } + } + } + let mut patches = BTreeMap::::new(); + for (section, file) in crate::patch::sections(&patch) { + let index = + owners.get(&file.path).ok_or_else(|| IdeError::invalid("The shelved file has no owning repository"))?; + patches.entry(*index).or_default().push_str(section); + } + Ok(patches + .into_iter() + .map(|(index, patch)| { + let repository = &info.repositories[index]; + ShelfSelection { repo: Some(repository.root.clone()), prefix: repository.prefix.clone(), patch } + }) + .collect()) } fn now_ms() -> f64 { @@ -51,13 +332,42 @@ fn entry_dir(shelf: &Path, id: &str) -> IdeResult { Ok(dir) } +fn members(shelf: &Path, id: &str) -> IdeResult> { + if !id.starts_with("batch-") { + entry_dir(shelf, id)?; + return Ok(vec![id.to_owned()]); + } + let mut ids = Vec::new(); + if let Ok(entries) = std::fs::read_dir(shelf) { + for entry in entries.flatten() { + let dir = entry.path(); + if dir.join(PATCH).is_file() && read_info(&dir).is_some_and(|info| info.group.as_deref() == Some(id)) { + ids.push(entry.file_name().to_string_lossy().into_owned()); + } + } + } + if ids.is_empty() { + return Err(IdeError::not_found(format!("shelved changes '{id}' not found"))); + } + ids.sort(); + Ok(ids) +} + fn read_info(dir: &Path) -> Option { serde_json::from_slice(&std::fs::read(dir.join(INFO)).ok()?).ok() } +fn changed_files(patch: &str) -> Vec { + crate::patch::parse_patch(patch) + .into_iter() + .map(|file| ChangedFile { path: file.path, kind: file.kind, old_path: file.old_path, link: None }) + .collect() +} + /// Shelved change lists, newest first. pub fn list(shelf: &Path) -> IdeResult> { let mut out = Vec::new(); + let mut groups = HashMap::::new(); let Ok(entries) = std::fs::read_dir(shelf) else { return Ok(out) }; for e in entries.flatten() { let dir = e.path(); @@ -70,6 +380,8 @@ pub fn list(shelf: &Path) -> IdeResult> { time_ms: 0.0, branch: None, repo: None, + repositories: Vec::new(), + group: None, files: std::fs::read_to_string(dir.join(PATCH)) .map(|p| { crate::patch::parse_patch(&p) @@ -79,8 +391,8 @@ pub fn list(shelf: &Path) -> IdeResult> { }) .unwrap_or_default(), }); - out.push(ShelvedChangeList { - id, + let entry = ShelvedChangeList { + id: info.group.clone().unwrap_or(id), name: info.name, time_ms: info.time_ms, branch: info.branch, @@ -89,24 +401,43 @@ pub fn list(shelf: &Path) -> IdeResult> { .into_iter() .map(|f| crate::ChangedFile { path: f.path, kind: f.kind, old_path: f.old_path, link: None }) .collect(), - }); + }; + if let Some(group) = info.group { + if let Some(existing) = groups.get_mut(&group) { + existing.files.extend(entry.files); + existing.time_ms = existing.time_ms.max(entry.time_ms); + existing.branch = None; + } else { + groups.insert(group, entry); + } + } else { + out.push(entry); + } } + out.extend(groups.into_values()); out.sort_by(|a, b| b.time_ms.total_cmp(&a.time_ms).then_with(|| a.name.cmp(&b.name))); Ok(out) } /// The patch text of a shelved change list. pub fn patch_of(shelf: &Path, id: &str) -> IdeResult { - Ok(std::fs::read_to_string(entry_dir(shelf, id)?.join(PATCH))?) + let patches = members(shelf, id)? + .into_iter() + .map(|id| Ok(std::fs::read_to_string(entry_dir(shelf, &id)?.join(PATCH))?)) + .collect::>>()?; + Ok(patches.concat()) } /// The repository captured when the shelf was made; legacy shelves used the primary repository. pub fn repository(shelf: &Path, id: &str) -> IdeResult> { - Ok(read_info(&entry_dir(shelf, id)?).and_then(|info| info.repo).map(|repo| repo.into_path_buf())) + let members = members(shelf, id)?; + Ok(read_info(&entry_dir(shelf, &members[0])?).and_then(|info| info.repo).map(|repo| repo.into_path_buf())) } pub fn delete(shelf: &Path, id: &str) -> IdeResult<()> { - std::fs::remove_dir_all(entry_dir(shelf, id)?)?; + for member in members(shelf, id)? { + std::fs::remove_dir_all(entry_dir(shelf, &member)?)?; + } Ok(()) } @@ -115,12 +446,20 @@ pub fn rename(shelf: &Path, id: &str, name: &str) -> IdeResult<()> { if name.is_empty() { return Err(IdeError::invalid("name must not be empty")); } - let dir = entry_dir(shelf, id)?; - let mut info = read_info(&dir).unwrap_or(Info { + for member in members(shelf, id)? { + rename_entry(&entry_dir(shelf, &member)?, name)?; + } + Ok(()) +} + +fn rename_entry(dir: &Path, name: &str) -> IdeResult<()> { + let mut info = read_info(dir).unwrap_or(Info { name: String::new(), time_ms: now_ms(), branch: None, repo: None, + repositories: Vec::new(), + group: None, files: vec![], }); info.name = name.to_string(); @@ -138,37 +477,220 @@ pub(crate) fn shelve(r: &Repo, shelf: &Path, name: &str, rel_paths: &[String]) - if files.is_empty() || patch.trim().is_empty() { return Err(IdeError::invalid("no changes to shelve")); } - std::fs::create_dir_all(shelf)?; - let base = slug(name); - let mut id = base.clone(); - let mut n = 1; - while shelf.join(&id).exists() { - n += 1; - id = format!("{base}_{n}"); + let entry = save_patch(r, shelf, name, &patch, files, None)?; + revert_files(r, &entry.files)?; + Ok(entry) +} + +/// Creates one visible entry per affected change list and one native archive for restoration. +pub(crate) fn capture_stash(r: &Repo, options: AutomaticShelf, name: &str, stash: &Stash) -> IdeResult { + let base = stash.base.as_deref().ok_or_else(|| IdeError::invalid("The saved local changes have no base commit"))?; + let batch = SHELF_BATCH.with(|slot| slot.borrow().clone()); + let prefix = batch.as_ref().map(|batch| repository_prefix(r.root(), &batch.base)).transpose()?.unwrap_or_default(); + let working = crate::patch::shelf_tree_patch_with_prefix(r, base, &stash.id, &prefix)?; + let staged = crate::patch::shelf_tree_patch_with_prefix(r, base, &format!("{}^2", stash.id), &prefix)?; + let groups = shelf_groups(r, base, stash, options.changelist_root.as_deref(), &working, &staged, &prefix)?; + if groups.is_empty() { + return Err(IdeError::invalid("Could not identify the stash containing the saved local changes")); } - let dir = shelf.join(&id); - std::fs::create_dir_all(&dir)?; + let branch = r.branch_info()?.head; + crate::changelists::ensure_ignored(&options.directory, &["*"])?; + let revisions = format!("{}\n^{base}\n", stash.id); + let pack = run(r.root(), &["pack-objects", "--stdout", "--revs"], Some(revisions.as_bytes()))?.stdout; + let mut archive = tempfile::Builder::new().prefix(".snapshot-").tempfile_in(&options.directory)?; + archive.write_all(&pack)?; + let filename = archive.path().file_name().unwrap().to_string_lossy().into_owned(); + let mut saved = SavedShelves { + directory: options.directory, + entries: Vec::new(), + snapshot: stash.id.clone(), + archive: filename, + prefix, + batch: batch.as_ref().map(|batch| batch.id.clone()), + }; + for ((list, label), (patch, files)) in groups { + let label = if list.is_empty() { name.to_owned() } else { format!("[{label}] {name}") }; + let mut info = Info { + name: label, + time_ms: now_ms(), + branch: branch.clone(), + repo: Some(r.root().into()), + files, + repositories: Vec::new(), + group: None, + }; + if let Some(batch) = &batch { + let key = format!("{}\0{}\0{name}\0{list}", batch.id, ide_core::ipc_path::to_ipc(&batch.base)); + info.group = Some(format!("batch-{}", blake3::hash(key.as_bytes()))); + info.repo = Some(batch.base.as_path().into()); + info.repositories.push(ShelfRepository { + root: r.root().into(), + prefix: saved.prefix.clone(), + paths: info.files.iter().map(|file| file.path.clone()).collect(), + }); + } + match write_entry(&saved.directory, info, &patch, Some(&saved.archive)) { + Ok(entry) => saved.entries.push(entry.id), + Err(error) => { + saved.clean_entries(); + return Err(error); + } + } + } + if let Err(error) = archive.keep() { + saved.clean_entries(); + return Err(error.error.into()); + } + Ok(saved) +} + +type ShelfPatch = (String, Vec); +type ShelfGroups = BTreeMap<(String, String), ShelfPatch>; + +fn shelf_groups( + r: &Repo, + base: &str, + stash: &Stash, + root: Option<&Path>, + working: &str, + staged: &str, + prefix: &str, +) -> IdeResult { + let mut groups = ShelfGroups::new(); + let state = root.map(|path| crate::changelists::load(&ide_core::project_dir::path(path, "changelists.json"))); + let mut renamed = HashMap::new(); + if root.is_some() { + for tree in [format!("{}^2", stash.id), stash.id.clone()] { + let status = run(r.root(), &["diff", "--name-status", "-z", "--find-renames", base, &tree, "--"], None)?; + for file in crate::ops::parse_name_status(&status.stdout_str()) { + if file.kind == ChangeKind::Renamed + && let Some(old) = file.old_path + { + renamed.insert(old, file.path); + } + } + } + } + let working = crate::patch::sections(working); + let visible: HashSet<_> = working.iter().map(|(_, file)| file.path.clone()).collect(); + // Index-only edits also belong to the shelf preview. + for (section, file) in working + .into_iter() + .chain(crate::patch::sections(staged).into_iter().filter(|(_, f)| !visible.contains(&f.path))) + { + let group = match (root, state.as_ref()) { + (Some(root), Some(state)) => { + let rel = file.path.strip_prefix(prefix).unwrap_or(&file.path); + let path = r.abs_path(renamed.get(rel).map_or(rel, String::as_str)); + let key = ide_core::ipc_path::to_ipc(path.strip_prefix(root).unwrap_or(&path)); + let id = state.files.get(&key).unwrap_or(&state.active); + let list = state.lists.iter().find(|list| &list.id == id).unwrap_or(&state.lists[0]); + (list.id.clone(), list.name.clone()) + } + _ => (String::new(), String::new()), + }; + let (patch, files) = groups.entry(group).or_default(); + patch.push_str(section); + files.push(ChangedFile { path: file.path, kind: file.kind, old_path: file.old_path, link: None }); + } + Ok(groups) +} + +fn save_patch( + r: &Repo, + shelf: &Path, + name: &str, + patch: &str, + files: Vec, + snapshot: Option<&str>, +) -> IdeResult { let info = Info { name: name.to_string(), time_ms: now_ms(), branch: r.branch_info()?.head, - files: files.clone(), + files, repo: Some(r.root().to_path_buf().into()), + repositories: Vec::new(), + group: None, + }; + write_entry(shelf, info, patch, snapshot) +} + +fn write_entry(shelf: &Path, info: Info, patch: &str, snapshot: Option<&str>) -> IdeResult { + std::fs::create_dir_all(shelf)?; + let base = slug(&info.name); + let mut id = base.clone(); + let mut n = 0; + let dir = loop { + let dir = shelf.join(&id); + match std::fs::create_dir(&dir) { + Ok(()) => break dir, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(error) => return Err(error.into()), + } + n += 1; + id = format!("{base}_{n}"); }; let write = || -> IdeResult<()> { - std::fs::write(dir.join(PATCH), patch.as_bytes())?; std::fs::write( dir.join(INFO), serde_json::to_vec_pretty(&info).map_err(|e| IdeError::internal(e.to_string()))?, )?; + if !info.repositories.is_empty() { + std::fs::write(dir.join(GROUPED), "")?; + } + if let Some(snapshot) = snapshot { + let digest = blake3::hash(patch.as_bytes()); + std::fs::write(dir.join(SNAPSHOT), format!("{snapshot}\n{digest}"))?; + } + let mut file = tempfile::NamedTempFile::new_in(&dir)?; + file.write_all(patch.as_bytes())?; + file.persist(dir.join(PATCH)).map_err(|error| error.error)?; Ok(()) }; if let Err(e) = write() { let _ = std::fs::remove_dir_all(&dir); return Err(e); } - revert_files(r, &files)?; - Ok(ShelvedChangeList { id, name: info.name, time_ms: info.time_ms, branch: info.branch, repo: info.repo, files }) + Ok(ShelvedChangeList { + id, + name: info.name, + time_ms: info.time_ms, + branch: info.branch, + repo: info.repo, + files: info.files, + }) +} + +/// Whether the pending shelf still exists and whether its snapshot still matches all of its files. +pub(crate) fn pending_snapshot(shelf: &Path, id: &str, snapshot: &str) -> IdeResult> { + Ok(owned_patch(shelf, id, snapshot)?.map(|(_, intact)| intact)) +} + +fn owned_patch(shelf: &Path, id: &str, snapshot: &str) -> IdeResult> { + let dir = shelf.join(id); + if !dir.join(PATCH).is_file() { + return Ok(None); + } + let dir = entry_dir(shelf, id)?; + let saved = match std::fs::read_to_string(dir.join(SNAPSHOT)) { + Ok(saved) => saved, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error.into()), + }; + let Some((id, digest)) = saved.split_once('\n') else { return Ok(None) }; + if id != snapshot { + return Ok(None); + } + let patch = std::fs::read_to_string(dir.join(PATCH))?; + let intact = blake3::hash(patch.as_bytes()).to_hex().as_str() == digest; + Ok(Some((patch, intact))) +} + +pub(crate) fn materialize_snapshot(r: &Repo, shelf: &Path, id: &str) -> IdeResult<()> { + let pack = std::fs::read(entry_dir(shelf, id)?.join(SNAPSHOT_PACK))?; + run(r.root(), &["unpack-objects", "-q"], Some(&pack))?; + Ok(()) } /// Restores `files` to HEAD in both index and working tree; files absent from HEAD are removed. @@ -218,84 +740,72 @@ pub struct ShelfDiffFile { pub after: Option, } -fn sections(patch: &str) -> Vec<(&str, crate::PatchFile)> { - let mut starts: Vec<_> = patch - .match_indices("diff --git ") - .filter(|(i, _)| *i == 0 || patch.as_bytes()[i - 1] == b'\n') - .map(|(i, _)| i) - .collect(); - if starts.is_empty() { - let (mut old, mut new) = (0u32, 0u32); - let mut offset = 0; - let mut lines = patch.split_inclusive('\n').peekable(); - while let Some(line) = lines.next() { - if old > 0 || new > 0 { - match line.as_bytes().first() { - Some(b'-') => old = old.saturating_sub(1), - Some(b'+') => new = new.saturating_sub(1), - Some(b' ') => { - old = old.saturating_sub(1); - new = new.saturating_sub(1); - } - _ => {} - } - } else if line.starts_with("--- ") && lines.peek().is_some_and(|l| l.starts_with("+++ ")) { - starts.push(offset); - } - if let Some(range) = line.strip_prefix("@@ ") { - let mut parts = range.split_whitespace(); - let count = |s: &str| s.split_once(',').map_or(1, |(_, n)| n.parse().unwrap_or(0)); - old = parts.next().map(count).unwrap_or(0); - new = parts.next().map(count).unwrap_or(0); - } - offset += line.len(); - } - } - starts - .iter() - .enumerate() - .filter_map(|(n, &start)| { - let section = &patch[start..starts.get(n + 1).copied().unwrap_or(patch.len())]; - crate::patch::parse_patch(section).into_iter().next().map(|file| (section, file)) - }) - .collect() -} - pub fn selected_patch(shelf: &Path, id: &str, path: Option<&str>) -> IdeResult { let patch = patch_of(shelf, id)?; let Some(path) = path else { return Ok(patch) }; - let selected: String = sections(&patch).into_iter().filter(|(_, f)| f.path == path).map(|(p, _)| p).collect(); + let selected = sections_for_path(&patch, path); if selected.is_empty() { return Err(IdeError::not_found("shelved file not found")); } Ok(selected) } +fn sections_for_path(patch: &str, path: &str) -> String { + crate::patch::sections(patch).into_iter().filter(|(_, f)| f.path == path).map(|(p, _)| p).collect() +} + pub fn delete_path(shelf: &Path, id: &str, path: Option<&str>) -> IdeResult<()> { let Some(path) = path else { return delete(shelf, id) }; selected_patch(shelf, id, Some(path))?; - let patch = patch_of(shelf, id)?; - let remaining: String = sections(&patch).into_iter().filter(|(_, f)| f.path != path).map(|(p, _)| p).collect(); + delete_paths(shelf, id, &[path.to_owned()]) +} + +pub fn delete_paths(shelf: &Path, id: &str, paths: &[String]) -> IdeResult<()> { + if paths.is_empty() { + return Ok(()); + } + let paths: HashSet<_> = paths.iter().collect(); + for member in members(shelf, id)? { + delete_paths_in_entry(shelf, &member, &paths)?; + } + Ok(()) +} + +fn delete_paths_in_entry(shelf: &Path, id: &str, paths: &HashSet<&String>) -> IdeResult<()> { + let dir = entry_dir(shelf, id)?; + let patch = std::fs::read_to_string(dir.join(PATCH))?; + let sections = crate::patch::sections(&patch); + if !sections.iter().any(|(_, file)| paths.contains(&file.path)) { + return Ok(()); + } + let remaining: String = sections.into_iter().filter(|(_, f)| !paths.contains(&f.path)).map(|(p, _)| p).collect(); if remaining.is_empty() { return delete(shelf, id); } - let dir = entry_dir(shelf, id)?; + if remaining == patch { + return Ok(()); + } let mut info = read_info(&dir).ok_or_else(|| IdeError::invalid("shelf metadata is missing"))?; - info.files = crate::patch::parse_patch(&remaining) - .into_iter() - .map(|f| crate::ChangedFile { path: f.path, kind: f.kind, old_path: f.old_path, link: None }) - .collect(); - std::fs::write(dir.join(PATCH), remaining)?; + info.files = changed_files(&remaining); + let mut file = tempfile::NamedTempFile::new_in(&dir)?; + file.write_all(remaining.as_bytes())?; + file.persist(dir.join(PATCH)).map_err(|error| error.error)?; std::fs::write(dir.join(INFO), serde_json::to_vec_pretty(&info).map_err(|e| IdeError::internal(e.to_string()))?)?; Ok(()) } /// Reconstruct each side in a throwaway index; neither HEAD nor the working files are used. pub fn diff_files(r: &Repo, shelf: &Path, id: &str) -> IdeResult> { + diff_from_patch(r, &patch_of(shelf, id)?, "") +} + +fn diff_from_patch(r: &Repo, patch: &str, prefix: &str) -> IdeResult> { let _scope = r.execution_scope(); - let patch = patch_of(shelf, id)?; + let strip = crate::patch::strip_option(prefix); + let mut apply = vec!["apply"]; + apply.extend(strip.as_deref()); let mut out = Vec::new(); - for (section, file) in sections(&patch) { + for (section, file) in crate::patch::sections(patch) { let mut item = ShelfDiffFile { path: file.path.clone(), patch: section.to_string(), before: None, after: None }; if !file.binary { let reconstruct = || -> IdeResult<(String, String)> { @@ -304,11 +814,14 @@ pub fn diff_files(r: &Repo, shelf: &Path, id: &str) -> IdeResult IdeResult { + let path = path + .strip_prefix(prefix) + .ok_or_else(|| IdeError::invalid("The patch contains a path outside its repository"))?; let bytes = run_env(r.root(), &["show", &format!(":{path}")], None, &env)?.stdout; if bytes.contains(&0) { return Err(IdeError::invalid("binary file")); @@ -322,7 +835,7 @@ pub fn diff_files(r: &Repo, shelf: &Path, id: &str) -> IdeResult IdeResult) -> IdeResult<()> { let files = crate::patch::parse_patch(patch); - if files.is_empty() || sections(patch).len() != files.len() { + if files.is_empty() || crate::patch::sections(patch).len() != files.len() { return Err(IdeError::invalid("no file changes found in the patch")); } std::fs::create_dir_all(shelf)?; @@ -357,6 +870,8 @@ pub fn import_patch(shelf: &Path, name: &str, patch: &str, repo: Option<&Path>) time_ms: now_ms(), branch: None, repo: repo.map(|r| r.to_path_buf().into()), + repositories: Vec::new(), + group: None, files: files .into_iter() .map(|f| crate::ChangedFile { path: f.path, kind: f.kind, old_path: f.old_path, link: None }) diff --git a/crates/ide-vcs/src/signing.rs b/crates/ide-vcs/src/signing.rs new file mode 100644 index 000000000..b2e7a0328 --- /dev/null +++ b/crates/ide-vcs/src/signing.rs @@ -0,0 +1,266 @@ +use crate::{Repo, cli, execution_allowed}; +use gix::lock::{self, acquire::Fail}; +use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind}; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::io; +use std::path::{Path, PathBuf}; +use std::process::Command; + +#[derive(Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct GitSigningConfig { + pub format: String, + pub enabled: bool, + pub key: Option, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct GpgSigningKey { + pub fingerprint: String, + pub user_id: Option, +} + +#[derive(Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct GitSigningEdit { + pub enabled: Option, + pub key: Option, +} + +impl Repo { + pub fn signing_config(&self) -> IdeResult { + Ok(GitSigningConfig { + format: self.config_get("gpg.format")?.unwrap_or_else(|| "openpgp".into()), + enabled: self.config_get_bool("commit.gpgsign")?.unwrap_or_default(), + key: self.config_get("user.signingkey")?.filter(|key| !key.is_empty()), + }) + } + + pub fn gpg_signing_keys(&self, cancel: &CancellationToken) -> IdeResult> { + let _scope = self.execution_scope(); + self.require_openpgp()?; + let program = gpg_program(self.root(), cancel)?; + let mut cmd = Command::new(&program); + cmd.current_dir(self.root()).args(["--batch", "--no-tty", "--with-colons", "--list-secret-keys"]); + ide_core::process::prepare(&mut cmd); + let out = cli::capture_command(cmd, None, cancel, 4 << 20, "GnuPG")?; + if out.code != Some(0) { + return Err(IdeError::unavailable(format!( + "Could not list OpenPGP signing keys ({}): {}", + program.display(), + String::from_utf8_lossy(&out.stderr).trim() + ))); + } + Ok(parse_keys(&out.stdout_str())) + } + + pub fn edit_signing(&self, edit: GitSigningEdit) -> IdeResult<()> { + let _scope = self.execution_scope(); + self.require_openpgp()?; + if edit.enabled.is_none() && edit.key.is_none() { + return Ok(()); + } + if edit.key.as_deref().is_some_and(|key| !valid_fingerprint(key)) { + return Err(IdeError::invalid("invalid OpenPGP fingerprint")); + } + let config = self.metadata_dirs()?[1].join("config"); + let mut lock = lock::File::acquire(&config, Fail::Immediately, None, 0, Some(&lock::acquire::resolve_symlink)) + .map_err(|error| IdeError::new(ErrorKind::Io, error.to_string()))?; + + // Let Git rewrite both values, holding its normal config lock until both edits succeed. + let mut original = std::fs::File::open(&config)?; + let mut staged = tempfile::NamedTempFile::new_in(config.parent().expect("repository config directory"))?; + io::copy(&mut original, &mut staged)?; + let enabled = edit.enabled.map(|enabled| if enabled { "true" } else { "false" }); + for (name, value) in [("commit.gpgsign", enabled), ("user.signingkey", edit.key.as_deref())] { + if let Some(value) = value { + cli::run( + self.root(), + &[ + "config", + "--file", + staged.path().to_str().ok_or_else(|| IdeError::invalid("non-UTF-8 Git config path"))?, + "--replace-all", + "--", + name, + value, + ], + None, + )?; + } + } + // Git's config writer replaces the staging file, so reopen its final path. + let mut updated = std::fs::File::open(staged.path())?; + lock.with_mut(|file| { + io::copy(&mut updated, file)?; + file.set_permissions(original.metadata()?.permissions()) + })?; + drop(original); + lock.commit().map_err(|error| IdeError::new(ErrorKind::Io, error.to_string()))?; + Ok(()) + } + + fn require_openpgp(&self) -> IdeResult<()> { + if !execution_allowed() { + return Err(IdeError::unavailable("Git signing configuration requires a trusted project")); + } + if self.config_get("gpg.format")?.is_some_and(|format| format != "openpgp") { + return Err(IdeError::invalid("the repository uses a signing format other than OpenPGP")); + } + Ok(()) + } +} + +fn gpg_program(root: &Path, cancel: &CancellationToken) -> IdeResult { + let args = ["config", "--null", "--get-regexp", r"^gpg\.(openpgp\.)?program$"]; + let out = cli::run_cancellable_raw(root, &args, cancel)?; + let program = match out.code { + Some(0) => { + let config = out.stdout_str(); + let (_, program) = config + .split_terminator('\0') + .next_back() + .and_then(|entry| entry.split_once('\n')) + .filter(|(_, program)| !program.is_empty()) + .ok_or_else(|| IdeError::invalid("invalid OpenPGP signing program"))?; + PathBuf::from(program) + } + Some(1) if out.stderr.is_empty() => PathBuf::from("gpg"), + _ => return Err(cli::failure(&args, &out.stderr, &out.stdout, out.code)), + }; + if cfg!(windows) + && (program.as_os_str().eq_ignore_ascii_case("gpg") || program.as_os_str().eq_ignore_ascii_case("gpg.exe")) + { + let exec_path = cli::run_cancellable(root, &["--exec-path"], cancel)?.stdout_str(); + let bundled = Path::new(exec_path.trim()).join("../../../usr/bin/gpg.exe"); + if let Ok(path) = dunce::canonicalize(bundled) { + return Ok(path); + } + } + Ok(if program.is_relative() && program.components().count() > 1 { root.join(program) } else { program }) +} + +fn valid_fingerprint(value: &str) -> bool { + matches!(value.len(), 40 | 64) && value.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn parse_keys(output: &str) -> Vec { + let mut keys = Vec::new(); + let mut pending = None; + let mut follows_primary = false; + for record in output.lines() { + let fields: Vec<_> = record.split(':').collect(); + match fields.first().copied() { + Some("sec") => { + if let Some(key) = pending.take() { + keys.push(key); + } + follows_primary = !matches!(fields.get(1), Some(&("r" | "e" | "i" | "d"))) + && fields.get(11).is_some_and(|caps| caps.contains('S') && !caps.contains('D')); + } + Some("fpr") if follows_primary => { + follows_primary = false; + if let Some(fingerprint) = fields.get(9).filter(|value| valid_fingerprint(value)) { + pending = Some(GpgSigningKey { fingerprint: fingerprint.to_string(), user_id: None }); + } + } + Some("uid") => { + if let Some(key) = pending.as_mut().filter(|key| key.user_id.is_none()) { + key.user_id = fields.get(9).map(|value| decode_user_id(value)); + } + } + _ => {} + } + } + keys.extend(pending); + keys +} + +fn decode_user_id(value: &str) -> String { + let mut bytes = Vec::new(); + let mut rest = value.as_bytes(); + while let Some((&byte, tail)) = rest.split_first() { + if let [b'\\', b'x', high, low, remaining @ ..] = rest + && let (Some(high), Some(low)) = (char::from(*high).to_digit(16), char::from(*low).to_digit(16)) + { + bytes.push((high * 16 + low) as u8); + rest = remaining; + } else { + bytes.push(byte); + rest = tail; + } + } + String::from_utf8_lossy(&bytes).into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ExecutionScope; + + const FINGERPRINT: &str = "1234567890123456789012345678901234567890"; + const SUBKEY: &str = "ABCDEFABCDEFABCDEFABCDEFABCDEFABCDEFABCD"; + + #[test] + fn lists_signing_primary_fingerprints_and_decodes_user_ids() { + let records = format!( + "sec:u:255:22:67890:1:::u:::cSC:::+::ed25519:::0:\n\ + fpr:::::::::{FINGERPRINT}:\n\ + uid:u::::1::AA::Signing\\x3a Test ::::::::::0:\n\ + ssb:u:255:22:FFFF:1::::::s:::+::ed25519::\n\ + fpr:::::::::{SUBKEY}:\n\ + sec:e:255:22:1111:1:::u:::sS:::+::ed25519:::0:\n\ + fpr:::::::::{SUBKEY}:\n\ + sec:u:255:22:2222:1:::u:::eE:::+::ed25519:::0:\n\ + fpr:::::::::{SUBKEY}:\n" + ); + assert_eq!( + parse_keys(&records), + vec![GpgSigningKey { + fingerprint: FINGERPRINT.into(), + user_id: Some("Signing: Test ".into()), + }] + ); + } + + #[test] + fn edits_local_signing_config_with_git_lock_and_preserves_other_settings() { + let dir = tempfile::tempdir().unwrap(); + let git = |args: &[&str]| { + let _scope = ExecutionScope::enter(true); + cli::run(dir.path(), args, None).unwrap().stdout_str() + }; + git(&["init"]); + git(&["config", "--local", "gpg.format", "openpgp"]); + git(&["config", "--local", "commit.gpgsign", "false"]); + git(&["config", "--local", "user.signingkey", "old-key"]); + git(&["config", "--local", "user.email", "test@example.com"]); + let repo = Repo::discover(dir.path()).unwrap().unwrap(); + + let enable = || GitSigningEdit { enabled: Some(true), key: Some(FINGERPRINT.into()) }; + assert!(repo.edit_signing(enable()).is_err()); + assert!(repo.gpg_signing_keys(&CancellationToken::default()).is_err()); + repo.set_execution_allowed(true); + let lock = dir.path().join(".git/config.lock"); + std::fs::write(&lock, b"another process owns this lock").unwrap(); + assert!(repo.edit_signing(enable()).is_err()); + assert_eq!(git(&["config", "--local", "--get", "user.signingkey"]).trim(), "old-key"); + std::fs::remove_file(lock).unwrap(); + + repo.edit_signing(enable()).unwrap(); + assert_eq!(git(&["config", "--local", "--get", "user.signingkey"]).trim(), FINGERPRINT); + assert_eq!(git(&["config", "--local", "--get", "user.email"]).trim(), "test@example.com"); + assert!(repo.signing_config().unwrap().enabled); + + repo.edit_signing(GitSigningEdit { enabled: Some(false), key: None }).unwrap(); + assert!(!repo.signing_config().unwrap().enabled); + assert_eq!(git(&["config", "--local", "--get", "user.signingkey"]).trim(), FINGERPRINT); + + git(&["config", "--local", "gpg.format", "ssh"]); + assert!(repo.edit_signing(enable()).is_err()); + assert_eq!(repo.signing_config().unwrap().format, "ssh"); + assert!(!repo.signing_config().unwrap().enabled); + } +} diff --git a/crates/ide-vcs/src/staged_text.rs b/crates/ide-vcs/src/staged_text.rs new file mode 100644 index 000000000..571a5ee97 --- /dev/null +++ b/crates/ide-vcs/src/staged_text.rs @@ -0,0 +1,253 @@ +use std::collections::HashSet; +use std::fs::{self, File}; +use std::path::Path; + +use gix::bstr::BStr; +use gix::index::entry::{Flags, Mode, Stage}; +use ide_core::error::ErrorKind; +use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath}; +use serde::{Deserialize, Serialize}; +use specta::Type; + +use crate::cli::TempIndex; +use crate::diff::{normalize_eol, replace_text}; +use crate::repo::{blob_data, gx}; +use crate::text_encoding::{TextEncoding, decode, encode, has_bom, is_binary}; +use crate::{ApplyCommitReview, HunkKind, Repo, write}; + +#[derive(Debug, Serialize, Deserialize, Type)] +pub struct StagedText { + pub text: String, + /// Identifies the index entry, including its mode, when this text was read. + pub version: String, +} + +#[derive(Debug, Serialize, Deserialize, Type)] +pub struct StagedTextEdit { + pub path: IpcPath, + pub version: String, + pub text: String, +} + +#[derive(Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct StagingLineHunk { + pub kind: HunkKind, + pub start: u32, + pub lines: u32, + pub head_start: u32, + pub head_lines: u32, + pub head_text: String, + pub index_start: u32, + pub index_lines: u32, + pub index_text: String, + pub staged: bool, + pub unstaged: bool, +} + +#[derive(Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct StagingLineHunks { + pub index_version: String, + pub hunks: Vec, +} + +struct StagedEntry { + mode: &'static str, + id: gix::ObjectId, +} + +impl StagedEntry { + fn version(&self) -> String { + format!("{}:{}", self.mode, self.id) + } +} + +fn staged_entry(repo: &gix::Repository, rel: &str) -> IdeResult> { + if !repo.index_path().is_file() { + return Ok(None); + } + let index = repo.open_index().map_err(gx)?; + Ok(staged_entry_at(&index, rel)) +} + +fn staged_entry_at(index: &gix::index::State, rel: &str) -> Option { + let entry = index.entry_by_path_and_stage(BStr::new(rel.as_bytes()), Stage::Unconflicted)?; + if entry.flags.contains(Flags::INTENT_TO_ADD) { + return None; + } + let mode = match entry.mode { + Mode::FILE => "100644", + Mode::FILE_EXECUTABLE => "100755", + _ => return None, + }; + Some(StagedEntry { mode, id: entry.id }) +} + +fn stale() -> IdeError { + IdeError::new(ErrorKind::OutOfSync, "The staged version changed on disk") +} + +fn updated_text(bytes: &[u8], text: &str, encoding: TextEncoding) -> IdeResult>> { + if is_binary(bytes, encoding) { + return Err(IdeError::invalid("Binary files cannot be edited in the index")); + } + let old = decode(bytes, encoding); + if normalize_eol(&old) == normalize_eol(text) { + return Ok(None); + } + let updated = replace_text(&old, text); + Ok(Some(encode(&updated, encoding, has_bom(bytes, encoding))?)) +} + +fn publish_index(mut lock: gix::lock::File, path: &Path, scratch: &TempIndex) -> IdeResult<()> { + let permissions = fs::metadata(path)?.permissions(); + let mut result = File::open(scratch.path())?; + lock.with_mut(|out| { + std::io::copy(&mut result, out)?; + out.set_permissions(permissions)?; + out.sync_all() + })?; + lock.commit().map_err(gx)?; + Ok(()) +} + +impl Repo { + pub fn staging_line_hunks( + &self, + path: &Path, + head_path: Option<&Path>, + working: &str, + max_bytes: usize, + encoding: impl Fn(&Path, &[u8]) -> TextEncoding, + ) -> IdeResult> { + if working.len() > max_bytes { + return Ok(None); + } + let Some(index) = self.staged_text(path, max_bytes, |bytes| encoding(path, bytes))? else { + return Ok(None); + }; + let head_path = head_path.unwrap_or(path); + let bytes = self.file_bytes_at(head_path, Some("HEAD"))?.unwrap_or_default(); + let encoding = encoding(head_path, &bytes); + if bytes.len() > max_bytes || is_binary(&bytes, encoding) { + return Ok(None); + } + let head = decode(&bytes, encoding); + Ok(Some(StagingLineHunks { + hunks: crate::diff::staging_line_hunks(&head, &index.text, working), + index_version: index.version, + })) + } + + pub fn staged_text( + &self, + path: &Path, + max_bytes: usize, + encoding: impl FnOnce(&[u8]) -> TextEncoding, + ) -> IdeResult> { + let _scope = self.execution_scope(); + let repo = self.gix()?; + let rel = self.rel_path(path)?; + let Some(entry) = staged_entry(&repo, &rel)? else { + return Ok(None); + }; + if repo.try_find_header(entry.id).map_err(gx)?.is_some_and(|header| header.size() > max_bytes as u64) { + return Ok(None); + } + let bytes = blob_data(&repo, entry.id)?; + if bytes.len() > max_bytes { + return Ok(None); + } + let encoding = encoding(&bytes); + if is_binary(&bytes, encoding) { + return Ok(None); + } + Ok(Some(StagedText { text: normalize_eol(&decode(&bytes, encoding)).into_owned(), version: entry.version() })) + } + + /// Replaces one stage-zero blob if the editor still has its current version. + pub fn save_staged_text( + &self, + path: &Path, + version: &str, + text: &str, + encoding: impl FnOnce(&[u8]) -> TextEncoding, + ) -> IdeResult { + let _scope = self.execution_scope(); + let repo = self.gix()?; + let path_to_index = repo.index_path(); + let lock = + gix::lock::File::acquire_to_update_resource(&path_to_index, gix::lock::acquire::Fail::Immediately, None, 0) + .map_err(gx)?; + let rel = self.rel_path(path)?; + let Some(entry) = staged_entry(&repo, &rel)? else { + return Err(stale()); + }; + let current = entry.version(); + if version != current { + return Err(stale()); + } + let bytes = blob_data(&repo, entry.id)?; + let encoding = encoding(&bytes); + let Some(contents) = updated_text(&bytes, text, encoding)? else { + return Ok(current); + }; + + // Let Git update the complete index, including its extensions, while its usual + // lock protects the input version and prevents a concurrent writer from losing edits. + let scratch = TempIndex::new(self); + fs::copy(&path_to_index, scratch.path())?; + let id = write::write_index_blob(self, &rel, &contents, &scratch.env())?; + publish_index(lock, &path_to_index, &scratch)?; + Ok(format!("{}:{id}", entry.mode)) + } + + /// Publishes formatter output against exactly the Git operation and index the user reviewed. + pub fn format_reviewed_apply( + &self, + checkpoint: &str, + edits: &[StagedTextEdit], + cancel: &CancellationToken, + encoding: impl Fn(&Path, &[u8]) -> TextEncoding, + ) -> IdeResult { + let _scope = self.execution_scope(); + let repo = self.gix()?; + let index_path = repo.index_path(); + let lock = + gix::lock::File::acquire_to_update_resource(&index_path, gix::lock::acquire::Fail::Immediately, None, 0) + .map_err(gx)?; + let review = self.require_apply_review(checkpoint, cancel)?; + let mut paths = review.paths.iter().map(|path| self.rel_path(&path.0)).collect::>>()?; + let index = repo.open_index().map_err(gx)?; + let scratch = TempIndex::new(self); + fs::copy(&index_path, scratch.path())?; + for edit in edits { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let path = &edit.path.0; + let rel = self.rel_path(path)?; + if !paths.remove(&rel) { + return Err(stale()); + } + let entry = + staged_entry_at(&index, &rel).filter(|entry| entry.version() == edit.version).ok_or_else(stale)?; + let bytes = blob_data(&repo, entry.id)?; + if let Some(contents) = updated_text(&bytes, &edit.text, encoding(path, &bytes))? { + write::write_index_blob(self, &rel, &contents, &scratch.env())?; + } + } + // Leave an existing non-empty resolution intact when formatting would make the step empty. + let Some(formatted) = self.review_apply_index(cancel, &scratch.env())? else { return Ok(review) }; + if formatted.checkpoint == checkpoint { + return Ok(review); + } + self.require_apply_review(checkpoint, cancel)?; + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + publish_index(lock, &index_path, &scratch)?; + Ok(formatted) + } +} diff --git a/crates/ide-vcs/src/status.rs b/crates/ide-vcs/src/status.rs index 3a04c41b1..6f5d6ba52 100644 --- a/crates/ide-vcs/src/status.rs +++ b/crates/ide-vcs/src/status.rs @@ -31,6 +31,36 @@ pub(crate) fn status(r: &Repo) -> IdeResult> { Ok(collect(r, &ignored, map, conflicts)) } +/// Git-ignored working-tree entries, with ignored directories reported as one entry each. +pub(crate) fn ignored_files(r: &Repo) -> IdeResult> { + let ignored = r.ignored.read().unwrap_or_else(|p| p.into_inner()).clone(); + let overrides = crate::cli::filter_overrides(r.root(), &ide_core::CancellationToken::new())?; + let mut args: Vec<&str> = overrides.iter().map(String::as_str).collect(); + args.extend([ + "status", + "--porcelain=v2", + "-z", + "--untracked-files=normal", + "--ignored=matching", + "--no-renames", + "--ignore-submodules=all", + ]); + let output = crate::cli::run_env(r.root(), &args, None, &read_only())?; + Ok(output + .stdout + .split(|b| *b == 0) + .filter_map(|record| std::str::from_utf8(record.strip_prefix(b"! ")?).ok()) + .filter(|rel| !rel.is_empty() && !ignored.is_ignored_path(rel)) + .map(|rel| FileStatus { + path: r.abs_path(rel).into(), + rel_path: rel.into(), + staged: None, + unstaged: Some(ChangeKind::Ignored), + renamed_from: None, + }) + .collect()) +} + /// Status of `paths` only (repository-relative, `/`-separated): the dirty-scope refresh. /// /// A watcher batch touches a few files, and the full status walks the whole tree; git's own @@ -210,9 +240,11 @@ fn gix_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult { } } } + // Gitoxide's index writer omits resolve-undo data. Keep those saved conflicts. // Serialize write-back and identity capture with watcher queries. if let Some(mut outcome) = iter.into_outcome() && outcome.has_changes() + && outcome.worktree_index.resolve_undo().is_none() { let mut writes = crate::index_writes::lock(); // Another process rewrote the index while this status run was reading it diff --git a/crates/ide-vcs/src/submodules.rs b/crates/ide-vcs/src/submodules.rs new file mode 100644 index 000000000..833097058 --- /dev/null +++ b/crates/ide-vcs/src/submodules.rs @@ -0,0 +1,182 @@ +//! Operations on the commits recorded for submodules. + +use crate::{Repo, cli, preserve, repo::gx}; +use gix::bstr::{BStr, ByteSlice}; +use gix::index::entry::Stage; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use std::path::{Component, Path, PathBuf}; + +#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub enum SubmoduleRollbackSource { + Head, + Index, +} + +impl Repo { + pub(crate) fn submodule_links(&self) -> IdeResult> { + let repo = self.gix()?; + let Some(modules) = repo.submodules().map_err(gx)? else { return Ok(Vec::new()) }; + let index = repo.index_or_empty().map_err(gx)?; + let mut links = Vec::new(); + for module in modules { + let raw = module.path().map_err(gx)?; + let Ok(name) = raw.to_str() else { continue }; + let path = Path::new(name); + if name.is_empty() || !path.components().all(|part| matches!(part, Component::Normal(_))) { + continue; + } + if let Some(entry) = index.entry_by_path_and_stage(BStr::new(name.as_bytes()), Stage::Unconflicted) + && entry.mode.is_submodule() + { + links.push((path.to_path_buf(), entry.id)); + } + } + Ok(links) + } + + pub(crate) fn initialized_submodule(&self, rel: &Path) -> Option { + let path = self.root().join(rel); + if !path.join(".git").exists() { + return None; + } + let root = dunce::canonicalize(self.root()).ok()?; + (dunce::canonicalize(&path).ok()?.strip_prefix(root).ok()? == rel).then_some(path) + } + + pub(crate) fn initialized_submodules(&self) -> IdeResult> { + Ok(self.submodule_links()?.into_iter().filter_map(|(rel, _)| self.initialized_submodule(&rel)).collect()) + } + + /// Restores the parent index, an initialized checkout, or a missing submodule directory. + pub fn rollback_submodule( + &self, + path: &Path, + source: SubmoduleRollbackSource, + restore_checkout: bool, + ) -> IdeResult<()> { + let _scope = self.execution_scope(); + if !crate::execution_allowed() { + return Err(IdeError::invalid("Submodule rollback requires a trusted project")); + } + let rel = self.rel_path(path)?; + let index = self.diff_entry_at(path, ":0")?; + let head = if source == SubmoduleRollbackSource::Head { self.head()?.1 } else { None }; + let recorded = head.as_deref().map(|rev| self.diff_entry_at(path, rev)).transpose()?.flatten(); + let index_commit = index.as_ref().and_then(|entry| entry.gitlink.as_deref()); + let target = match source { + SubmoduleRollbackSource::Head => recorded.as_ref().and_then(|entry| entry.gitlink.as_deref()), + SubmoduleRollbackSource::Index => index_commit, + }; + if target.is_none() && (source != SubmoduleRollbackSource::Head || index_commit.is_none()) { + return Err(IdeError::invalid(format!("{rel} is no longer a submodule change"))); + } + let reset_index = source == SubmoduleRollbackSource::Head && target != index_commit; + if restore_checkout && let Some(target) = target { + let checkout = self.root().join(&rel); + let child = self + .initialized_submodule(Path::new(&rel)) + .and_then(|root| Self::discover(&root).ok().flatten().filter(|repo| repo.root() == root)); + if let Some(child) = child { + child.set_execution_allowed(true); + if child.head()?.1.as_deref() != Some(target) { + if child.operation()?.is_some() || !crate::write::unmerged_paths(&child)?.is_empty() { + return Err(IdeError::invalid( + "Finish the Git operation in the submodule before rolling it back", + )); + } + // A normal checkout lets Git carry edits across or refuse an overwrite. Nested + // submodules are separate changes in the parent Commit tree. + cli::run(child.root(), &["checkout", "--no-recurse-submodules", "--detach", target, "--"], None)?; + } + } else if std::fs::symlink_metadata(checkout) + .is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound) + { + let mut args = vec!["--literal-pathspecs", "restore", "--worktree", "--no-recurse-submodules"]; + if let Some(rev) = head.as_deref() { + args.extend(["--source", rev]); + } + args.extend(["--", &rel]); + cli::run(self.root(), &args, None)?; + } else if !reset_index { + return Err(IdeError::invalid(format!("Submodule checkout is unavailable for {rel}"))); + } + } + if reset_index { + if let Some(head) = head { + cli::run( + self.root(), + &[ + "--literal-pathspecs", + "restore", + "--staged", + "--no-recurse-submodules", + "--source", + &head, + "--", + &rel, + ], + None, + )?; + } else { + crate::write::unstage(self, std::slice::from_ref(&path.to_path_buf()))?; + } + } + Ok(()) + } + + /// Updates a single detached checkout. The caller visits every child in parent-first order + /// so Git does not switch checked-out branches or bypass protection in nested worktrees. + pub fn update_from_superproject( + &self, + parent: &Repo, + cancel: &CancellationToken, + on_output: &dyn Fn(String), + ) -> IdeResult<()> { + // The superproject's git runs it; the submodule can only restrict what it may do. + let _parent = parent.execution_scope(); + let _scope = self.execution_scope(); + if !crate::execution_allowed() { + return Err(IdeError::invalid("Submodule update requires a trusted project")); + } + let relative = self + .root() + .strip_prefix(parent.root()) + .map_err(|_| IdeError::invalid("The submodule is outside its parent repository"))?; + let Some((_, target)) = parent.submodule_links()?.into_iter().find(|(path, _)| path == relative) else { + return Ok(()); + }; + if !parent.initialized_submodules()?.iter().any(|path| path == self.root()) { + return Err(IdeError::invalid("The submodule worktree is no longer available")); + } + let (branch, head) = self.head()?; + if branch.is_some() { + return Err(IdeError::invalid("The submodule is now on a branch. Update it again to use its upstream.")); + } + if head.as_deref() == Some(target.to_string().as_str()) { + return Ok(()); + } + if parent.operation()?.is_some() || !crate::write::unmerged_paths(parent)?.is_empty() { + return Err(IdeError::invalid( + "Finish the Git operation in the parent repository before updating its submodule", + )); + } + if self.operation()?.is_some() || !crate::write::unmerged_paths(self)?.is_empty() { + return Err(IdeError::invalid("Finish the Git operation in the submodule before updating it")); + } + let path = ide_core::ipc_path::to_ipc(relative); + preserve::around(self, "Local changes saved before update", || { + if self.head()?.0.is_some() { + return Err(IdeError::invalid( + "The submodule is now on a branch. Update it again to use its upstream.", + )); + } + cli::run_streaming( + parent.root(), + &["-c", "submodule.recurse=false", "--literal-pathspecs", "submodule", "update", "--", &path], + cancel, + on_output, + ) + }) + } +} diff --git a/crates/ide-vcs/src/worktree_config.rs b/crates/ide-vcs/src/worktree_config.rs new file mode 100644 index 000000000..e47052bf6 --- /dev/null +++ b/crates/ide-vcs/src/worktree_config.rs @@ -0,0 +1,104 @@ +use crate::Repo; +use crate::cli::run; +use crate::ignore::is_link; +use crate::repo::{gx, tree_of}; +use gix::bstr::BStr; +use ide_core::{IdeError, IdeResult}; +use std::fs; +use std::io::{self, ErrorKind}; +use std::path::{Component, Path, PathBuf}; + +const INCLUDE: &str = ".worktreeinclude"; + +impl Repo { + /// The worktree's include file path and whether it is a regular file on disk. + pub fn worktree_include(&self) -> IdeResult<(PathBuf, bool)> { + let path = self.root().join(INCLUDE); + match fs::symlink_metadata(&path) { + Ok(meta) if meta.is_file() && !is_link(&meta) => Ok((path, true)), + Ok(_) => Err(IdeError::invalid(".worktreeinclude is not a regular file")), + Err(error) if error.kind() == ErrorKind::NotFound => Ok((path, false)), + Err(error) => Err(error.into()), + } + } + + /// Copies local files listed in the source worktree's .worktreeinclude after checkout. + pub fn copy_worktree_config(&self, target: &Path) -> IdeResult<()> { + if !self.worktree_include()?.1 { + return Ok(()); + } + let root = self.root(); + let _scope = self.execution_scope(); + let matches = run( + root, + &["ls-files", "-z", "--cached", "--others", "--ignored", "--exclude-from=.worktreeinclude"], + None, + )?; + let repo = self.gix()?; + let head = tree_of(&repo, "HEAD")?; + let target = root.join(target); + let meta = fs::symlink_metadata(&target)?; + if !meta.is_dir() || is_link(&meta) { + return Err(IdeError::invalid("worktree location is not a regular directory")); + } + let mut failures = Vec::new(); + for raw in matches.stdout.split(|&byte| byte == 0).filter(|path| !path.is_empty()) { + let rel = gix::path::from_bstr(BStr::new(raw)).map_err(gx)?; + if rel + .components() + .any(|part| !matches!(part, Component::Normal(name) if !name.eq_ignore_ascii_case(".git"))) + { + continue; + } + if let Some(tree) = &head + && tree.lookup_entry_by_path(&rel).map_err(gx)?.is_some() + { + continue; + } + if let Err(error) = copy_local_file(root, &target, &rel) { + failures.push(format!("{}: {error}", rel.display())); + } + } + if failures.is_empty() { Ok(()) } else { Err(IdeError::invalid(failures.join("\n"))) } + } +} + +fn ordinary_directories(root: &Path, relative: &Path, create: bool) -> io::Result { + let mut path = root.to_path_buf(); + for part in relative.components() { + path.push(part); + match fs::symlink_metadata(&path) { + Ok(meta) if meta.is_dir() && !is_link(&meta) => {} + Ok(_) => return Err(io::Error::new(ErrorKind::AlreadyExists, "path is not a regular directory")), + Err(error) if create && error.kind() == ErrorKind::NotFound => fs::create_dir(&path)?, + Err(error) => return Err(error), + } + } + Ok(path) +} + +fn copy_local_file(source: &Path, target: &Path, relative: &Path) -> io::Result<()> { + let source_file = source.join(relative); + let meta = match fs::symlink_metadata(&source_file) { + Ok(meta) if meta.is_file() && !is_link(&meta) => meta, + Ok(_) => return Ok(()), + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error), + }; + let dir = relative.parent().unwrap_or(Path::new("")); + ordinary_directories(source, dir, false)?; + let destination = target.join(relative); + match fs::symlink_metadata(&destination) { + Ok(_) => return Ok(()), + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + let mut temporary = tempfile::NamedTempFile::new_in(ordinary_directories(target, dir, true)?)?; + io::copy(&mut fs::File::open(source_file)?, &mut temporary)?; + temporary.as_file().set_permissions(meta.permissions())?; + match temporary.persist_noclobber(destination) { + Ok(_) => Ok(()), + Err(error) if error.error.kind() == ErrorKind::AlreadyExists => Ok(()), + Err(error) => Err(error.error), + } +} diff --git a/crates/ide-vcs/src/write.rs b/crates/ide-vcs/src/write.rs index fa9efa555..a0150160a 100644 --- a/crates/ide-vcs/src/write.rs +++ b/crates/ide-vcs/src/write.rs @@ -2,15 +2,20 @@ use crate::TextEncoding; use crate::cli::{self, run}; +use crate::push_report; use crate::repo::{gx, resolve}; use crate::text_encoding::{decode, encode, has_bom, is_binary}; use crate::{ - BlameLine, BranchUpdate, BranchUpdateStatus, CheckoutMode, CheckoutOptions, CheckoutOutcome, CommitOptions, - DeletedBranch, DivergedLocal, PushBranchOptions, Repo, + BlameLine, BranchCreation, BranchCreationOutcome, BranchRebasePlan, BranchUpdate, BranchUpdateStatus, CheckoutMode, + CheckoutOptions, CheckoutOutcome, CheckoutRebasePlan, CommitOptions, DeletedBranch, DivergedLocal, HistoryTip, + LargeCommitFile, MergeOptions, MergeOutcome, PartialCommitFile, PushBranchOptions, PushRefStatus, PushReport, + PushTags, Repo, UpstreamTracking, }; use gix::bstr::{BStr, ByteSlice}; -use ide_core::error::ErrorKind; -use ide_core::{CancellationToken, IdeError, IdeResult}; +use ide_core::error::{ErrorData, ErrorKind, PushDivergence}; +use ide_core::workflow_settings::{FetchTagsMode, GitAnnotateMovement, GitAnnotateSettings}; +use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath}; +use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; const UNCOMMITTED_AUTHOR: &str = "Not Committed Yet"; @@ -114,6 +119,7 @@ pub(crate) fn blame( current_text: Option<&str>, revision: Option<&str>, encoding: TextEncoding, + options: GitAnnotateSettings, ) -> IdeResult> { let rel = r.rel_path(path)?; let revision = match revision { @@ -127,8 +133,22 @@ pub(crate) fn blame( }; let text = current_text.map(str::to_owned).unwrap_or_else(|| decode(&disk, encoding).into_owned()); let ignore = ignore_revs_args(r); + let mut args = vec!["--literal-pathspecs", "blame", "--porcelain"]; + if options.ignore_whitespace { + args.push("-w"); + } + match options.movement { + GitAnnotateMovement::None => {} + GitAnnotateMovement::WithinFile => args.push("-M"), + GitAnnotateMovement::AcrossFiles => args.push("-C"), + } + if !crate::execution_allowed() { + args.push("--no-textconv"); + } + args.extend(ignore.iter().map(String::as_str)); + let plain_args = [args.as_slice(), &[revision, "--", &rel]].concat(); if encoding.has_ascii_conversion() { - return converted_blame(r, path, &rel, &text, revision, encoding, &ignore); + return converted_blame(r, path, (&rel, revision), &text, encoding, &plain_args, options.ignore_whitespace); } let contents = match current_text { Some(_) if crate::diff::normalize_eol(&text) == crate::diff::normalize_eol(&decode(&disk, encoding)) => disk, @@ -160,43 +180,34 @@ pub(crate) fn blame( // older releases reject the pair (`fatal: cannot use --contents with final // commit object name`) and take the same plain path — the edited lines are // marked uncommitted below either way (issue #755). - let contents_args = { - let mut args = vec!["--literal-pathspecs", "blame", "--porcelain"]; - args.extend(ignore.iter().map(String::as_str)); - args.extend(["--contents", "-", revision, "--", &rel]); - args - }; - let plain_args: Vec<&str> = { - let mut args = vec!["--literal-pathspecs", "blame"]; - if !crate::execution_allowed() { - args.push("--no-textconv"); - } - args.extend(ignore.iter().map(String::as_str)); - args.extend(["--porcelain", revision, "--", &rel]); - args - }; let (out, contents_blame) = if crate::execution_allowed() { - let out = cli::run_raw(r.root(), &contents_args, Some(&contents))?; + args.extend(["--contents", "-"]); + if revision != "HEAD" { + args.push(revision); + } + args.extend(["--", &rel]); + let out = cli::run_raw(r.root(), &args, Some(&contents))?; if out.code == Some(0) { (out, true) } else if String::from_utf8_lossy(&out.stderr).contains("cannot use --contents") { (run(r.root(), &plain_args, None)?, false) } else { - return Err(cli::failure(&contents_args, &out.stderr, &out.stdout, out.code)); + return Err(cli::failure(&args, &out.stderr, &out.stdout, out.code)); } } else { (run(r.root(), &plain_args, None)?, false) }; - let mut lines = crate::blame::parse_porcelain(&out.stdout_str()); + let mut lines = crate::blame::parse_porcelain(&out.stdout_str(), r.root(), &rel); for line in &mut lines { if line.commit.bytes().all(|b| b == b'0') { line.author = UNCOMMITTED_AUTHOR.to_string(); line.summary = String::new(); + line.origin_path = None; } } if !contents_blame { let base = r.file_at(path, Some(revision), encoding)?.unwrap_or_default(); - for hunk in crate::diff::line_hunks(&base, &text).into_iter().rev() { + for hunk in blame_hunks(&base, &text, options.ignore_whitespace).into_iter().rev() { let start = (hunk.old_start as usize).min(lines.len()); let end = (start + hunk.old_lines as usize).min(lines.len()); lines.splice(start..end, uncommitted_lines(hunk.lines as usize)); @@ -210,29 +221,35 @@ pub(crate) fn blame( Ok(lines) } +fn blame_hunks(base: &str, text: &str, ignore_whitespace: bool) -> Vec { + if !ignore_whitespace { + return crate::diff::line_hunks(base, text); + } + let strip = |text: &str| { + let text = crate::diff::normalize_eol(text); + let mut normalized = text.replace([' ', '\t', '\u{b}', '\u{c}'], ""); + if !text.is_empty() && !text.ends_with('\n') { + normalized.push('\n'); + } + normalized + }; + crate::diff::line_hunks(&strip(base), &strip(text)) +} + fn converted_blame( r: &Repo, path: &Path, - rel: &str, + (rel, revision): (&str, &str), text: &str, - revision: &str, encoding: TextEncoding, - ignore: &[String], + args: &[&str], + ignore_whitespace: bool, ) -> IdeResult> { let current = crate::diff::normalize_eol(text); let mut result = uncommitted_lines(current.split_inclusive('\n').count()); let Some(base) = r.file_bytes_at(path, Some(revision))? else { return Ok(result) }; - let args: Vec<&str> = { - let mut args = vec!["--literal-pathspecs", "blame"]; - if !crate::execution_allowed() { - args.push("--no-textconv"); - } - args.extend(ignore.iter().map(String::as_str)); - args.extend(["--porcelain", revision, "--", rel]); - args - }; - let out = run(r.root(), &args, None)?; - let physical = crate::blame::parse_porcelain(&out.stdout_str()); + let out = run(r.root(), args, None)?; + let physical = crate::blame::parse_porcelain(&out.stdout_str(), r.root(), rel); let raw = crate::text_encoding::decode_raw(&base, encoding); let raw = crate::diff::normalize_eol(&raw); let mut logical = Vec::new(); @@ -242,7 +259,7 @@ fn converted_blame( logical.extend(std::iter::repeat_n(metadata, displayed.split_inclusive('\n').count())); } let base = decode(&base, encoding); - let hunks = crate::diff::line_hunks(&base, ¤t); + let hunks = blame_hunks(&base, ¤t, ignore_whitespace); let (mut old, mut new) = (0usize, 0usize); for h in hunks { let unchanged = h.start as usize - new; @@ -269,6 +286,7 @@ fn uncommitted_lines(n: usize) -> Vec { author: UNCOMMITTED_AUTHOR.to_string(), time_ms: now, summary: String::new(), + origin_path: None, }) .collect() } @@ -315,6 +333,27 @@ pub(crate) fn stage(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> { run_paths(r, &["add", "-A"], &rel) } +pub(crate) fn stage_without_content(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> { + run_paths(r, &["add", "--intent-to-add"], &r.rel_paths(paths)?) +} + +pub(crate) fn restore_unstaged(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> { + use gix::index::entry::{Flags, Stage}; + let rel = r.rel_paths(paths)?; + let repo = r.gix()?; + let index = repo.index_or_empty().map_err(gx)?; + for path in &rel { + // An intent-to-add entry stands in for an absent file, even though Git gives it an empty blob. + if index + .entry_by_path_and_stage(BStr::new(path.as_bytes()), Stage::Unconflicted) + .is_none_or(|entry| entry.flags.contains(Flags::INTENT_TO_ADD)) + { + return Err(IdeError::invalid(format!("No staged version to restore for {path}"))); + } + } + run_paths(r, &["restore", "--worktree"], &rel) +} + pub(crate) fn unstage(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> { let rel = r.rel_paths(paths)?; if r.has_head()? { @@ -438,25 +477,53 @@ pub(crate) fn discard(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> { Ok(()) } +pub(crate) fn commit_metadata_flags( + sign_off: bool, + run_hooks: bool, + author: Option<&str>, + author_date: Option<&str>, +) -> Vec { + let mut flags = Vec::new(); + if sign_off { + flags.push("--signoff".into()); + } + if !run_hooks { + flags.push("--no-verify".into()); + } + flags.extend(author.map(str::trim).filter(|a| !a.is_empty()).map(|a| format!("--author={a}"))); + flags.extend(author_date.map(str::trim).filter(|d| !d.is_empty()).map(|d| format!("--date={d}"))); + flags +} + pub(crate) fn commit( r: &Repo, message: &str, options: &CommitOptions, encoding: &dyn Fn(&Path) -> IdeResult, ) -> IdeResult { + if matches!(r.operation()?.as_deref(), Some("cherry-pick" | "revert")) { + return Err(IdeError::invalid("Use Continue to commit the paused cherry-pick or revert")); + } let mut args = vec!["commit", "-q", "--cleanup=whitespace"]; - if options.amend { + let specific = options.amend_target.as_ref(); + if specific.is_some() { + if !options.amend { + return Err(IdeError::invalid("an amend target requires Amend mode")); + } + args.push("--allow-empty"); + } else if options.amend { args.push("--amend"); } - if options.sign_off { - args.push("--signoff"); - } - if !options.run_hooks { - args.push("--no-verify"); - } - let author = options.author.as_deref().map(str::trim).filter(|a| !a.is_empty()).map(|a| format!("--author={a}")); - if let Some(a) = &author { - args.push(a.as_str()); + let flags = commit_metadata_flags( + options.sign_off, + options.run_hooks, + options.author.as_deref(), + options.author_date.as_deref(), + ); + args.extend(flags.iter().map(String::as_str)); + if let Some(target) = specific { + args.extend(["-F", "-"]); + return crate::commit_rewrite::amend(r, target, message, &args, options, encoding); } let stdin = if options.amend && message.trim().is_empty() { args.push("--no-edit"); @@ -528,6 +595,15 @@ fn select_into( std::fs::copy(&index, &tmp.0)?; } let env = [("GIT_INDEX_FILE", tmp.0.as_os_str())]; + fill_commit_index(r, &env, options, encoding) +} + +pub(crate) fn fill_commit_index( + r: &Repo, + env: &[(&str, &std::ffi::OsStr)], + options: &CommitOptions, + encoding: &dyn Fn(&Path) -> IdeResult, +) -> IdeResult> { let rel_paths = |paths: &[ide_core::IpcPath]| -> IdeResult> { let paths: Vec = paths.iter().map(|p| p.0.clone()).collect(); r.rel_paths(&paths) @@ -539,46 +615,206 @@ fn select_into( } else { &["--literal-pathspecs", "rm", "--cached", "-r", "-q", "--ignore-unmatch", "--"] }; - cli::run_paths_env(r.root(), args, &exclude, None, &env)?; + cli::run_paths_env(r.root(), args, &exclude, None, env)?; } let mut rels = rel_paths(&options.stage)?; - cli::run_paths_env(r.root(), &["--literal-pathspecs", "add", "-A", "--"], &rels, None, &env)?; + cli::run_paths_env(r.root(), &["--literal-pathspecs", "add", "-A", "--"], &rels, None, env)?; for file in &options.partial { let rel = r.rel_path(&file.path.0)?; - let head = { - let repo = r.gix()?; - crate::repo::blob_at(&repo, &rel, "HEAD")? - } - .ok_or_else(|| { - IdeError::invalid(format!("{rel}: only changes of a file in HEAD can be committed partially")) - })?; - let disk = std::fs::read(r.abs_path(&rel))?; let encoding = encoding(&file.path.0)?; - let bom = has_bom(&head, encoding); - if is_binary(&head, encoding) || is_binary(&disk, encoding) { - return Err(IdeError::invalid(format!("{rel}: binary files cannot be committed partially"))); - } - let (head, disk) = (decode(&head, encoding), decode(&disk, encoding)); - let hunks = crate::diff::line_hunks(&head, &disk); - let mut selected = Vec::new(); - for want in &file.hunks { - let found = hunks.iter().position(|h| { - (h.start, h.lines, h.old_start, h.old_lines) == (want.start, want.lines, want.old_start, want.old_lines) - }); - match found { - Some(i) => selected.push(i), - None => return Err(IdeError::invalid(format!("{rel} changed on disk; review its changes again"))), - } - } - cli::run_env(r.root(), &["--literal-pathspecs", "reset", "-q", "HEAD", "--", &rel], None, &env)?; - let text = crate::diff::selected_text(&head, &disk, &selected); + let (text, bom) = partial_commit_text(r, &rel, file, encoding)?; + cli::run_env(r.root(), &["--literal-pathspecs", "reset", "-q", "HEAD", "--", &rel], None, env)?; let bytes = encode(&text, encoding, bom)?; - write_index_blob(r, &rel, &bytes, &env)?; + write_index_blob(r, &rel, &bytes, env)?; rels.push(rel); } Ok(rels) } +pub(crate) fn partial_commit_text( + r: &Repo, + rel: &str, + file: &PartialCommitFile, + encoding: TextEncoding, +) -> IdeResult<(String, bool)> { + let (selected, bom) = select_partial_commit_text(r, rel, file, encoding)?; + let Some(prepared) = &file.prepared else { return Ok((selected, bom)) }; + if crate::diff::normalize_eol(&selected) != prepared.before { + return Err(IdeError::invalid(format!("{rel} changed on disk; review its changes again"))); + } + if prepared.text.contains('\0') { + return Err(IdeError::invalid(format!("{rel}: binary files cannot be committed partially"))); + } + Ok((crate::diff::replace_text(&selected, &prepared.text), bom)) +} + +fn select_partial_commit_text( + r: &Repo, + rel: &str, + file: &PartialCommitFile, + encoding: TextEncoding, +) -> IdeResult<(String, bool)> { + let repo = r.gix()?; + let head = crate::repo::blob_at(&repo, rel, "HEAD")?.ok_or_else(|| { + IdeError::invalid(format!("{rel}: only changes of a file in HEAD can be committed partially")) + })?; + let disk = std::fs::read(r.abs_path(rel))?; + let bom = has_bom(&head, encoding); + if is_binary(&head, encoding) || is_binary(&disk, encoding) { + return Err(IdeError::invalid(format!("{rel}: binary files cannot be committed partially"))); + } + let (head, disk) = (decode(&head, encoding), decode(&disk, encoding)); + let hunks = crate::diff::line_hunks(&head, &disk); + let stale = || IdeError::invalid(format!("{rel} changed on disk; review its changes again")); + let find = |want: &crate::HunkRange| { + hunks + .iter() + .position(|h| { + (h.start, h.lines, h.old_start, h.old_lines) == (want.start, want.lines, want.old_start, want.old_lines) + }) + .ok_or_else(stale) + }; + let selected = file.hunks.iter().map(find).collect::>>()?; + if file.line_hunks.is_empty() { + return Ok((crate::diff::selected_text(&head, &disk, &selected), bom)); + } + let normalized = crate::diff::normalize_eol(&disk); + let lines: Vec<_> = normalized.split_inclusive('\n').collect(); + let mut partial = BTreeMap::new(); + for change in &file.line_hunks { + let index = find(&change.range)?; + let hunk = &hunks[index]; + let current = &lines[hunk.start as usize..(hunk.start + hunk.lines) as usize]; + if hunk.old_text != change.old_text || current.concat() != change.new_text { + return Err(stale()); + } + if selected.contains(&index) + || partial.insert(index, change).is_some() + || change.deletions.iter().any(|&line| line >= hunk.old_lines) + || change.additions.iter().any(|&line| line >= hunk.lines) + { + return Err(IdeError::invalid(format!("{rel}: invalid partial commit line selection"))); + } + } + Ok((crate::diff::selected_lines_text(&head, &disk, &selected, &partial), bom)) +} + +enum CommitFileSource<'a> { + Worktree, + Partial(&'a PartialCommitFile), +} + +/// Overrides for files whose selected content comes from outside the index. +fn commit_file_sources<'a>(r: &Repo, options: &'a CommitOptions) -> IdeResult>> { + let mut sources = BTreeMap::new(); + for path in &options.stage { + sources.insert(r.rel_path(&path.0)?, CommitFileSource::Worktree); + } + for file in &options.partial { + sources.insert(r.rel_path(&file.path.0)?, CommitFileSource::Partial(file)); + } + Ok(sources) +} + +pub(crate) fn commit_crlf_paths( + r: &Repo, + paths: &[PathBuf], + options: &CommitOptions, + encoding: &dyn Fn(&Path) -> IdeResult, + cancel: &CancellationToken, +) -> IdeResult> { + // Git converts CRLF on commit for `input` and for every spelling of a true boolean. + if paths.is_empty() + || matches!( + r.config_get("core.autocrlf")?.map(|s| s.trim().to_ascii_lowercase()).as_deref(), + Some("true" | "yes" | "on" | "1" | "input") + ) + { + return Ok(Vec::new()); + } + let paths = r.rel_paths(paths)?; + let file_sources = commit_file_sources(r, options)?; + let args = ["--literal-pathspecs", "ls-files", "--eol", "-z", "--cached", "--others", "--exclude-standard", "--"]; + let mut problems = BTreeSet::new(); + for batch in cli::batch_paths(cli::base_command_line_len(&args), &paths, cli::command_line_limit()) { + let mut full = args.to_vec(); + full.extend(batch.iter().map(String::as_str)); + let out = cli::run_cancellable(r.root(), &full, cancel)?; + let requested: BTreeSet<_> = batch.iter().map(String::as_str).collect(); + for row in out.stdout.split(|byte| *byte == 0) { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let row = String::from_utf8_lossy(row); + let Some((fields, rel)) = row.split_once('\t') else { continue }; + let Some((sources, attrs)) = fields.split_once("attr/") else { continue }; + if !attrs.trim().is_empty() || !requested.contains(rel) { + continue; + } + let mut sources = sources.split_whitespace(); + let staged_eol = sources.next().and_then(|field| field.strip_prefix("i/")); + let working_eol = sources.next().and_then(|field| field.strip_prefix("w/")); + let has_crlf = match file_sources.get(rel) { + Some(CommitFileSource::Partial(file)) => encoding(&file.path.0) + .and_then(|encoding| partial_commit_text(r, rel, file, encoding)) + .is_ok_and(|(text, _)| text.contains("\r\n")), + Some(CommitFileSource::Worktree) => matches!(working_eol, Some("crlf" | "mixed")), + None => matches!(staged_eol, Some("crlf" | "mixed")), + }; + if has_crlf { + problems.insert(r.abs_path(rel)); + } + } + } + Ok(problems.into_iter().map(IpcPath).collect()) +} + +pub(crate) fn commit_large_files( + r: &Repo, + paths: &[PathBuf], + options: &CommitOptions, + limit: u64, + encoding: &dyn Fn(&Path) -> IdeResult, + cancel: &CancellationToken, +) -> IdeResult> { + if paths.is_empty() || limit == 0 || r.config_get("lfs.repositoryformatversion")?.is_some() { + return Ok(Vec::new()); + } + let paths = r.rel_paths(paths)?; + let sources = commit_file_sources(r, options)?; + let repo = r.gix()?; + let index = repo.index_or_empty().map_err(gx)?; + let mut large = Vec::new(); + for rel in paths { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let path = r.abs_path(&rel); + let size = match sources.get(&rel) { + Some(CommitFileSource::Worktree) => { + std::fs::symlink_metadata(&path).ok().filter(std::fs::Metadata::is_file).map(|meta| meta.len()) + } + Some(CommitFileSource::Partial(file)) => encoding(&file.path.0) + .and_then(|encoding| { + let (text, bom) = partial_commit_text(r, &rel, file, encoding)?; + encode(&text, encoding, bom) + }) + .ok() + .map(|bytes| bytes.len() as u64), + None => index + .entry_by_path_and_stage(BStr::new(rel.as_bytes()), gix::index::entry::Stage::Unconflicted) + .filter(|entry| !entry.mode.is_submodule()) + .and_then(|entry| repo.try_find_header(entry.id).ok().flatten()) + .filter(|header| header.kind() == gix::object::Kind::Blob) + .map(|header| header.size()), + }; + if let Some(size) = size.filter(|size| *size > limit) { + large.push(LargeCommitFile { path: IpcPath(path), size }); + } + } + Ok(large) +} + /// The changes a commit of `options` would make, as `git diff` reports them (renames /// detected), from HEAD (an empty tree without one). Nothing is committed and the /// working tree and the index are left alone: a selection is made in a copy of the @@ -722,7 +958,10 @@ pub(crate) fn checkout(r: &Repo, branch: &str, create: bool) -> IdeResult<()> { /// What a checkout of `branch` runs. enum SwitchPlan { - Switch(Vec), + Switch { + args: Vec, + target: String, + }, /// `git rebase `. Rebase { local: String, @@ -735,36 +974,119 @@ enum SwitchPlan { } fn switch_plan(r: &Repo, branch: &str, create: bool, diverged: Option) -> IdeResult { - let args = |a: &[&str]| SwitchPlan::Switch(a.iter().map(|s| s.to_string()).collect()); + let switch = |args: &[&str], target: String| SwitchPlan::Switch { + args: args.iter().map(|s| s.to_string()).collect(), + target, + }; if create { - return Ok(args(&["switch", "-c", branch])); + return Ok(switch(&["switch", "-c", branch], "HEAD".into())); } let repo = r.gix()?; + let detached = || Ok(switch(&["switch", "--detach", branch], resolve(&repo, branch)?.to_string())); + // Revision expressions such as `HEAD~1` are not branch names. + let candidate = format!("refs/heads/{branch}"); + if <&gix::refs::FullNameRef>::try_from(candidate.as_str()).is_err() { + return detached(); + } let exists = |name: &str| repo.try_find_reference(name).map_err(gx).map(|r| r.is_some()); - if exists(&format!("refs/heads/{branch}"))? { - return Ok(args(&["switch", branch])); - } - if exists(&format!("refs/remotes/{branch}"))? - && let Some((_, name)) = branch.split_once('/') - { - if !exists(&format!("refs/heads/{name}"))? { - return Ok(args(&["switch", "-c", name, "--track", branch])); + let qualified = branch.starts_with("refs/"); + let local_name = branch.strip_prefix("refs/heads/"); + if let Some(name) = local_name.or_else(|| (!qualified).then_some(branch)) { + let local = format!("refs/heads/{name}"); + if exists(&local)? { + return Ok(switch(&["switch", "--no-guess", check_rev(name)?], local)); + } + if local_name.is_some() { + return Err(IdeError::not_found(format!("unknown revision {branch}"))); } - // IDEA: a local namesake that is merely behind is fast-forwarded; one with commits - // of its own needs the user's choice. - let range = format!("{branch}..refs/heads/{name}"); - let ahead = run(r.root(), &["rev-list", "--count", &range], None)?.stdout_str().trim() != "0"; - return Ok(match (ahead, diverged) { - (true, None) => SwitchPlan::Ahead { local: name.to_string(), remote: branch.to_string() }, - (true, Some(DivergedLocal::Rebase)) => { - SwitchPlan::Rebase { local: name.to_string(), remote: branch.to_string() } - } - _ => args(&["switch", "-C", name, "--track", branch]), - }); } - // A tag or commit: detached HEAD. - resolve(&repo, branch)?; - Ok(args(&["switch", "--detach", branch])) + let remote_name = branch.strip_prefix("refs/remotes/"); + if let Some(remote) = remote_name.or_else(|| (!qualified).then_some(branch)) { + let remote_ref = format!("refs/remotes/{remote}"); + if exists(&remote_ref)? + && let Some(name) = remote_branch_name(&repo, remote) + { + if !exists(&format!("refs/heads/{name}"))? { + return Ok(switch(&["switch", "-c", name, "--track", &remote_ref], remote_ref.clone())); + } + // A local namesake with its own commits needs the user's choice. + let range = format!("{remote_ref}..refs/heads/{name}"); + let ahead = run(r.root(), &["rev-list", "--count", &range], None)?.stdout_str().trim() != "0"; + return Ok(match (ahead, diverged) { + (true, None) => SwitchPlan::Ahead { local: name.to_owned(), remote: remote.to_owned() }, + (true, Some(DivergedLocal::Rebase)) => SwitchPlan::Rebase { + local: name.to_owned(), + remote: unambiguous_branch_name(r, &remote_ref).to_owned(), + }, + _ => switch(&["switch", "-C", name, "--track", &remote_ref], remote_ref.clone()), + }); + } + if remote_name.is_some() { + return Err(IdeError::not_found(format!("unknown revision {branch}"))); + } + } + detached() +} + +fn remote_branch_name<'a>(repo: &gix::Repository, remote_ref: &'a str) -> Option<&'a str> { + repo.remote_names() + .iter() + .filter_map(|remote| remote_ref.strip_prefix(&format!("{remote}/"))) + .min_by_key(|name| name.len()) + .or_else(|| remote_ref.split_once('/').map(|(_, name)| name)) +} + +pub(crate) fn checkout_affected_files(r: &Repo, branch: &str) -> IdeResult> { + let branch = check_rev(branch.trim())?; + let SwitchPlan::Switch { target, .. } = switch_plan(r, branch, false, None)? else { return Ok(Vec::new()) }; + if !r.has_head()? || r.operation()?.is_some() { + return Ok(Vec::new()); + } + // The dry run leaves the index and worktree alone, but reports only the first failure. + let dry = cli::run_raw(r.root(), &["read-tree", "--dry-run", "-m", "-u", "HEAD", &target], None)?; + if dry.code == Some(0) { + return Ok(Vec::new()); + } + affected_tree_files(r, "HEAD", &target, false) +} + +pub(crate) fn merge_affected_files(r: &Repo, branch: &str) -> IdeResult> { + if r.operation()?.is_some() { + return Ok(Vec::new()); + } + let branch = check_rev(branch.trim())?; + let Some(head) = r.head()?.1 else { return Ok(Vec::new()) }; + let target = resolve(&r.gix()?, branch)?.to_string(); + let Some(base) = r.merge_base(&head, &target)? else { return Ok(Vec::new()) }; + if base == target { + return Ok(Vec::new()); + } + // A three-way merge can also refuse staged edits even on paths unchanged by the incoming branch. + affected_tree_files(r, &base, &target, base != head) +} + +fn affected_tree_files(r: &Repo, base: &str, target: &str, include_staged: bool) -> IdeResult> { + let changed = run(r.root(), &["diff", "--name-only", "-z", "--no-renames", base, target, "--"], None)?; + let changed = changed.stdout_str(); + let changed: BTreeSet<_> = changed.split_terminator('\0').collect(); + let dirty = run( + r.root(), + &["--no-optional-locks", "status", "--porcelain=v1", "-z", "--untracked-files=no", "--no-renames"], + None, + )?; + let dirty = dirty.stdout_str(); + let affected = dirty.split_terminator('\0').filter_map(|entry| { + let path = entry.get(3..)?; + if include_staged && !entry.starts_with(' ') { + return Some(path.to_owned()); + } + let prefix = format!("{path}/"); + let incoming = changed.contains(path) + || path.match_indices('/').any(|(i, _)| changed.contains(&path[..i])) + || changed.range(prefix.as_str()..).next().is_some_and(|changed| changed.starts_with(&prefix)); + incoming.then(|| path.to_owned()) + }); + Ok(affected.collect()) } /// Files git refuses to overwrite with local changes, from its error message. @@ -795,9 +1117,20 @@ fn branch_of_other_worktree(stderr: &str) -> Option<(String, String)> { } fn listed_files(stderr: &str, header: &str) -> Option> { - let mut lines = stderr.lines().skip_while(|l| !l.contains(header)); - lines.next()?; - Some(lines.take_while(|l| l.starts_with('\t')).map(|l| l.trim().to_string()).collect()) + let mut files = Vec::new(); + let mut in_list = false; + for line in stderr.lines() { + if let Some(path) = line.strip_prefix('\t') { + if in_list { + files.push(path.to_owned()); + } + } else { + in_list = line.contains(header); + } + } + files.sort_unstable(); + files.dedup(); + (!files.is_empty()).then_some(files) } pub(crate) fn checkout_with( @@ -813,7 +1146,7 @@ pub(crate) fn checkout_with( if branch.starts_with('-') { return Err(IdeError::invalid(format!("invalid revision '{branch}'"))); } - let mut args = match switch_plan(r, branch, create, options.diverged)? { + let args = match switch_plan(r, branch, create, options.diverged)? { SwitchPlan::Ahead { local, remote } => return Ok(CheckoutOutcome::LocalBranchAhead { local, remote }), SwitchPlan::Rebase { local, remote } => { crate::preserve::save(r, "Local changes saved before checkout")?; @@ -829,15 +1162,18 @@ pub(crate) fn checkout_with( } return Ok(CheckoutOutcome::Conflicts { files }); } - SwitchPlan::Switch(args) => args, + SwitchPlan::Switch { args, .. } => args, }; + switch_with(r, branch, args.iter().map(String::as_str).collect(), options) +} + +fn switch_with(r: &Repo, branch: &str, mut argv: Vec<&str>, options: &CheckoutOptions) -> IdeResult { if options.mode == CheckoutMode::Force { - args.push("--discard-changes".into()); + argv.push("--discard-changes"); } if options.ignore_other_worktrees { - args.push("--ignore-other-worktrees".into()); + argv.push("--ignore-other-worktrees"); } - let argv: Vec<&str> = args.iter().map(String::as_str).collect(); let out = cli::run_raw(r.root(), &argv, None)?; if out.code == Some(0) { return Ok(CheckoutOutcome::Done); @@ -855,39 +1191,14 @@ pub(crate) fn checkout_with( if options.mode != CheckoutMode::Smart { return Ok(CheckoutOutcome::LocalChanges { files }); } - // Smart Checkout: stash → switch → unstash, like IDEA. - let before = stash_count(r)?; - run(r.root(), &["stash", "push", "-q", "-m", &format!("Uncommitted changes before checkout of {branch}")], None)?; - if stash_count(r)? == before { - return Err(IdeError::invalid("could not save the local changes")); - } - if let Err(e) = run(r.root(), &argv, None) { - run(r.root(), &["stash", "pop", "-q", "--index"], None)?; - return Err(e); - } - // Staged changes come back staged; when the index can't be restored as it was (it - // conflicts with the new branch), the changes come back unstaged. - let pop = cli::run_raw(r.root(), &["stash", "pop", "-q", "--index"], None)?; - if pop.code == Some(0) { - return Ok(CheckoutOutcome::Done); - } - let pop = if unmerged_paths(r)?.is_empty() && stash_count(r)? > before { - cli::run_raw(r.root(), &["stash", "pop", "-q"], None)? - } else { - pop - }; - if pop.code == Some(0) { - return Ok(CheckoutOutcome::Done); - } - let files = unmerged_paths(r)?; - if files.is_empty() { - return Err(cli::failure(&["stash", "pop"], &pop.stderr, &pop.stdout, pop.code)); - } - Ok(CheckoutOutcome::Conflicts { files }) -} - -fn stash_count(r: &Repo) -> IdeResult { - Ok(run(r.root(), &["stash", "list"], None)?.stdout_str().lines().count()) + let restored = crate::preserve::checkout(r, &format!("Uncommitted changes before checkout of {branch}"), || { + run(r.root(), &argv, None).map(|_| ()) + })?; + Ok(match restored { + Ok(files) if files.is_empty() => CheckoutOutcome::Done, + Ok(files) => CheckoutOutcome::Conflicts { files }, + Err(error) => CheckoutOutcome::RestoreFailed { message: error.message }, + }) } /// Creates `name` at `start` (default HEAD); a remote-tracking start point is tracked. @@ -895,9 +1206,10 @@ pub(crate) fn create_branch( r: &Repo, name: &str, start: Option<&str>, - checkout: bool, + checkout: Option<&CheckoutOptions>, overwrite: bool, -) -> IdeResult<()> { + expected_tip: Option<&str>, +) -> IdeResult { let name = name.trim(); let valid = !name.is_empty() && !name.starts_with('-') @@ -907,15 +1219,23 @@ pub(crate) fn create_branch( return Err(IdeError::invalid(format!("'{name}' is not a valid branch name"))); } let start = start.map(str::trim).filter(|s| !s.is_empty()); - if let Some(s) = start { - if s.starts_with('-') { - return Err(IdeError::invalid("invalid start point")); - } - let repo = r.gix()?; - resolve(&repo, s)?; + let revision = check_rev(start.unwrap_or("HEAD"))?; + let tip = run(r.root(), &["rev-parse", "--verify", &format!("{revision}^{{commit}}")], None)? + .stdout_str() + .trim() + .to_string(); + let reference = format!("refs/heads/{name}"); + let previous_tip = if overwrite { + let out = cli::run_raw(r.root(), &["rev-parse", "--verify", "-q", &reference], None)?; + (out.code == Some(0)).then(|| out.stdout_str().trim().to_string()) + } else { + None + }; + if expected_tip.is_some() && previous_tip.as_deref() != expected_tip { + return Err(branch_creation_changed(name)); } - let no_track = start.is_some_and(|s| renamed_remote_start(r, name, s)); - let mut args = match (checkout, overwrite) { + let no_track = previous_tip.is_some() || start.is_some_and(|s| renamed_remote_start(r, name, s)); + let mut args = match (checkout.is_some(), overwrite) { (true, false) => vec!["switch", "-c", name], (true, true) => vec!["switch", "-C", name], (false, false) => vec!["branch"], @@ -924,18 +1244,75 @@ pub(crate) fn create_branch( if no_track { args.push("--no-track"); } - if !checkout { + if checkout.is_none() { args.extend(["--", name]); } args.extend(start); - let out = cli::run_raw(r.root(), &args, None)?; - if out.code == Some(0) { - return Ok(()); + let checkout = match checkout { + Some(options) => switch_with(r, name, args, options)?, + None => { + run(r.root(), &args, None)?; + CheckoutOutcome::Done + } + }; + let created = checkout.switched().then_some(BranchCreation { tip, previous_tip }); + Ok(BranchCreationOutcome { checkout, created }) +} + +fn branch_creation_changed(name: &str) -> IdeError { + IdeError::invalid(format!("Branch '{name}' changed during branch creation")) +} + +pub(crate) fn undo_branch_creation( + r: &Repo, + name: &str, + created: &BranchCreation, + previous_head: Option<&HistoryTip>, +) -> IdeResult<()> { + check_local_branch(r, name)?; + let reference = format!("refs/heads/{name}"); + let tip = run(r.root(), &["rev-parse", "--verify", &reference], None)?.stdout_str(); + if tip.trim() != created.tip { + return Err(branch_creation_changed(name)); } - if let Some((branch, path)) = branch_of_other_worktree(&String::from_utf8_lossy(&out.stderr)) { - return Err(IdeError::invalid(format!("branch '{branch}' is already checked out in worktree at '{path}'"))); + if let Some(before) = previous_head { + let current = r.branch_info()?; + if current.head.as_deref() != Some(name) + || current.head_commit.as_deref() != Some(created.tip.as_str()) + || current.operation.is_some() + { + return Err(branch_creation_changed(name)); + } + if before.branch.as_deref() == Some(name) { + if created.previous_tip.as_deref() != Some(before.commit.as_str()) { + return Err(branch_creation_changed(name)); + } + return restore_head(r, &before.commit, &created.tip, before.branch.as_deref()); + } + let rev = check_rev(before.branch.as_deref().unwrap_or(&before.commit))?; + if let Some(branch) = &before.branch { + check_local_branch(r, branch)?; + } + let options = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() }; + if !matches!(checkout_with(r, rev, false, &options)?, CheckoutOutcome::Done) { + return Err(IdeError::invalid("Could not check out the previous branch")); + } + } + if let Some(previous) = &created.previous_tip { + if r.worktrees()?.iter().any(|tree| tree.branch.as_deref() == Some(name)) { + return Err(branch_creation_changed(name)); + } + let previous = check_rev(previous)?; + let expected = check_rev(&created.tip)?; + run(r.root(), &["update-ref", "-m", "undo branch creation", &reference, previous, expected], None)?; + Ok(()) + } else { + // Git checks all worktrees and clears the tracking config it may have added. + if run(r.root(), &["rev-parse", "--verify", &reference], None)?.stdout_str().trim() != created.tip { + return Err(branch_creation_changed(name)); + } + delete_branch(r, name, true) } - Err(cli::failure(&args, &out.stderr, &out.stdout, out.code)) } /// Whether `start` is a remote-tracking branch with another name than the new branch @@ -951,111 +1328,88 @@ pub(crate) fn renamed_remote_start(r: &Repo, name: &str, start: &str) -> bool { let full = out.stdout_str().trim().to_string(); let Some(rest) = full.strip_prefix("refs/remotes/").filter(|_| out.code == Some(0)) else { return false }; let Ok(repo) = r.gix() else { return false }; - let names = repo.remote_names(); - let branch = names.iter().find_map(|remote| rest.strip_prefix(&format!("{remote}/"))); - branch.is_some_and(|b| b != name) + remote_branch_name(&repo, rest).is_some_and(|branch| branch != name) } -/// Undo Commit: moves the current branch back to the parent of `commit` (which must be -/// HEAD), keeping its changes staged. Returns the undone commit's message. -/// Edit Commit Message: writes `commit` again with `message`, and its descendants on top -/// of it with their own trees, then moves HEAD to the new tip. Trees don't change, so the -/// index and the working tree stay as they are (local changes included). Returns HEAD -/// before and after, for [`restore_head`]. -pub(crate) fn reword(r: &Repo, commit: &str, message: &str) -> IdeResult<(String, String)> { - if r.branch_info()?.operation.is_some() { - return Err(IdeError::invalid( - "cannot edit a commit message while a merge, rebase or cherry-pick is in progress", - )); - } - let message = message.trim(); - if message.is_empty() { - return Err(IdeError::invalid("commit message is empty")); - } - let (target, head) = { - let repo = r.gix()?; - let head = repo.head_id().map_err(|_| IdeError::invalid("there is no commit to edit"))?.detach(); - let target = repo.find_object(resolve(&repo, commit)?).map_err(gx)?.peel_to_commit().map_err(gx)?.id; - (target.to_string(), head.to_string()) +/// Undo of a history rewrite: moves HEAD from `after` back to `before`, preserving local changes. +pub(crate) fn restore_head(r: &Repo, before: &str, after: &str, branch: Option<&str>) -> IdeResult<()> { + let check = || { + if r.operation()?.is_some() { + return Err(IdeError::invalid("cannot undo while a merge, rebase or cherry-pick is in progress")); + } + let (current, head) = r.head()?; + if head.as_deref() != Some(after) || branch.is_some_and(|expected| current.as_deref() != Some(expected)) { + return Err(IdeError::invalid("the branch has changed since; undo is no longer possible")); + } + Ok(()) }; - if cli::run_raw(r.root(), &["merge-base", "--is-ancestor", &target, &head], None)?.code != Some(0) { - return Err(IdeError::invalid("the commit is not in the current branch")); - } - // target..HEAD must be a straight line on top of the target. - let range = format!("{target}..{head}"); - let listed = run(r.root(), &["rev-list", "--reverse", "--topo-order", "--parents", &range], None)?.stdout_str(); - let mut chain = vec![target.clone()]; - for line in listed.lines() { - let ids: Vec<&str> = line.split_whitespace().collect(); - if ids.len() != 2 || ids[1] != chain.last().unwrap() { - return Err(IdeError::invalid("the commits after this one are not a linear history")); - } - chain.push(ids[0].to_string()); - } - let mut parent: Option = None; - for (i, id) in chain.iter().enumerate() { - let raw = run(r.root(), &["cat-file", "commit", id], None)?.stdout; - let text = String::from_utf8_lossy(&raw); - let (headers, body) = text.split_once("\n\n").unwrap_or((&text, "")); - let mut tree = ""; - let mut parents = Vec::new(); - let mut author = ""; - for line in headers.lines() { - if let Some(v) = line.strip_prefix("tree ") { - tree = v; - } else if let Some(v) = line.strip_prefix("parent ") { - parents.push(v.to_string()); - } else if let Some(v) = line.strip_prefix("author ") { - author = v; - } - } - if parents.len() > 1 { - return Err(IdeError::invalid("merge commits cannot be reworded")); - } - if let Some(p) = &parent { - parents = vec![p.clone()]; - } - let (name, rest) = author.split_once(" <").unwrap_or((author, "")); - let (email, date) = rest.split_once("> ").unwrap_or((rest, "")); - let env = [ - ("GIT_AUTHOR_NAME", std::ffi::OsStr::new(name)), - ("GIT_AUTHOR_EMAIL", std::ffi::OsStr::new(email)), - ("GIT_AUTHOR_DATE", std::ffi::OsStr::new(date)), - ]; - let mut args = vec!["commit-tree", tree]; - for p in &parents { - args.extend(["-p", p.as_str()]); - } - let new_message = if i == 0 { format!("{message}\n") } else { body.to_string() }; - let created = cli::run_env(r.root(), &args, Some(new_message.as_bytes()), &env)?.stdout_str(); - parent = Some(created.trim().to_string()); - } - let new_head = parent.expect("the chain holds the target"); - let reason = format!("reword: {}", message.lines().next().unwrap_or_default()); - run(r.root(), &["update-ref", "-m", &reason, "HEAD", &new_head, &head], None)?; - Ok((head, new_head)) -} - -/// Undo of a history rewrite: moves HEAD from `after` back to `before`, keeping local -/// changes (`git reset --keep`). Refused when HEAD has moved since. -pub(crate) fn restore_head(r: &Repo, before: &str, after: &str) -> IdeResult<()> { - if r.branch_info()?.operation.is_some() { - return Err(IdeError::invalid("cannot undo while a merge, rebase or cherry-pick is in progress")); - } - let head = run(r.root(), &["rev-parse", "--verify", "HEAD"], None)?.stdout_str(); - if head.trim() != after { - return Err(IdeError::invalid("the branch has changed since; undo is no longer possible")); - } + check()?; let before = check_rev(before)?; let tree = |rev: &str| run(r.root(), &["rev-parse", &format!("{rev}^{{tree}}")], None).map(|o| o.stdout_str()); if tree(before)? == tree(after)? { - run(r.root(), &["update-ref", "-m", "undo", "HEAD", before, after], None)?; + let reference = branch.map_or_else(|| "HEAD".to_owned(), |branch| format!("refs/heads/{branch}")); + run(r.root(), &["update-ref", "-m", "undo", &reference, before, after], None)?; } else { - run(r.root(), &["reset", "-q", "--keep", before, "--"], None)?; + // Reset --keep preserves the files on disk but unstages previously staged changes. + crate::preserve::around(r, "Local changes saved before undo", || { + check()?; + run(r.root(), &["reset", "-q", "--keep", before, "--"], None).map(|_| ()) + })?; } Ok(()) } +/// Returns to the original checkout and restores the branch that was rebased. +pub(crate) fn restore_rebase_checkout( + r: &Repo, + before: &str, + after: &str, + branch: &str, + checkout: &HistoryTip, +) -> IdeResult<()> { + let before = check_rev(before)?; + let after = check_rev(after)?; + check_local_branch(r, branch)?; + let reference = format!("refs/heads/{branch}"); + let checkout_commit = check_rev(&checkout.commit)?; + let switch = if let Some(name) = &checkout.branch { + check_local_branch(r, name)?; + if name == branch { + return Err(IdeError::invalid("Cannot restore the checkout to the rebased branch")); + } + vec!["switch", "--no-guess", name.as_str()] + } else { + vec!["switch", "--detach", checkout_commit] + }; + let check = || { + let (current, tip) = r.head()?; + if r.operation()?.is_some() || current.as_deref() != Some(branch) || tip.as_deref() != Some(after) { + return Err(IdeError::invalid("the branch has changed since; undo is no longer possible")); + } + if let Some(name) = &checkout.branch { + let tip = resolve(&r.gix()?, &format!("refs/heads/{name}"))?; + if Some(tip) != gix::ObjectId::from_hex(checkout_commit.as_bytes()).ok() { + return Err(IdeError::invalid("The previous branch has changed since the rebase")); + } + } + Ok(()) + }; + check()?; + crate::preserve::around(r, "Local changes saved before undo", || { + check()?; + // A refused switch leaves both refs untouched. Update the rebased branch by its exact + // name and expected tip after it is no longer checked out. + run(r.root(), &switch, None)?; + if before != after { + if r.worktrees()?.iter().any(|tree| !tree.prunable && tree.branch.as_deref() == Some(branch)) { + return Err(IdeError::invalid("The rebased branch is now checked out")); + } + run(r.root(), &["update-ref", "-m", "undo checkout and rebase", &reference, before, after], None)?; + } + Ok(()) + }) +} + pub(crate) fn undo_commit(r: &Repo, commit: &str) -> IdeResult { if r.branch_info()?.operation.is_some() { return Err(IdeError::invalid("cannot undo a commit while a merge, rebase or cherry-pick is in progress")); @@ -1093,36 +1447,104 @@ pub(crate) fn delete_branch(r: &Repo, branch: &str, force: bool) -> IdeResult<() run(r.root(), &["branch", if force { "-D" } else { "-d" }, "--", branch], None).map(|_| ()) } -/// The short name (`origin/main`) of the branch a local branch tracks, as the branch list shows it. -fn upstream_name(r: &Repo, branch: &str) -> IdeResult> { - let out = run(r.root(), &["for-each-ref", "--format=%(upstream:short)", &format!("refs/heads/{branch}")], None)?; - let upstream = out.stdout_str().trim().to_string(); - Ok((!upstream.is_empty()).then_some(upstream)) -} - -pub(crate) fn delete_branch_restorable(r: &Repo, branch: &str) -> IdeResult { +fn branch_deletion_receipt(r: &Repo, branch: &str) -> IdeResult<(DeletedBranch, Option)> { check_local_branch(r, branch)?; let tip = run(r.root(), &["rev-parse", "--verify", "-q", &format!("refs/heads/{branch}^{{commit}}")], None)? .stdout_str() .trim() .to_string(); - let upstream = upstream_name(r, branch)?; + let out = run( + r.root(), + &[ + "for-each-ref", + "--format=%(upstream:short)%09%(upstream)%09%(upstream:remotename)%09%(upstream:remoteref)", + &format!("refs/heads/{branch}"), + ], + None, + )?; + let output = out.stdout_str(); + let mut fields = output.trim_end_matches(['\r', '\n']).split('\t'); + let upstream = fields.next().filter(|name| !name.is_empty()).map(str::to_owned); + let full_ref = fields.next().filter(|name| !name.is_empty()).map(str::to_owned); + let remote = fields.next().filter(|name| !name.is_empty() && *name != "."); + let remote_branch = fields.next().and_then(|name| name.strip_prefix("refs/heads/")); + let remote_upstream = remote + .zip(remote_branch) + .map(|(remote, branch)| UpstreamTracking { remote: remote.to_owned(), branch: branch.to_owned() }); + Ok(( + DeletedBranch { name: branch.to_owned(), tip, upstream, remote_upstream, unmerged_base: None, unmerged: false }, + full_ref, + )) +} + +pub(crate) fn delete_branch_restorable( + r: &Repo, + branch: &str, + expected: Option<(&str, &str)>, +) -> IdeResult { + let (mut deleted, upstream_ref) = branch_deletion_receipt(r, branch)?; + if let Some((tip, upstream)) = expected + && (deleted.tip != tip + || deleted + .remote_upstream + .as_ref() + .is_none_or(|tracking| format!("{}/{}", tracking.remote, tracking.branch) != upstream)) + { + return Err(IdeError::invalid(format!("Tracking branch '{branch}' changed before it could be deleted"))); + } let out = cli::run_raw(r.root(), &["branch", "-d", "--", branch], None)?; - let unmerged = match out.code { + deleted.unmerged = match out.code { Some(0) => false, _ if String::from_utf8_lossy(&out.stderr).contains("not fully merged") => { + let repo = r.gix()?; + deleted.unmerged_base = upstream_ref + .as_deref() + .and_then(|upstream| resolve(&repo, upstream).ok()) + .or_else(|| repo.head_id().ok().map(|id| id.detach())) + .map(|id| id.to_string()); run(r.root(), &["branch", "-D", "--", branch], None)?; true } code => return Err(cli::failure(&["branch"], &out.stderr, &out.stdout, code)), }; - Ok(DeletedBranch { name: branch.to_string(), tip, upstream, unmerged }) + Ok(deleted) +} + +pub(crate) fn delete_merged_branch(r: &Repo, branch: &str, expected_tip: &str) -> IdeResult { + let (deleted, _) = branch_deletion_receipt(r, branch)?; + if deleted.tip != expected_tip { + return Err(IdeError::invalid(format!("Branch '{branch}' changed since the merge"))); + } + // ':' cannot name a remote. With no upstream, Git checks HEAD for reachability + // and still refuses to delete branches in use by any worktree. + // The environment form accepts '=' in a branch name, which '-c key=value' splits. + let index = std::env::var("GIT_CONFIG_COUNT").ok().and_then(|count| count.parse::().ok()).unwrap_or(0); + let key = format!("branch.{branch}.remote"); + let count = index.saturating_add(1).to_string(); + cli::run_env( + r.root(), + &["branch", "-d", "--", branch], + None, + &[ + ("GIT_CONFIG_COUNT", count.as_ref()), + (&format!("GIT_CONFIG_KEY_{index}"), key.as_ref()), + (&format!("GIT_CONFIG_VALUE_{index}"), ":".as_ref()), + ], + )?; + Ok(deleted) } pub(crate) fn restore_branch(r: &Repo, deleted: &DeletedBranch) -> IdeResult<()> { let tip = check_rev(&deleted.tip)?; run(r.root(), &["branch", "--", &deleted.name, tip], None)?; - if let Some(upstream) = &deleted.upstream { + if let Some(tracking) = &deleted.remote_upstream { + // Keep the configured upstream even if its remote-tracking ref was pruned. + let remote_key = format!("branch.{}.remote", deleted.name); + let merge_key = format!("branch.{}.merge", deleted.name); + let merge = format!("refs/heads/{}", tracking.branch); + run(r.root(), &["config", "--local", "--replace-all", "--", &remote_key, &tracking.remote], None)?; + run(r.root(), &["config", "--local", "--replace-all", "--", &merge_key, &merge], None)?; + } else if let Some(upstream) = &deleted.upstream { let target = format!("--set-upstream-to={upstream}"); run(r.root(), &["branch", &target, "--", &deleted.name], None)?; } @@ -1135,14 +1557,23 @@ pub(crate) fn rename_branch(r: &Repo, from: &str, to: &str, unset_upstream: bool if to.is_empty() { return Err(IdeError::invalid("branch name is empty")); } - let has_upstream = unset_upstream && upstream_name(r, from)?.is_some(); - run(r.root(), &["branch", "-m", "--", from, to], None)?; - if has_upstream { - run(r.root(), &["branch", "--unset-upstream", "--", to], None).map_err(|mut error| { - error.message = - format!("Renamed branch '{from}' to '{to}', but could not unset its upstream: {}", error.message); - error - })?; + if from == to { + check_local_branch(r, from)?; + } else { + run(r.root(), &["branch", "-m", "--", from, to], None)?; + } + if unset_upstream { + let args = ["branch", "--unset-upstream", "--", to]; + let out = cli::run_raw(r.root(), &args, None)?; + let no_upstream = format!("fatal: branch '{to}' has no upstream information"); + if out.code != Some(0) && !String::from_utf8_lossy(&out.stderr).lines().any(|line| line == no_upstream) { + let mut error = cli::failure(&args, &out.stderr, &out.stdout, out.code); + if from != to { + error.message = + format!("Renamed branch '{from}' to '{to}', but could not unset its upstream: {}", error.message); + } + return Err(error); + } } Ok(()) } @@ -1158,7 +1589,7 @@ fn check_rev(rev: &str) -> IdeResult<&str> { /// The short name of a full branch ref (`refs/heads/x`, `refs/remotes/origin/x`) when it /// names that same branch: git writes the name it is given into the merge message and the /// reflog. A name a tag shares stays a full ref, the case IDEA also passes in full. -fn unambiguous_branch_name<'a>(r: &Repo, rev: &'a str) -> &'a str { +pub(crate) fn unambiguous_branch_name<'a>(r: &Repo, rev: &'a str) -> &'a str { let Some(short) = rev.strip_prefix("refs/heads/").or_else(|| rev.strip_prefix("refs/remotes/")) else { return rev; }; @@ -1178,6 +1609,76 @@ pub(crate) fn merge(r: &Repo, branch: &str) -> IdeResult<()> { }) } +pub(crate) fn merge_attempt(r: &Repo, args: &[&str], options: &MergeOptions, smart: bool) -> IdeResult { + let attempt = || { + let out = cli::run_raw(r.root(), args, None)?; + let stdout = out.stdout_str(); + let stderr = String::from_utf8_lossy(&out.stderr); + let conflicts = stdout + .lines() + .chain(stderr.lines()) + .any(|line| line.starts_with("CONFLICT (") || line.contains("Applying autostash resulted in conflicts")); + if conflicts && !unmerged_paths(r)?.is_empty() { + return Ok(MergeOutcome::Conflicts); + } + if out.code == Some(0) { + if stdout.lines().chain(stderr.lines()).any(|line| { + matches!( + line.trim_end_matches('.'), + "Already up to date" | "Already up-to-date" | "Already up to date. (nothing to squash)" + ) + }) { + return Ok(MergeOutcome::AlreadyUpToDate); + } + if options.squash { + return Ok(MergeOutcome::Squashed); + } + if options.no_commit && r.operation()?.as_deref() == Some("merge") { + return Ok(MergeOutcome::ReadyToCommit); + } + return Ok(MergeOutcome::Done); + } + if let Some(files) = merge_overwritten_files(r, &stderr)? { + return Ok(MergeOutcome::LocalChanges { files }); + } + Err(cli::failure(args, &out.stderr, &out.stdout, out.code)) + }; + if !smart { + return attempt(); + } + crate::preserve::save(r, "Local changes saved before merge")?; + let result = attempt(); + if matches!(result, Ok(MergeOutcome::Conflicts)) { + return result; + } + let restored = crate::preserve::restore(r); + let value = result?; + if let Err(error) = restored { + if !unmerged_paths(r)?.is_empty() { + return Ok(MergeOutcome::Conflicts); + } + return Err(error); + } + Ok(value) +} + +fn merge_overwritten_files(r: &Repo, stderr: &str) -> IdeResult>> { + const HEADER: &str = "local changes to the following files would be overwritten by merge"; + let mut files = listed_files(stderr, HEADER).unwrap_or_default(); + // The three-way strategy prints an undelimited list of staged paths, some of which may contain spaces. + if stderr + .lines() + .zip(stderr.lines().skip(1)) + .any(|(header, line)| header.contains(HEADER) && line.starts_with(" ")) + { + let staged = run(r.root(), &["diff", "--cached", "--name-only", "-z", "--no-renames", "--"], None)?; + files.extend(staged.stdout_str().split_terminator('\0').map(ToOwned::to_owned)); + files.sort_unstable(); + files.dedup(); + } + Ok((!files.is_empty()).then_some(files)) +} + pub(crate) fn rebase(r: &Repo, onto: &str) -> IdeResult<()> { let onto = unambiguous_branch_name(r, check_rev(onto)?); crate::preserve::around(r, "Local changes saved before rebase", || { @@ -1185,6 +1686,118 @@ pub(crate) fn rebase(r: &Repo, onto: &str) -> IdeResult<()> { }) } +pub(crate) fn rebase_branch( + r: &Repo, + plan: &BranchRebasePlan, + cancel: &CancellationToken, + out: &dyn Fn(String), +) -> IdeResult { + let target = check_rev(&plan.target)?; + let check = || { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + if r.operation()?.is_some() || !unmerged_paths(r)?.is_empty() { + return Err(IdeError::invalid("finish the Git operation or resolve the conflicts before rebasing")); + } + let (branch, commit) = r.head()?; + if branch.is_none() || branch != plan.head.branch || commit.as_deref() != Some(plan.head.commit.as_str()) { + return Err(IdeError::invalid("The current branch changed before rebase")); + } + if Some(resolve(&r.gix()?, target)?) != gix::ObjectId::from_hex(plan.onto.as_bytes()).ok() { + return Err(IdeError::invalid("The target branch changed before rebase")); + } + Ok(()) + }; + check()?; + crate::preserve::around(r, "Local changes saved before rebase", || { + check()?; + cli::run_streaming(r.root(), &["rebase", unambiguous_branch_name(r, target)], cancel, out)?; + completed_rebase(r, plan.head.branch.as_deref()) + }) +} + +fn completed_rebase(r: &Repo, expected: Option<&str>) -> IdeResult { + if r.operation()?.as_deref() == Some("rebase") { + return Err(IdeError::invalid("Rebase paused")); + } + let (branch, commit) = r.head()?; + if branch.as_deref() == expected + && let Some(commit) = commit + { + return Ok(HistoryTip { branch, commit }); + } + Err(IdeError::invalid("The current branch changed during rebase")) +} + +pub(crate) fn checkout_rebase( + r: &Repo, + plan: &CheckoutRebasePlan, + cancel: &CancellationToken, + out: &dyn Fn(String), +) -> IdeResult { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let branch = check_rev(&plan.branch)?; + run(r.root(), &["check-ref-format", &format!("refs/heads/{branch}")], None)?; + if plan.base.branch.as_deref() == Some(branch) { + return Err(IdeError::invalid("check out another branch to rebase it onto the current branch")); + } + if r.operation()?.is_some() || !unmerged_paths(r)?.is_empty() { + return Err(IdeError::invalid("finish the Git operation or resolve the conflicts before rebasing")); + } + if let Some(tree) = r.worktrees()?.into_iter().find(|tree| tree.branch.as_deref() == Some(branch) && !tree.prunable) + { + return Err(IdeError::invalid(format!("branch '{branch}' is checked out at {}", tree.path.0.display()))); + } + + check_checkout_rebase_refs(r, plan, branch)?; + crate::preserve::around(r, "Local changes saved before rebase", || { + check_checkout_rebase_refs(r, plan, branch)?; + if let Some(remote) = &plan.remote + && (plan.branch_tip.is_none() || remote.drop_local_commits) + { + let start = format!("refs/remotes/{}", remote.name); + let create = if plan.branch_tip.is_some() { "-C" } else { "-c" }; + cli::run_streaming(r.root(), &["switch", create, branch, &start], cancel, out)?; + cli::run_streaming(r.root(), &["rebase", &plan.base.commit], cancel, out)?; + } else { + cli::run_streaming(r.root(), &["rebase", &plan.base.commit, branch], cancel, out)?; + } + completed_rebase(r, Some(branch)) + }) +} + +fn check_checkout_rebase_refs(r: &Repo, plan: &CheckoutRebasePlan, branch: &str) -> IdeResult<()> { + let repo = r.gix()?; + let (head, oid) = crate::refs::head(&repo)?; + let changed = || IdeError::invalid("a branch changed since checkout and rebase was requested; try again"); + if head != plan.base.branch || oid.as_deref() != Some(plan.base.commit.as_str()) { + return Err(changed()); + } + let mut local = repo.try_find_reference(format!("refs/heads/{branch}").as_str()).map_err(gx)?; + let local_tip = + local.as_mut().map(|reference| reference.peel_to_id().map(|id| id.to_string())).transpose().map_err(gx)?; + if local_tip != plan.branch_tip { + return Err(changed()); + } + let Some(remote) = &plan.remote else { + return local_tip.map(|_| ()).ok_or_else(changed); + }; + let mut tracking = + repo.try_find_reference(format!("refs/remotes/{}", remote.name).as_str()).map_err(gx)?.ok_or_else(changed)?; + if gix::ObjectId::from_hex(remote.commit.as_bytes()).ok() != Some(tracking.peel_to_id().map_err(gx)?.detach()) { + return Err(changed()); + } + if let Some(local) = local + && crate::refs::upstream_of(&repo, local.name()).is_some_and(|(upstream, _)| upstream != remote.name) + { + return Err(IdeError::invalid(format!("branch '{branch}' tracks a different remote branch"))); + } + Ok(()) +} + pub(crate) fn stash_push( r: &Repo, message: Option<&str>, @@ -1213,17 +1826,21 @@ pub(crate) fn stash_push( run(r.root(), &args, None).map(|_| ()) } -pub(crate) fn stash_apply(r: &Repo, index: u32, pop: bool, reinstate_index: bool) -> IdeResult<()> { - let spec = format!("stash@{{{index}}}"); +pub(crate) fn stash_apply( + r: &Repo, + spec: &str, + pop: bool, + reinstate_index: bool, +) -> IdeResult { let mut args = vec!["stash", if pop { "pop" } else { "apply" }, "-q"]; if reinstate_index { args.push("--index"); } - args.push(&spec); - run(r.root(), &args, None).map(|_| ()) + args.push(spec); + crate::conflict_resolution::run_manual_unstash(r, &args) } -pub(crate) fn stash_branch(r: &Repo, index: u32, branch: &str) -> IdeResult<()> { +pub(crate) fn stash_branch(r: &Repo, spec: &str, branch: &str) -> IdeResult { let branch = branch.trim(); let valid = !branch.is_empty() && !branch.starts_with('-') @@ -1231,8 +1848,7 @@ pub(crate) fn stash_branch(r: &Repo, index: u32, branch: &str) -> IdeResult<()> if !valid { return Err(IdeError::invalid(format!("'{branch}' is not a valid branch name"))); } - let spec = format!("stash@{{{index}}}"); - run(r.root(), &["stash", "branch", branch, &spec], None).map(|_| ()) + crate::conflict_resolution::run_manual_unstash(r, &["stash", "branch", branch, spec]) } pub(crate) fn stash_drop(r: &Repo, index: u32) -> IdeResult<()> { @@ -1240,6 +1856,73 @@ pub(crate) fn stash_drop(r: &Repo, index: u32) -> IdeResult<()> { run(r.root(), &["stash", "drop", "-q", &spec], None).map(|_| ()) } +/// Linked worktrees have different indexes but share this stash reflog. +pub(crate) fn lock_stashes(r: &Repo) -> IdeResult { + let [_, common_dir] = r.metadata_dirs()?; + let lock = std::fs::File::options() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(common_dir.join("openidea-stash.lock"))?; + lock.lock()?; + Ok(lock) +} + +pub(crate) fn selected_stash_index(r: &Repo, selected: &crate::Stash) -> IdeResult> { + let entries = r.stashes()?; + let mut matching = entries.iter().filter(|entry| entry.same_entry(selected)).map(|entry| entry.index); + let index = matching.next(); + if matching.next().is_some() { + return Err(IdeError::invalid("The selected stash is ambiguous because the stash list changed")); + } + Ok(index) +} + +fn require_stash_index(r: &Repo, stash: &crate::Stash) -> IdeResult { + selected_stash_index(r, stash)?.ok_or_else(|| IdeError::invalid("The selected stash is no longer available")) +} + +pub(crate) fn drop_selected_stash(r: &Repo, stash: &crate::Stash) -> IdeResult { + let _stash_lock = lock_stashes(r)?; + let index = require_stash_index(r, stash)?; + stash_drop(r, index)?; + Ok(index) +} + +pub(crate) fn drop_restored_stash(r: &Repo, stash: &crate::Stash) -> IdeResult<()> { + let drop_entry = || { + if let Some(index) = selected_stash_index(r, stash)? { + stash_drop(r, index)?; + } + Ok::<_, IdeError>(()) + }; + drop_entry().map_err(|error| { + IdeError::invalid(format!("Stash changes were restored, but the stash entry could not be dropped: {error}")) + }) +} + +pub(crate) fn unstash_selected( + r: &Repo, + stash: &crate::Stash, + pop: bool, + reinstate_index: bool, + branch: Option<&str>, +) -> IdeResult { + let _stash_lock = lock_stashes(r)?; + let index = require_stash_index(r, stash)?; + // Git resolves an index again when a pop finishes. Use the saved commit for the + // restore, then look up the entry again before removing it. + let outcome = match branch { + Some(name) => stash_branch(r, &stash.id, name), + None => stash_apply(r, &stash.id, false, reinstate_index), + }?; + if outcome == crate::StashApplyOutcome::Done && (pop || branch.is_some()) { + drop_restored_stash(r, stash)?; + } + Ok(crate::StashApplyResult { index, outcome }) +} + pub(crate) fn delete_remote_branch( r: &Repo, branch: &str, @@ -1257,7 +1940,17 @@ pub(crate) fn delete_remote_branch( if name.is_empty() || name.starts_with('-') || name == "HEAD" { return Err(IdeError::invalid(format!("invalid remote branch '{branch}'"))); } - cli::run_streaming(r.root(), &["push", "--progress", remote, "--delete", name], cancel, on_output) + let reference = format!("refs/heads/{name}"); + let missing = format!("error: unable to delete '{reference}': remote ref does not exist"); + let result = + cli::run_streaming(r.root(), &["push", "--progress", "--delete", "--", remote, &reference], cancel, on_output); + match result { + Err(error) if error.message.lines().any(|line| line == missing) => { + // Another repository may have just deleted the branch from the same remote. + cli::run_streaming(r.root(), &["remote", "prune", "--", remote], cancel, on_output) + } + result => result, + } } pub(crate) fn push( @@ -1265,13 +1958,13 @@ pub(crate) fn push( o: crate::PushOptions, cancel: &CancellationToken, on_output: &dyn Fn(String), -) -> IdeResult<()> { - let mut args: Vec = vec!["push".into(), "--progress".into()]; +) -> IdeResult { + let mut args: Vec = vec!["push".into(), "--progress".into(), "--porcelain".into()]; args.extend(force_args(o.force, o.force_with_lease, o.no_verify)); - if o.tags == Some(crate::PushTags::CurrentBranch) { + if o.tags == Some(PushTags::CurrentBranch) { args.push("--follow-tags".into()); } - if o.set_upstream { + let remote = if o.set_upstream { let repo = r.gix()?; let head = repo.head_name().map_err(gx)?.ok_or_else(|| IdeError::invalid("cannot set upstream: HEAD is detached"))?; @@ -1288,21 +1981,250 @@ pub(crate) fn push( } }) .ok_or_else(|| IdeError::invalid("no remote configured"))?; - args.extend(["--set-upstream".into(), remote, short]); - } else if let Some((remote, target)) = renamed_upstream(r)? { - args.extend([remote, format!("HEAD:{target}")]); - } + args.extend(["--set-upstream".into(), remote.clone(), short]); + Some(remote) + } else if let Some((upstream_remote, target)) = renamed_upstream(r)? { + args.extend([upstream_remote.clone(), format!("HEAD:{target}")]); + Some(upstream_remote) + } else if !o.force && !o.force_with_lease { + push_remote(r).ok() + } else { + None + }; let argv: Vec<&str> = args.iter().map(String::as_str).collect(); - cli::run_streaming(r.root(), &argv, cancel, on_output)?; - if o.tags == Some(crate::PushTags::All) { - // `git push --tags` alone pushes only tags, so it runs after the branch push. - let remote = push_remote(r)?; - let mut args = vec!["push", "--progress"]; - if o.no_verify { + let mut report = PushReport::new(remote.clone().or_else(|| push_remote(r).ok())); + if let Err(mut error) = push_report::run(&mut report, r.root(), &argv, cancel, on_output) { + if !o.force + && !o.force_with_lease + && let Some(rejection) = + remote.as_deref().and_then(|remote| tracked_push_rejection(r, remote, &error, cancel)) + { + error.data = Some(rejection); + } + return Err(error); + } + push_all_tags(&mut report, r, o.tags, o.no_verify, cancel, on_output)?; + Ok(report) +} + +fn tracked_push_rejection(r: &Repo, remote: &str, error: &IdeError, cancel: &CancellationToken) -> Option { + let report = match &error.data { + // A previous push URL may have accepted the branch itself. In that case the + // result needs review instead of an automatic update and retry. + Some(ErrorData::PushPartiallyApplied { report }) + if report + .refs + .iter() + .all(|r| r.status == PushRefStatus::UpToDate || r.reference.starts_with("refs/tags/")) => + { + Some(report) + } + None => None, + _ => return None, + }; + let mut rejected = error.message.lines().filter_map(|line| line.strip_prefix("!\t")); + let (refs, reason) = rejected.next()?.split_once('\t')?; + let known = reason == "[rejected] (non-fast-forward)"; + if (!known && reason != "[rejected] (fetch first)") || rejected.next().is_some() { + return None; + } + let (source_ref, target_ref) = refs.split_once(':')?; + let target = target_ref.strip_prefix("refs/heads/")?; + let repo = r.gix().ok()?; + let head = repo.head_name().ok()??; + let head_ref = head.as_bstr().to_str_lossy(); + if source_ref != head_ref && source_ref != "HEAD" { + return None; + } + let source = head.as_ref().shorten().to_str_lossy().into_owned(); + if branch_upstream(r, &source)? != (remote.to_owned(), target.to_owned()) { + return None; + } + let tracking = crate::refs::upstream_of(&repo, head.as_ref()); + let divergence = tracking + .as_ref() + .filter(|_| known) + .and_then(|(_, tip)| push_divergence(r, &repo, &source, remote, target, *tip, cancel)) + .map(Box::new); + let upstream = tracking.map_or_else(|| format!("{remote}/{target}"), |(name, _)| name); + Some(ErrorData::PushRejected { source, upstream, divergence, report: report.cloned() }) +} + +pub(crate) fn push_selected( + r: &Repo, + selection: &crate::PushSelection, + inspected: Option<&crate::PushInspection>, + options: crate::PushOptions, + cancel: &CancellationToken, + out: &dyn Fn(String), +) -> IdeResult { + let (source_ref, target, tip) = selection.refs(r, cancel)?; + let urls = crate::ops::remote_push_urls(r, &selection.remote, cancel)?; + let mut args = vec!["push".to_string(), "--progress".into(), "--porcelain".into()]; + let mut pinned = false; + if inspected.is_some_and(|review| review.local_tip != tip) { + return Err(IdeError::invalid( + "Push source or destination changed. Open Push again to review the current branches.", + )); + } + let expected = if options.force_with_lease { inspected } else { None }; + if let Some(expected) = expected { + if expected.state == crate::PushTargetState::FetchRequired { + return Err(IdeError::invalid("Fetch the remote commits before force pushing.")); + } + if let Some(remote_tip) = expected.remote_tip.as_ref() { + if urls.len() != 1 + || (!remote_tip.is_empty() + && (remote_tip.len() != tip.len() || !remote_tip.bytes().all(|b| b.is_ascii_hexdigit()))) + { + return Err(IdeError::invalid( + "Push source or destination changed. Open Push again to review the current branches.", + )); + } + args.push(format!("--force-with-lease={target}:{remote_tip}")); + pinned = true; + } + } + if !pinned + && !options.force + && selection.branch.is_none() + && inspected.is_some_and(|review| review.remote_checked && review.remote_tip.as_deref() == Some("")) + { + // This destination was shown as a new branch. Refuse a concurrent creation. + args.push(format!("--force-with-lease={target}:")); + pinned = true; + } + let force = options.force && !pinned; + if options.force_with_lease && !pinned && !force { + args.push(format!("--force-with-lease={target}")); + } + if options.no_verify { + args.push("--no-verify".into()); + } + let set_upstream = + options.set_upstream && source_ref.is_some() && selection.revision.is_none() && !selection.special_ref; + if set_upstream { + args.push("--set-upstream".into()); + } + if let Some(tags) = options.tags { + args.push(push_tags_arg(tags).into()); + } + let source = if selection.revision.is_some() || (pinned && !set_upstream) { + tip.as_str() + } else { + source_ref.as_deref().unwrap_or(&tip) + }; + // Force applies to the selected destination only, even when tags travel with it. + let prefix = if force { "+" } else { "" }; + args.extend(["--".into(), selection.remote.clone(), format!("{prefix}{source}:{target}")]); + let argv: Vec<&str> = args.iter().map(String::as_str).collect(); + let mut report = PushReport::new(Some(selection.remote.clone())); + if let Err(mut error) = push_report::run(&mut report, r.root(), &argv, cancel, out) { + if !options.force + && !options.force_with_lease + && selection.revision.is_none() + && let Some(rejection) = tracked_push_rejection(r, &selection.remote, &error, cancel) + { + error.data = Some(rejection); + } + return Err(error); + } + Ok(report) +} + +fn push_divergence( + r: &Repo, + repo: &gix::Repository, + source: &str, + remote: &str, + target: &str, + tip: gix::ObjectId, + cancel: &CancellationToken, +) -> Option { + if crate::ops::remote_push_urls(r, remote, cancel).ok()?.len() != 1 { + return None; + } + let local_tip = repo.head_id().ok()?.to_string(); + let remote_tip = tip.to_string(); + let range = format!("{local_tip}...{remote_tip}"); + let counts = cli::run_cancellable(r.root(), &["rev-list", "--left-right", "--count", &range], cancel).ok()?; + let counts = counts.stdout_str(); + let (local, incoming) = counts.trim().split_once('\t')?; + let remote_commits: u32 = incoming.parse().ok()?; + (local.parse::().ok()? > 0 && remote_commits > 0).then(|| PushDivergence { + source: source.to_owned(), + remote: remote.to_owned(), + target: target.to_owned(), + local_tip, + remote_tip, + remote_commits, + }) +} + +pub(crate) fn force_push_rejected( + r: &Repo, + divergence: &PushDivergence, + tags: Option, + no_verify: bool, + cancel: &CancellationToken, + on_output: &dyn Fn(String), +) -> IdeResult { + let PushDivergence { source, remote, target, local_tip, remote_tip, .. } = divergence; + let (head, tip) = r.head()?; + if head.as_ref() != Some(source) + || tip.as_ref() != Some(local_tip) + || branch_upstream(r, source).as_ref() != Some(&(remote.clone(), target.clone())) + || crate::ops::remote_push_urls(r, remote, cancel)?.len() != 1 + || remote_tip.len() != local_tip.len() + || !remote_tip.bytes().all(|byte| byte.is_ascii_hexdigit()) + { + return Err(IdeError::invalid( + "Push source or destination changed. Open Push again to review the current branches.", + )); + } + let target = format!("refs/heads/{target}"); + let lease = format!("--force-with-lease={target}:{remote_tip}"); + let refspec = format!("{local_tip}:{target}"); + let mut args = vec!["push", "--progress", "--porcelain", &lease]; + if no_verify { + args.push("--no-verify"); + } + if let Some(tags) = tags { + args.push(push_tags_arg(tags)); + } + args.extend(["--", remote, &refspec]); + let mut report = PushReport::new(Some(remote.clone())); + push_report::run(&mut report, r.root(), &args, cancel, on_output)?; + Ok(report) +} + +fn push_tags_arg(tags: PushTags) -> &'static str { + match tags { + PushTags::All => "--tags", + PushTags::CurrentBranch => "--follow-tags", + } +} + +fn push_all_tags( + report: &mut PushReport, + r: &Repo, + tags: Option, + no_verify: bool, + cancel: &CancellationToken, + on_output: &dyn Fn(String), +) -> IdeResult<()> { + if tags == Some(PushTags::All) { + let remote = report + .remote + .clone() + .map_or_else(|| push_remote(r), Ok) + .map_err(|e| push_report::with_partial_push(e, report))?; + let mut args = vec!["push", "--progress", "--porcelain"]; + if no_verify { args.push("--no-verify"); } - args.extend([remote.as_str(), "--tags"]); - cli::run_streaming(r.root(), &args, cancel, on_output)?; + args.extend(["--tags", "--", remote.as_str()]); + push_report::run(report, r.root(), &args, cancel, on_output)?; } Ok(()) } @@ -1338,7 +2260,7 @@ pub(crate) fn has_hook(r: &Repo, name: &str) -> IdeResult { } /// Remote and branch name a local branch pulls from (`branch..remote` / `.merge`). -fn branch_upstream(r: &Repo, branch: &str) -> Option<(String, String)> { +pub(crate) fn branch_upstream(r: &Repo, branch: &str) -> Option<(String, String)> { let get = |key: &str| { let out = cli::run_raw(r.root(), &["config", "--get", key], None).ok()?; let v = out.stdout_str().trim().to_string(); @@ -1357,6 +2279,14 @@ fn check_local_branch(r: &Repo, branch: &str) -> IdeResult<()> { .map_err(|_| IdeError::invalid(format!("'{branch}' is not a local branch"))) } +pub(crate) fn require_checked_out_branch(root: &Path, branch: &str, cancel: &CancellationToken) -> IdeResult<()> { + let actual = cli::run_cancellable_raw(root, &["symbolic-ref", "-q", "HEAD"], cancel)?; + if actual.stdout_str().trim().strip_prefix("refs/heads/") == Some(branch) { + return Ok(()); + } + Err(IdeError::invalid(format!("Branch '{branch}' is no longer checked out"))) +} + /// Pushes local `branch` (or only up to `opts.revision`) to its upstream; a branch /// without one goes to the default remote under the same name and, when pushed whole, /// gets it as upstream. @@ -1366,7 +2296,7 @@ pub(crate) fn push_branch( opts: PushBranchOptions<'_>, cancel: &CancellationToken, on_output: &dyn Fn(String), -) -> IdeResult<()> { +) -> IdeResult { let PushBranchOptions { revision, target, @@ -1398,41 +2328,39 @@ pub(crate) fn push_branch( Some(rev) => check_rev(rev)?.to_string(), None => format!("refs/heads/{branch}"), }; - let mut args: Vec = vec!["push".into(), "--progress".into()]; + let mut args: Vec = vec!["push".into(), "--progress".into(), "--porcelain".into()]; args.extend(force_args(force, force_with_lease, no_verify)); if untracked || (set_upstream && revision.is_none()) { args.push("--set-upstream".into()); } - args.extend([remote, format!("{source}:refs/heads/{target}")]); + let mut report = PushReport::new(Some(remote.clone())); + args.extend(["--".into(), remote, format!("{source}:refs/heads/{target}")]); let argv: Vec<&str> = args.iter().map(String::as_str).collect(); - cli::run_streaming(r.root(), &argv, cancel, on_output) + push_report::run(&mut report, r.root(), &argv, cancel, on_output)?; + Ok(report) } -/// Update Selected (IDEA's Git.Update.Selected): fetches the remote of each branch once, -/// then fast-forwards the branch to its tracked branch: the checked-out one with -/// `merge --ff-only`, the others with a local fetch, which refuses branches checked out -/// in another worktree. Diverged branches are left alone. +/// Fetches each remote once, then fast-forwards ref-only branches and checked-out worktrees. pub(crate) fn update_branches( r: &Repo, branches: &[String], + tags: FetchTagsMode, cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult> { - let head = - run(r.root(), &["symbolic-ref", "-q", "--short", "HEAD"], None).ok().map(|o| o.stdout_str().trim().to_string()); let mut fetched: Vec<(String, Result<(), String>)> = Vec::new(); let mut out = Vec::with_capacity(branches.len()); for branch in branches { check_local_branch(r, branch)?; - let result = |status, message| BranchUpdate { branch: branch.clone(), status, message }; + let result = |status, message, worktree| BranchUpdate { branch: branch.clone(), status, message, worktree }; let Some((remote, _)) = branch_upstream(r, branch) else { - out.push(result(BranchUpdateStatus::NoUpstream, None)); + out.push(result(BranchUpdateStatus::NoUpstream, None, None)); continue; }; let fetch = match fetched.iter().find(|(name, _)| *name == remote) { Some((_, done)) => done.clone(), None => { - let done = match cli::run_streaming(r.root(), &["fetch", "--progress", &remote], cancel, on_output) { + let done = match fetch_for_update(r, &remote, tags, cancel, on_output) { Err(e) if e.kind == ErrorKind::Cancelled => return Err(e), done => done.map_err(|e| e.message), }; @@ -1440,11 +2368,15 @@ pub(crate) fn update_branches( done } }; - let (status, message) = match fetch { - Err(message) => (BranchUpdateStatus::Failed, Some(message)), - Ok(()) => fast_forward(r, branch, head.as_deref() == Some(branch.as_str()), cancel, on_output)?, + let (status, message, worktree) = match fetch { + Err(message) => (BranchUpdateStatus::Failed, Some(message), None), + Ok(()) => match fast_forward(r, branch, cancel, on_output) { + Ok(result) => result, + Err(error) if error.kind == ErrorKind::Cancelled => return Err(error), + Err(error) => (BranchUpdateStatus::Failed, Some(error.message), None), + }, }; - out.push(result(status, message)); + out.push(result(status, message, worktree)); } Ok(out) } @@ -1452,10 +2384,9 @@ pub(crate) fn update_branches( fn fast_forward( r: &Repo, branch: &str, - current: bool, cancel: &CancellationToken, on_output: &dyn Fn(String), -) -> IdeResult<(BranchUpdateStatus, Option)> { +) -> IdeResult<(BranchUpdateStatus, Option, Option)> { let rev = |args: &[&str]| run(r.root(), args, None).ok().map(|o| o.stdout_str().trim().to_string()); let ancestor = |a: &str, b: &str| { cli::run_raw(r.root(), &["merge-base", "--is-ancestor", a, b], None).is_ok_and(|o| o.code == Some(0)) @@ -1466,27 +2397,64 @@ fn fast_forward( let target = tracked.as_deref().and_then(|t| rev(&["rev-parse", "-q", "--verify", &format!("{t}^{{commit}}")])); let (Some(tracked), Some(target), Some(tip)) = (tracked, target, rev(&["rev-parse", "-q", "--verify", &local])) else { - return Ok((BranchUpdateStatus::Failed, Some(format!("the tracked branch of '{branch}' was not found")))); + return Ok((BranchUpdateStatus::Failed, Some(format!("the tracked branch of '{branch}' was not found")), None)); }; if tip == target || ancestor(&target, &tip) { - return Ok((BranchUpdateStatus::UpToDate, None)); + return Ok((BranchUpdateStatus::UpToDate, None, None)); } if !ancestor(&tip, &target) { - return Ok((BranchUpdateStatus::NotFastForward, None)); + return Ok((BranchUpdateStatus::NotFastForward, None, None)); } - let refspec = format!("{tracked}:{local}"); - let args: &[&str] = if current { &["merge", "--ff-only", &tracked] } else { &["fetch", ".", &refspec] }; - match cli::run_streaming(r.root(), args, cancel, on_output) { - Ok(()) => Ok((BranchUpdateStatus::Updated, None)), + + let mut holders = r.worktrees()?.into_iter().filter(|worktree| worktree.branch.as_deref() == Some(branch)); + let holder = holders.next(); + if holders.next().is_some() { + return Err(IdeError::invalid(format!("Branch '{branch}' is checked out in more than one worktree"))); + } + let mut linked = None; + if let Some(worktree) = holder.as_ref().filter(|worktree| worktree.prunable) { + return Err(IdeError::invalid(format!( + "Branch '{branch}' is checked out in a missing worktree at '{}'. Prune the worktree first.", + worktree.path.0.display() + ))); + } + let updated = if let Some(worktree) = holder { + let path = &worktree.path.0; + let canonical = dunce::canonicalize(path)?; + if canonical != dunce::canonicalize(r.root())? { + let tree = gix::discover(path).map_err(gx)?; + if tree.workdir().and_then(|root| dunce::canonicalize(root).ok()).as_deref() != Some(&canonical) + || dunce::canonicalize(tree.common_dir())? != dunce::canonicalize(r.gix()?.common_dir())? + { + return Err(IdeError::invalid(format!( + "The worktree at '{}' no longer belongs to this repository", + path.display() + ))); + } + linked = Some(worktree.path.clone()); + } + require_checked_out_branch(path, branch, cancel) + .and_then(|()| cli::run_streaming(path, &["merge", "--ff-only", &target], cancel, on_output)) + } else { + let refspec = format!("{tracked}:{local}"); + cli::run_streaming(r.root(), &["fetch", ".", &refspec], cancel, on_output) + }; + match updated { + Ok(()) => Ok((BranchUpdateStatus::Updated, None, linked)), Err(e) if e.kind == ErrorKind::Cancelled => Err(e), - Err(e) => Ok((BranchUpdateStatus::Failed, Some(e.message))), + Err(e) => Ok((BranchUpdateStatus::Failed, Some(e.message), linked)), } } /// Update Project › Reset to the Remote Branch: fetches the current branch's tracked /// branch and moves the branch to it, dropping local commits. Local changes are put /// aside and brought back (an error with the conflicts left in place when they clash). -pub(crate) fn reset_to_upstream(r: &Repo, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { +pub(crate) fn reset_to_upstream( + r: &Repo, + tags: FetchTagsMode, + cancel: &CancellationToken, + on_output: &dyn Fn(String), +) -> IdeResult<()> { let head = run(r.root(), &["symbolic-ref", "-q", "--short", "HEAD"], None) .map_err(|_| IdeError::invalid("cannot reset: HEAD is detached"))? .stdout_str(); @@ -1494,7 +2462,7 @@ pub(crate) fn reset_to_upstream(r: &Repo, cancel: &CancellationToken, on_output: let no_tracked = || IdeError::invalid(format!("no tracked branch configured for branch {head} or the branch doesn't exist")); let (remote, name) = branch_upstream(r, head).ok_or_else(no_tracked)?; - cli::run_streaming(r.root(), &["fetch", "--progress", &remote], cancel, on_output)?; + fetch_for_update(r, &remote, tags, cancel, on_output)?; let tracked = format!("refs/remotes/{remote}/{name}"); if run(r.root(), &["rev-parse", "-q", "--verify", &format!("{tracked}^{{commit}}")], None).is_err() { return Err(no_tracked()); @@ -1504,6 +2472,19 @@ pub(crate) fn reset_to_upstream(r: &Repo, cancel: &CancellationToken, on_output: }) } +fn fetch_for_update( + r: &Repo, + remote: &str, + tags: FetchTagsMode, + cancel: &CancellationToken, + on_output: &dyn Fn(String), +) -> IdeResult<()> { + let mut args = vec!["fetch", "--progress"]; + args.extend(crate::remotes::fetch_tag_args(tags, false)); + args.extend(["--", remote]); + cli::run_streaming(r.root(), &args, cancel, on_output) +} + /// The remote the current branch pushes to (`origin`, or the only remote, by default). /// The remote and ref HEAD's branch tracks when the ref has another name: a plain /// `git push` refuses that under the default `push.default=simple`. @@ -1541,13 +2522,18 @@ fn push_remote(r: &Repo) -> IdeResult { .ok_or_else(|| IdeError::invalid("no remote configured")) } -pub(crate) fn write_index_blob(r: &Repo, rel: &str, bytes: &[u8], env: &[(&str, &std::ffi::OsStr)]) -> IdeResult<()> { +pub(crate) fn write_index_blob( + r: &Repo, + rel: &str, + bytes: &[u8], + env: &[(&str, &std::ffi::OsStr)], +) -> IdeResult { let entry = cli::run_env(r.root(), &["--literal-pathspecs", "ls-files", "--stage", "--", rel], None, env)?.stdout_str(); let mode = entry.split_whitespace().next().unwrap_or("100644"); let id = run(r.root(), &["hash-object", "-w", "--stdin"], Some(bytes))?.stdout_str(); cli::run_env(r.root(), &["update-index", "--add", "--cacheinfo", mode, id.trim(), rel], None, env)?; - Ok(()) + Ok(id.trim().to_owned()) } pub(crate) fn stage_hunks( @@ -1572,7 +2558,7 @@ pub(crate) fn stage_hunks( } let text = crate::diff::selected_text(&old, current, selected); let bytes = encode(&text, encoding, has_bom(&base, encoding))?; - write_index_blob(r, &rel, &bytes, &[]) + write_index_blob(r, &rel, &bytes, &[]).map(|_| ()) } // Git headers contain UTF-8 paths; only source lines use the file's encoding. diff --git a/crates/ide-vcs/tests/blame_ignore.rs b/crates/ide-vcs/tests/blame_ignore.rs index 12e565f00..f1817bb93 100644 --- a/crates/ide-vcs/tests/blame_ignore.rs +++ b/crates/ide-vcs/tests/blame_ignore.rs @@ -1,5 +1,6 @@ -//! Annotate skips the commits listed in `blame.ignoreRevsFile`. +//! Git Annotate handles ignored commits and attribution options. +use ide_core::workflow_settings::{GitAnnotateMovement, GitAnnotateSettings}; use ide_vcs::Repo; use std::path::{Path, PathBuf}; use std::process::Command; @@ -129,3 +130,50 @@ fn ignoring_a_commit_adds_it_to_the_configured_list() { let blamed = commits(&fx.repo(), &fx.path("file.txt")); assert_ne!(blamed[1], second); } + +#[test] +fn annotate_tracks_whitespace_and_line_movement() { + let fx = Fixture::new(); + let source = "original café.txt"; + let within = "Move this existing line below a larger block of unchanged lines"; + let across = "Move this line into a different file within the same repository"; + let anchors = "retain line 1\nretain line 2\nretain line 3\nretain line 4\nretain line 5\nretain line 6\n"; + fx.write("spaces.txt", "this line is only indented later\n"); + fx.write("target.txt", &format!("{within}\n{anchors}")); + fx.write(source, &format!("{across}\nretain source line\n")); + let first = fx.commit_all("original files"); + fx.write("spaces.txt", " this line is only indented later\n"); + fx.write("target.txt", &format!("{anchors}{within}\n{across}\n")); + fx.write(source, "retain source line\n"); + let second = fx.commit_all("move and indent lines"); + + for repo in [fx.repo(), fx.restricted()] { + let blame = |path: &str, text: Option<&str>, ignore_whitespace, movement| { + repo.blame_with_options( + &fx.path(path), + text, + None, + encoding_rs::UTF_8.into(), + GitAnnotateSettings { ignore_whitespace, movement }, + ) + .unwrap() + }; + use GitAnnotateMovement::{AcrossFiles, WithinFile}; + assert_eq!(blame("spaces.txt", None, true, GitAnnotateMovement::None)[0].commit, first); + assert_eq!(blame("spaces.txt", None, false, GitAnnotateMovement::None)[0].commit, second); + assert_eq!( + blame("spaces.txt", Some("\tthis line is only indented later\n"), true, GitAnnotateMovement::None)[0] + .commit, + first + ); + let unchanged = blame("target.txt", None, true, GitAnnotateMovement::None); + let moved = blame("target.txt", None, true, WithinFile); + let copied = blame("target.txt", None, true, AcrossFiles); + let commits = |lines: &[ide_vcs::BlameLine]| [lines[6].commit.clone(), lines[7].commit.clone()]; + assert_eq!(commits(&unchanged), [second.clone(), second.clone()]); + assert_eq!(commits(&moved), [first.clone(), second.clone()]); + assert_eq!(commits(&copied), [first.clone(), first.clone()]); + assert!(copied[6].origin_path.is_none()); + assert!(copied[7].origin_path.as_ref().unwrap().0.ends_with(source)); + } +} diff --git a/crates/ide-vcs/tests/git_workflows.rs b/crates/ide-vcs/tests/git_workflows.rs index 764b48cd6..152250a24 100644 --- a/crates/ide-vcs/tests/git_workflows.rs +++ b/crates/ide-vcs/tests/git_workflows.rs @@ -119,6 +119,206 @@ fn quiet() -> (CancellationToken, impl Fn(String)) { (CancellationToken::new(), |_line: String| {}) } +#[test] +fn not_cherry_picked_matches_patch_and_manual_resolutions() { + let fx = Fixture::new(); + fx.write("base.txt", "base\n"); + fx.commit_all("shared"); + fx.git(&["switch", "-qc", "release"]); + fx.write("equivalent.txt", "unchanged patch\n"); + let equivalent = fx.commit_all("patch match"); + fx.write("origin.txt", "original patch\n"); + let origin = fx.commit_all("recorded pick"); + fx.write("metadata.txt", "source patch\n"); + let metadata = fx.commit_all("metadata match"); + fx.write("waiting.txt", "to pick\n"); + let waiting = fx.commit_all("still waiting"); + fx.git(&["switch", "-q", "main"]); + fx.write("main.txt", "main only\n"); + fx.commit_all("different history"); + fx.git(&["cherry-pick", &equivalent]); + fx.write("origin.txt", "resolved differently\n"); + fx.commit_all(&format!("Conflict resolution\n\n(cherry picked from commit {origin})")); + fx.write("metadata.txt", "other conflict resolution\n"); + fx.git(&["add", "metadata.txt"]); + fx.git(&["commit", "-C", &metadata]); + fx.git(&["tag", "release", "HEAD"]); + + let repo = fx.repo(); + repo.set_execution_allowed(false); + let cancel = CancellationToken::new(); + assert_eq!(repo.not_cherry_picked("release", "HEAD", &cancel).unwrap(), Some(vec![waiting])); + assert_eq!(repo.not_cherry_picked("HEAD", "HEAD", &cancel).unwrap(), Some(vec![])); + assert_eq!(repo.not_cherry_picked("missing", "HEAD", &cancel).unwrap(), None); + cancel.cancel(); + assert!(repo.not_cherry_picked("release", "HEAD", &cancel).is_err()); +} + +#[test] +fn checkout_and_rebase_restores_staged_and_unstaged_changes_after_conflict() { + let fx = Fixture::new(); + fx.write("shared.txt", "base\n"); + fx.write("staged.txt", "base\n"); + fx.commit_all("base"); + fx.git(&["switch", "-qc", "feature"]); + fx.write("shared.txt", "feature\n"); + let feature = fx.commit_all("feature"); + fx.git(&["switch", "-q", "main"]); + fx.write("shared.txt", "main\n"); + let main = fx.commit_all("main"); + fx.git(&["tag", "feature", &main]); + fx.write("shared.txt", "working edit\n"); + fx.write("staged.txt", "staged edit\n"); + fx.git(&["add", "staged.txt"]); + fx.write("untracked.txt", "untracked edit\n"); + + let plan = CheckoutRebasePlan { + base: HistoryTip { branch: Some("main".into()), commit: main.clone() }, + branch: "feature".into(), + branch_tip: Some(feature), + remote: None, + }; + let repo = fx.repo(); + let (cancel, out) = quiet(); + assert!(repo.checkout_rebase(&plan, &cancel, &out).is_err()); + assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("rebase")); + assert_eq!(fx.git(&["show", ":2:shared.txt"]), "main"); + assert_eq!(fx.git(&["show", ":3:shared.txt"]), "feature"); + assert_eq!(fx.read("staged.txt"), "base\n"); + assert_eq!(fx.read("untracked.txt"), "untracked edit\n"); + assert!(fx.exists(".git/openidea-saved-changes")); + let stash = repo.stashes().unwrap().remove(0); + fx.write(".git/openidea-saved-changes", &stash.id); + + repo.skip_operation(&cancel, &out).unwrap(); + assert_eq!(fx.git(&["branch", "--show-current"]), "feature"); + assert_eq!(fx.head(), main); + assert_eq!(fx.git(&["rev-parse", "refs/heads/main"]), main); + assert_eq!(fx.git(&["show", ":staged.txt"]), "staged edit"); + assert_eq!(fx.git(&["show", ":shared.txt"]), "main"); + assert_eq!(fx.read("shared.txt"), "working edit\n"); + assert_eq!(fx.read("untracked.txt"), "untracked edit\n"); + assert!(!fx.exists(".git/openidea-saved-changes")); + assert!(fx.git(&["stash", "list"]).is_empty()); +} + +#[test] +fn checkout_and_rebase_remote_checks_the_confirmed_refs_before_resetting() { + let (fx, _) = Fixture::with_origin(); + fx.git(&["config", "branch.autoSetupMerge", "true"]); + fx.git(&["switch", "-qc", "remote"]); + fx.write("remote.txt", "remote\n"); + let remote = fx.commit_all("remote"); + fx.git(&["push", "-qu", "origin", "HEAD:refs/heads/topic"]); + fx.git(&["switch", "-qc", "topic", "--no-track", "HEAD~"]); + fx.write("topic.txt", "local\n"); + let local = fx.commit_all("local"); + fx.git(&["switch", "-q", "main"]); + fx.write("main.txt", "main\n"); + let main = fx.commit_all("main"); + fx.write("remote.txt", "untracked\n"); + + let plan = CheckoutRebasePlan { + base: HistoryTip { branch: Some("main".into()), commit: main.clone() }, + branch: "topic".into(), + branch_tip: Some(local.clone()), + remote: Some(CheckoutRebaseRemote { + name: "origin/topic".into(), + commit: remote.clone(), + drop_local_commits: true, + }), + }; + let repo = fx.repo(); + let (cancel, out) = quiet(); + fx.git(&["branch", "-f", "topic", &main]); + let err = repo.checkout_rebase(&plan, &cancel, &out).unwrap_err(); + assert!(err.message.contains("a branch changed")); + assert_eq!(fx.git(&["rev-parse", "refs/heads/topic"]), main); + + fx.git(&["branch", "-f", "topic", &local]); + assert!(repo.checkout_rebase(&plan, &cancel, &out).is_err(), "untracked file prevents switching"); + assert_eq!(fx.git(&["rev-parse", "refs/heads/topic"]), local); + assert_eq!(fx.git(&["branch", "--show-current"]), "main"); + assert_eq!(fx.read("remote.txt"), "untracked\n"); + + std::fs::remove_file(fx.path("remote.txt")).unwrap(); + repo.checkout_rebase(&plan, &cancel, &out).unwrap(); + assert_eq!(fx.git(&["branch", "--show-current"]), "topic"); + assert_eq!(fx.git(&["rev-parse", "HEAD^"]), main); + assert_eq!(fx.git(&["rev-parse", "refs/remotes/origin/topic"]), remote); + assert_eq!(fx.git(&["rev-parse", "--abbrev-ref", "@{upstream}"]), "origin/topic"); + assert_eq!(fx.read("remote.txt"), "remote\n"); + assert!(!fx.exists("topic.txt")); +} + +#[test] +fn checkout_and_rebase_keeps_a_divergent_local_branch_and_can_restore_the_checkout() { + let (fx, _) = Fixture::with_origin(); + fx.git(&["switch", "-qc", "remote"]); + fx.write("remote.txt", "remote\n"); + let remote = fx.commit_all("remote work"); + fx.git(&["push", "-q", "origin", "HEAD:refs/heads/topic"]); + fx.git(&["switch", "-qc", "topic", "HEAD~"]); + fx.write("topic.txt", "local\n"); + let local = fx.commit_all("local work"); + fx.git(&["branch", "--set-upstream-to=origin/topic"]); + fx.git(&["switch", "-q", "main"]); + fx.write("main.txt", "main\n"); + let main = fx.commit_all("main work"); + fx.git(&["tag", "topic", &main]); + let repo = fx.repo(); + let (cancel, out) = quiet(); + let plan = CheckoutRebasePlan { + base: HistoryTip { branch: Some("main".into()), commit: main.clone() }, + branch: "topic".into(), + branch_tip: Some(local.clone()), + remote: Some(CheckoutRebaseRemote { name: "origin/topic".into(), commit: remote, drop_local_commits: false }), + }; + + let rebased = repo.checkout_rebase(&plan, &cancel, &out).unwrap(); + assert_eq!(rebased.branch.as_deref(), Some("topic")); + assert_eq!(rebased.commit, fx.head()); + assert_eq!(fx.git(&["rev-parse", "HEAD^"]), main); + assert_eq!(fx.read("topic.txt"), "local\n"); + assert!(!fx.exists("remote.txt")); + assert_eq!(fx.git(&["rev-parse", "--abbrev-ref", "@{upstream}"]), "origin/topic"); + + assert!(repo.restore_rebase_checkout(&local, &local, "topic", &plan.base).is_err()); + fx.git(&["branch", "-f", "main", &local]); + assert!(repo.restore_rebase_checkout(&local, &rebased.commit, "topic", &plan.base).is_err()); + assert_eq!(fx.head(), rebased.commit); + fx.git(&["branch", "-f", "main", &main]); + fx.write("main.txt", "local after rebase\n"); + fx.git(&["add", "main.txt"]); + repo.restore_rebase_checkout(&local, &rebased.commit, "topic", &plan.base).unwrap(); + assert_eq!(fx.git(&["branch", "--show-current"]), "main"); + assert_eq!(fx.head(), main); + assert_eq!(fx.git(&["rev-parse", "refs/heads/topic"]), local); + assert_eq!(fx.git(&["show", ":main.txt"]), "local after rebase"); +} + +#[test] +fn checkout_and_rebase_creates_a_tracking_branch_under_the_chosen_name() { + let (fx, _) = Fixture::with_origin(); + fx.git(&["config", "branch.autoSetupMerge", "true"]); + let main = fx.head(); + fx.git(&["switch", "--detach"]); + let (cancel, out) = quiet(); + let repo = fx.repo(); + let plan = CheckoutRebasePlan { + base: HistoryTip { branch: None, commit: main.clone() }, + branch: "review".into(), + branch_tip: None, + remote: Some(CheckoutRebaseRemote { name: "origin/main".into(), commit: main, drop_local_commits: false }), + }; + let rebased = repo.checkout_rebase(&plan, &cancel, &out).unwrap(); + assert_eq!(fx.git(&["branch", "--show-current"]), "review"); + assert_eq!(fx.git(&["rev-parse", "--abbrev-ref", "@{upstream}"]), "origin/main"); + repo.restore_rebase_checkout(&rebased.commit, &rebased.commit, "review", &plan.base).unwrap(); + assert!(fx.git(&["branch", "--show-current"]).is_empty()); + assert_eq!(fx.head(), plan.base.commit); +} + fn status_of<'a>(st: &'a [FileStatus], rel: &str) -> Option<&'a FileStatus> { st.iter().find(|s| s.rel_path == rel) } @@ -338,6 +538,27 @@ fn interactive_rebase_squash_without_message_combines_messages() { assert!(!msg.contains('#'), "comment lines must be stripped: {msg}"); } +#[test] +fn interactive_rebase_amends_the_message_after_the_last_fixup() { + let (fx, ids) = linear(); + let (cancel, out) = quiet(); + let message = "Combined commits\n\n# Details"; + fx.repo() + .interactive_rebase( + Some(&ids[0]), + &[ + entry(&ids[1], RebaseAction::Pick, None), + entry(&ids[2], RebaseAction::Fixup, None), + entry(&ids[3], RebaseAction::Fixup, Some(message)), + ], + &cancel, + &out, + ) + .unwrap(); + assert_eq!(fx.git(&["log", "-1", "--format=%B"]), message); + assert_eq!(fx.git(&["show", "--format=", "--name-only", "HEAD"]), "f2.txt\nf3.txt\nf4.txt"); +} + #[test] fn interactive_rebase_keeps_local_changes() { let (fx, ids) = linear(); @@ -541,6 +762,7 @@ fn interactive_rebase_edit_stops_for_amend() { let (fx, ids) = linear(); let repo = fx.repo(); let (cancel, out) = quiet(); + assert!(!repo.is_interactive_rebase()); repo.interactive_rebase( Some(&ids[1]), &[entry(&ids[2], RebaseAction::Edit, None), entry(&ids[3], RebaseAction::Pick, None)], @@ -549,11 +771,13 @@ fn interactive_rebase_edit_stops_for_amend() { ) .unwrap(); assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("rebase")); + assert!(repo.is_interactive_rebase()); fx.write("f3.txt", "edited\n"); repo.stage(&[fx.path("f3.txt")]).unwrap(); repo.commit("", true, false).unwrap(); repo.continue_operation(&cancel, &out).unwrap(); assert_eq!(repo.branch_info().unwrap().operation, None); + assert!(!repo.is_interactive_rebase()); assert_eq!(fx.git(&["show", "HEAD~1:f3.txt"]), "edited"); } @@ -795,6 +1019,454 @@ fn reset_to_the_remote_branch_needs_a_tracked_branch_that_exists() { assert!(err.message.contains("no tracked branch"), "{}", err.message); } +#[test] +fn fetching_one_remote_only_refreshes_its_tracking_branches() { + let (fx, bare) = Fixture::with_origin(); + let head = fx.head(); + fx.git(&["remote", "add", "vendor/team", bare.to_str().unwrap()]); + git_in(&bare, &["branch", "published-later", &head]); + let (cancel, out) = quiet(); + let repo = fx.repo(); + repo.fetch_remote("vendor/team", &cancel, &out).unwrap(); + assert_eq!(fx.git(&["rev-parse", "vendor/team/published-later"]), head); + assert!(!fx.git(&["branch", "-r"]).contains("origin/published-later")); + assert_eq!(fx.head(), head); + assert!(repo.fetch_remote("not-configured", &cancel, &out).is_err()); + // Git's remote command rejects overlapping names, but repositories can have them in config. + fx.git(&["config", "remote.vendor.url", bare.to_str().unwrap()]); + fx.git(&["config", "remote.vendor.fetch", "+refs/heads/*:refs/remotes/vendor/*"]); + fx.git(&["config", "branch.main.remote", "vendor"]); + fx.git(&["config", "branch.main.merge", "refs/heads/team/main"]); + let info = repo.branch_info().unwrap(); + assert_eq!(info.upstream.as_deref(), Some("vendor/team/main")); + let tracking = info.upstream_tracking.unwrap(); + assert_eq!((tracking.remote.as_str(), tracking.branch.as_str()), ("vendor", "team/main")); +} + +#[test] +fn pull_from_without_a_mode_uses_the_repositorys_pull_config() { + let (fx, bare) = Fixture::with_origin(); + fx.git(&["config", "pull.ff", "true"]); + fx.write("local.txt", "local work"); + fx.commit_all("local"); + fx.push_from_other(&bare, "remote.txt", "remote work"); + let remote = git_in(&bare, &["rev-parse", "main"]); + let (cancel, out) = quiet(); + fx.repo().pull_from("origin", &["main".into()], None, &MergeOptions::default(), &cancel, &out).unwrap(); + assert_eq!(fx.git(&["rev-parse", "HEAD^"]), remote); + assert_eq!(fx.subjects()[..2], ["local", "remote remote.txt"]); +} + +#[test] +fn rebase_a_named_branch_from_root_updates_refs_and_preserves_changes() { + let (fx, _) = Fixture::with_origin(); + let main = fx.head(); + fx.git(&["switch", "--orphan", "topic"]); + fx.write("topic.txt", "root of topic"); + let old_root = fx.commit_all("Topic root"); + fx.git(&["branch", "bookmark"]); + fx.write("next.txt", "next step"); + let old_tip = fx.commit_all("Topic tip"); + fx.git(&["switch", "main"]); + fx.write("a.txt", "staged local changes"); + fx.git(&["add", "a.txt"]); + fx.write("a.txt", "working copy changes"); + let repo = fx.repo(); + let options = RebaseOptions { + onto: Some("refs/heads/main".into()), + branch: Some("topic".into()), + update_refs: true, + autosquash: Some(false), + ..Default::default() + }; + repo.rebase_with(None, &options).unwrap(); + assert_eq!(fx.git(&["symbolic-ref", "--short", "HEAD"]), "topic"); + assert_ne!(fx.head(), old_tip); + assert_ne!(fx.git(&["rev-parse", "bookmark"]), old_root); + assert_eq!(fx.git(&["rev-parse", "bookmark"]), fx.git(&["rev-parse", "HEAD^"])); + assert_eq!(fx.git(&["rev-parse", "HEAD^^"]), main); + assert_eq!(fx.git(&["rev-parse", "main"]), main); + assert_eq!(fx.git(&["show", ":a.txt"]), "staged local changes"); + assert_eq!(fx.read("a.txt"), "working copy changes"); +} + +#[test] +fn interactive_rebase_edits_gits_merge_plan_and_commit_message() { + let (fx, _) = Fixture::with_origin(); + fx.git(&["switch", "-c", "topic"]); + fx.write("primary.txt", "primary"); + fx.commit_all("Primary change"); + fx.git(&["switch", "-c", "side"]); + fx.write("side.txt", "side"); + fx.commit_all("Side change"); + fx.git(&["switch", "topic"]); + fx.write("topic.txt", "topic"); + fx.commit_all("Topic change"); + fx.git(&["merge", "--no-ff", "-m", "Merge side", "side"]); + fx.write("primary.txt", "fixed"); + let head = fx.commit_all("fixup! Primary change"); + fx.git(&["switch", "main"]); + fx.write("upstream.txt", "upstream"); + let upstream = fx.commit_all("Upstream change"); + fx.git(&["switch", "topic"]); + fx.write("local.txt", "staged"); + fx.git(&["add", "local.txt"]); + fx.write("local.txt", "working"); + + let repo = fx.repo(); + let options = RebaseOptions { rebase_merges: true, autosquash: Some(true), ..Default::default() }; + let (cancel, out) = quiet(); + let declined = repo.rebase_with_editor(Some("main"), &options, &cancel, &out, &|prompt| { + assert!(matches!(prompt.kind, RebaseEditKind::Plan)); + None + }); + assert!(matches!(declined, Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled)); + assert_eq!(fx.head(), head); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["show", ":local.txt"]), "staged"); + assert_eq!(fx.read("local.txt"), "working"); + + let abort_request = CancellationToken::new(); + let cancelled = repo.rebase_with_editor(Some("main"), &options, &abort_request, &out, &|_| { + abort_request.cancel(); + None + }); + assert!(matches!(cancelled, Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled)); + assert_eq!(fx.head(), head); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["show", ":local.txt"]), "staged"); + + let message_prompt = std::cell::Cell::new(false); + repo.rebase_with_editor(Some("main"), &options, &cancel, &out, &|prompt| match prompt.kind { + RebaseEditKind::Plan => { + assert!(prompt.plan.is_none()); + for instruction in ["label ", "reset ", "merge -C ", "fixup "] { + assert!(prompt.text.lines().any(|line| line.starts_with(instruction)), "missing {instruction}"); + } + let primary = + prompt.text.lines().find(|line| line.starts_with("pick ") && line.ends_with("Primary change")).unwrap(); + Some(prompt.text.replacen(primary, &primary.replacen("pick ", "reword ", 1), 1).into()) + } + RebaseEditKind::Message => { + assert!(prompt.text.starts_with("Primary change")); + message_prompt.set(true); + Some("Primary change with fixup\n\n# Markdown section\n".to_owned().into()) + } + }) + .unwrap(); + assert!(message_prompt.get()); + assert_ne!(fx.head(), head); + assert_eq!(fx.git(&["show", "-s", "--format=%P", "HEAD"]).split_whitespace().count(), 2); + assert_eq!(fx.git(&["merge-base", "HEAD", "main"]), upstream); + assert_eq!(fx.git(&["log", "--format=%s", "main..HEAD"]).lines().count(), 4); + assert!(fx.subjects().iter().any(|subject| subject == "Primary change with fixup")); + assert_eq!( + fx.git(&["log", "--format=%b", "--fixed-strings", "--grep=Primary change with fixup", "-1"]), + "# Markdown section" + ); + assert_eq!(fx.read("primary.txt"), "fixed"); + assert_eq!(fx.git(&["show", ":local.txt"]), "staged"); + assert_eq!(fx.read("local.txt"), "working"); + assert_eq!(fx.git(&["stash", "list"]), ""); +} + +#[test] +fn interactive_rebase_resumes_with_git_message_editors_after_conflicts() { + let (fx, _) = Fixture::with_origin(); + fx.git(&["switch", "-c", "topic"]); + fx.write("a.txt", "topic\n"); + let original = fx.commit_all("Topic conflict\n\n# Markdown heading\n; Literal semicolon"); + fx.write("later.txt", "later\n"); + let later = fx.commit_all("Topic follow-up"); + fx.git(&["switch", "main"]); + fx.write("a.txt", "upstream\n"); + fx.write("other.txt", "upstream\n"); + let upstream = fx.commit_all("Upstream conflict"); + fx.git(&["switch", "topic"]); + fx.git(&["config", "rebase.abbreviateCommands", "true"]); + fx.git(&["config", "core.commentChar", ";"]); + fx.git(&["config", "commit.verbose", "true"]); + + let repo = fx.repo(); + let (cancel, out) = quiet(); + let start = || RebaseEditorOperation::Start { upstream: Some("main".into()), options: RebaseOptions::default() }; + let edit_plan = |prompt: RebaseEdit| { + let plan = prompt.plan.unwrap(); + let [ + RebaseTodoRow::Commit { id: first_id, author, summary, .. }, + RebaseTodoRow::Commit { id: second_id, revision, message, action: RebaseAction::Pick, .. }, + ] = plan.as_slice() + else { + panic!("expected two commit rows"); + }; + assert_eq!(first_id, &original); + assert_eq!(author, "Test User"); + assert_eq!(summary, "Topic conflict"); + assert_eq!(second_id, &later); + assert_eq!(message, "Topic follow-up"); + assert!(prompt.text.lines().any(|line| line.starts_with(';'))); + assert!(!prompt.text.contains('\u{1}')); + let entry = format!("p {revision}"); + assert!(prompt.text.contains(&entry)); + Some(prompt.text.replacen(&entry, &format!("r {revision}"), 1).into()) + }; + let stopped = repo.rebase_editor_operation(start(), &cancel, &out, &edit_plan); + assert!(stopped.is_err()); + assert_eq!(repo.operation().unwrap().as_deref(), Some("rebase")); + assert!(!fx.read(".git/rebase-merge/git-rebase-todo").contains('\u{1}')); + fx.write("a.txt", "resolved\n"); + fx.git(&["add", "a.txt"]); + let resume = RebaseEditorOperation::Continue { stage: false }; + let declined = repo.rebase_editor_operation(resume, &cancel, &out, &|prompt| { + assert!(matches!(prompt.kind, RebaseEditKind::Message)); + assert!(prompt.text.starts_with("Topic conflict")); + None + }); + assert!(matches!(declined, Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled)); + assert_eq!(repo.operation().unwrap().as_deref(), Some("rebase")); + assert_eq!(fx.git(&["show", ":a.txt"]), "resolved"); + + fx.write("other.txt", "stage and retry\n"); + let resume = RebaseEditorOperation::Continue { stage: false }; + let refused = repo.rebase_editor_operation(resume, &cancel, &out, &|_| panic!("unexpected editor prompt")); + assert!(matches!(refused, Err(e) if e.message == UNSTAGED_CHANGES_PREVENT_REBASE)); + + let follow_up = std::cell::Cell::new(false); + let resume = RebaseEditorOperation::Continue { stage: true }; + repo.rebase_editor_operation(resume, &cancel, &out, &|prompt| { + assert!(matches!(prompt.kind, RebaseEditKind::Message)); + assert!(!prompt.text.contains('\u{1}') && !prompt.text.contains("diff --git")); + assert!(!prompt.text.contains("Please enter the commit message")); + if prompt.text.starts_with("Topic conflict") { + assert!(prompt.text.contains("# Markdown heading\n; Literal semicolon")); + Some(prompt.text.into()) + } else { + assert!(prompt.text.starts_with("Topic follow-up")); + follow_up.set(true); + Some("Reworded follow-up\n".to_owned().into()) + } + }) + .unwrap(); + assert!(follow_up.get()); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["rev-parse", "HEAD^^"]), upstream); + assert_eq!(fx.git(&["log", "--format=%s", "main..HEAD"]), "Reworded follow-up\nTopic conflict"); + assert_eq!(fx.git(&["show", "-s", "--format=%b", "HEAD^"]), "# Markdown heading\n; Literal semicolon"); + assert_eq!(fx.read("a.txt"), "resolved\n"); + assert_eq!(fx.git(&["show", "HEAD^:other.txt"]), "stage and retry"); + + fx.git(&["switch", "-c", "skip-conflict", &later]); + assert!(repo.rebase_editor_operation(start(), &cancel, &out, &edit_plan).is_err()); + assert_eq!(repo.operation().unwrap().as_deref(), Some("rebase")); + // An older stopped session already has todo comments written using the repository configuration. + let pending = ".git/rebase-merge/git-rebase-todo"; + fx.write(pending, &format!("; Saved before the editor upgrade\n{}", fx.read(pending))); + fx.write(".git/rebase-merge/openidea-editor", "{}"); + repo.rebase_editor_operation(RebaseEditorOperation::Skip, &cancel, &out, &|prompt| { + assert!(matches!(prompt.kind, RebaseEditKind::Message)); + assert!(prompt.text.starts_with("Topic follow-up")); + Some("Reworded after skip\n".to_owned().into()) + }) + .unwrap(); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["rev-parse", "HEAD^"]), upstream); + assert_eq!(fx.git(&["log", "--format=%s", "main..HEAD"]), "Reworded after skip"); + assert_eq!(fx.read("a.txt"), "upstream\n"); + assert_eq!(fx.git(&["config", "--get", "core.commentChar"]), ";"); +} + +#[test] +fn interactive_rebase_remembers_inline_rewords_by_original_commit_across_conflicts() { + let (fx, _) = Fixture::with_origin(); + fx.git(&["switch", "-c", "topic"]); + fx.write("a.txt", "topic\n"); + fx.commit_all("Identical original message"); + fx.write("second.txt", "second\n"); + let second = fx.commit_all("Identical original message"); + fx.write("third.txt", "third\n"); + let third = fx.commit_all("Identical original message"); + fx.git(&["switch", "main"]); + fx.write("a.txt", "upstream\n"); + fx.commit_all("Upstream conflict"); + fx.git(&["switch", "topic"]); + fx.git(&["config", "core.commentString", "//"]); + + let (cancel, out) = quiet(); + let start = RebaseEditorOperation::Start { upstream: Some("main".into()), options: RebaseOptions::default() }; + let stopped = fx.repo().rebase_editor_operation(start, &cancel, &out, &|prompt| { + let rows = prompt.plan.unwrap(); + let revisions: Vec<_> = rows + .iter() + .map(|row| match row { + RebaseTodoRow::Commit { message, revision, .. } => { + assert_eq!(message, "Identical original message"); + revision + } + _ => panic!("expected a commit row"), + }) + .collect(); + assert_eq!(revisions.len(), 3); + Some(RebaseEditorReply { + text: format!("pick {}\nr {}\nreword {}\n", revisions[0], revisions[1], revisions[2]), + rewords: [ + (second.clone(), "Second subject\n\n# Second body\n// Second literal prefix\n".into()), + (third.clone(), "Third subject\n\n# Third body\n// Third literal prefix\n".into()), + ] + .into(), + }) + }); + assert!(stopped.is_err()); + let repo = fx.repo(); + assert_eq!(repo.operation().unwrap().as_deref(), Some("rebase")); + fx.write("a.txt", "resolved\n"); + fx.git(&["add", "a.txt"]); + + let prompts = std::cell::Cell::new(0); + repo.rebase_editor_operation(RebaseEditorOperation::Continue { stage: false }, &cancel, &out, &|prompt| { + prompts.set(prompts.get() + 1); + assert_eq!(prompts.get(), 1); + assert!(matches!(prompt.kind, RebaseEditKind::Message)); + assert!(prompt.text.starts_with("Identical original message")); + Some("Manual conflict message\n".to_owned().into()) + }) + .unwrap(); + assert_eq!(prompts.get(), 1); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.subjects()[..3], ["Third subject", "Second subject", "Manual conflict message"]); + assert_eq!( + fx.git(&["show", "-s", "--format=%B", "HEAD"]), + "Third subject\n\n# Third body\n// Third literal prefix" + ); + assert_eq!( + fx.git(&["show", "-s", "--format=%B", "HEAD^"]), + "Second subject\n\n# Second body\n// Second literal prefix" + ); + assert!(!fx.exists(".git/rebase-merge/openidea-editor")); +} + +#[test] +fn interactive_rebase_preserves_and_edits_autosquash_message_replacements() { + let fx = Fixture::new(); + fx.git(&["config", "rebase.abbreviateCommands", "true"]); + fx.write("base.txt", "base\n"); + let base = fx.commit_all("Base"); + fx.write("target.txt", "original\n"); + let target = fx.commit_all("Prepare review"); + fx.write("follow-up.txt", "follow-up\n"); + let follow_up = fx.commit_all("Add follow-up"); + fx.write("target.txt", "amended\n"); + let replacement = "Review ready\n\n# Replacement details"; + let amend = fx.commit_all(&format!("amend! Prepare review\n\n{replacement}")); + fx.git(&["branch", "edit-message"]); + let (cancel, out) = quiet(); + for edit_message in [false, true] { + if edit_message { + fx.git(&["switch", "edit-message"]); + } + let edited = "Review ready for submission\n\n# Updated details"; + let edited_message = std::cell::Cell::new(false); + fx.repo() + .rebase_with_editor(Some(&base), &RebaseOptions::default(), &cancel, &out, &|prompt| match prompt.kind { + RebaseEditKind::Plan => { + let plan = prompt.plan.unwrap(); + let [ + RebaseTodoRow::Commit { id: first, .. }, + RebaseTodoRow::Commit { + id: second, + action: RebaseAction::Fixup, + fixup_message: Some(RebaseFixupMessage::Replace), + .. + }, + RebaseTodoRow::Commit { id: third, .. }, + ] = plan.as_slice() + else { + panic!("expected Git's autosquashed plan"); + }; + assert_eq!([first, second, third], [&target, &amend, &follow_up]); + assert!(prompt.text.contains("\nf -C ")); + let text = if edit_message { prompt.text.replace("\nf -C ", "\nf -c ") } else { prompt.text }; + Some(text.into()) + } + RebaseEditKind::Message => { + assert!(edit_message); + assert_eq!(prompt.text.trim(), replacement); + assert!(!edited_message.replace(true)); + Some(format!("{edited}\n").into()) + } + }) + .unwrap(); + assert_eq!(edited_message.get(), edit_message); + assert_eq!(fx.git(&["show", "-s", "--format=%s", "HEAD"]), "Add follow-up"); + assert_eq!(fx.git(&["show", "-s", "--format=%B", "HEAD^"]), if edit_message { edited } else { replacement }); + assert_eq!(fx.git(&["show", "HEAD^:target.txt"]), "amended"); + assert_eq!(fx.repo().operation().unwrap(), None); + } +} + +#[test] +fn interactive_rebase_can_move_a_branch_update_in_the_structured_plan() { + let (fx, _) = Fixture::with_origin(); + fx.git(&["config", "rebase.abbreviateCommands", "true"]); + fx.git(&["switch", "-c", "topic"]); + fx.write("first.txt", "first\n"); + let original = fx.commit_all("First change"); + fx.git(&["branch", "review"]); + fx.write("second.txt", "second\n"); + fx.commit_all("Second change"); + fx.git(&["switch", "main"]); + fx.write("upstream.txt", "upstream\n"); + let upstream = fx.commit_all("Advance base"); + fx.git(&["switch", "topic"]); + let start = RebaseEditorOperation::Start { + upstream: Some("main".into()), + options: RebaseOptions { update_refs: true, ..RebaseOptions::default() }, + }; + let (cancel, out) = quiet(); + fx.repo() + .rebase_editor_operation(start, &cancel, &out, &|prompt| { + let plan = prompt.plan.unwrap(); + let [ + RebaseTodoRow::Commit { line: first, id, .. }, + RebaseTodoRow::UpdateRef { line: update, reference }, + RebaseTodoRow::Commit { line: second, .. }, + ] = plan.as_slice() + else { + panic!("expected two commits and one ref update"); + }; + assert_eq!(id, &original); + assert_eq!(reference, "refs/heads/review"); + let lines: Vec<_> = prompt.text.lines().collect(); + assert_eq!(lines[*update], "u refs/heads/review"); + Some(format!("{}\n{}\n{}\n", lines[*first], lines[*second], lines[*update]).into()) + }) + .unwrap(); + assert_eq!(fx.git(&["rev-parse", "review"]), fx.git(&["rev-parse", "topic"])); + assert_ne!(fx.git(&["rev-parse", "review"]), original); + assert_eq!(fx.git(&["rev-parse", "topic~2"]), upstream); + assert_eq!(fx.git(&["log", "--format=%s", "main..review"]), "Second change\nFirst change"); +} + +#[test] +fn merge_unrelated_histories_requires_the_explicit_option() { + let (fx, _) = Fixture::with_origin(); + let head = fx.head(); + let tree = fx.git(&["rev-parse", "HEAD^{tree}"]); + let unrelated = fx.git(&["commit-tree", &tree, "-m", "Independent history"]); + fx.git(&["branch", "external", &unrelated]); + let repo = fx.repo(); + let branches = ["refs/heads/external".into()]; + assert!(repo.merge_with(&branches, &MergeOptions::default()).is_err()); + assert_eq!(fx.head(), head); + let options = MergeOptions { + allow_unrelated_histories: true, + message: Some("Join the histories".into()), + ..Default::default() + }; + repo.merge_with(&branches, &options).unwrap(); + assert_eq!(fx.git(&["show", "-s", "--format=%P", "HEAD"]), format!("{head} {unrelated}")); + assert_eq!(fx.subjects()[0], "Join the histories"); +} + #[cfg(unix)] #[test] fn push_can_skip_a_failing_pre_push_hook() { @@ -830,10 +1502,555 @@ fn force_push_without_lease_overwrites_a_remote_that_moved() { let lease = PushOptions { force_with_lease: true, ..Default::default() }; let err = repo.push_with(lease, &cancel, &out).unwrap_err(); assert!(err.message.contains("stale info"), "{}", err.message); - repo.push_with(PushOptions { force: true, ..Default::default() }, &cancel, &out).unwrap(); + let report = repo.push_with(PushOptions { force: true, ..Default::default() }, &cancel, &out).unwrap(); + assert_eq!(report.refs[0].status, PushRefStatus::Forced); assert_eq!(git_in(&bare, &["rev-parse", "main"]), fx.head()); } +#[test] +fn push_reports_a_custom_destination_and_the_actual_commit_and_tag_updates() { + let (fx, bare) = Fixture::with_origin(); + let repo = fx.repo(); + let cancel = CancellationToken::new(); + let output = Mutex::new(Vec::new()); + let out = |line: String| output.lock().unwrap().push(line); + let selection = PushSelection { + branch: Some("main".into()), + revision: None, + remote: "origin".into(), + target: "review/saved".into(), + special_ref: false, + }; + let push = + |tags| repo.push_selected(&selection, None, PushOptions { tags, ..Default::default() }, &cancel, &out).unwrap(); + let created = push(None); + assert_eq!(created.remote.as_deref(), Some("origin")); + assert_eq!( + created.refs, + [PushRefResult { reference: "refs/heads/review/saved".into(), status: PushRefStatus::Created, commits: None }] + ); + assert_eq!(push(None).refs[0].status, PushRefStatus::UpToDate); + + fx.write("a.txt", "two\n"); + fx.commit_all("Second"); + fx.write("a.txt", "three\n"); + fx.commit_all("Third"); + fx.git(&["tag", "reviewed"]); + output.lock().unwrap().clear(); + let report = push(Some(PushTags::All)); + assert_eq!(output.lock().unwrap().iter().filter(|line| line.starts_with("To ")).count(), 1); + assert_eq!( + report.refs, + [ + PushRefResult { + reference: "refs/heads/review/saved".into(), + status: PushRefStatus::FastForward, + commits: Some(2), + }, + PushRefResult { reference: "refs/tags/reviewed".into(), status: PushRefStatus::Created, commits: None }, + ] + ); + assert_eq!(git_in(&bare, &["rev-parse", "review/saved"]), fx.head()); + assert_eq!(push(Some(PushTags::All)).refs[1].status, PushRefStatus::UpToDate); +} + +#[test] +fn push_keeps_the_applied_branch_in_the_report_when_a_tag_fails() { + use ide_core::error::ErrorData; + + let (fx, bare) = Fixture::with_origin(); + let original = fx.head(); + git_in(&bare, &["tag", "release"]); + fx.write("a.txt", "new work\n"); + fx.commit_all("Local work"); + fx.git(&["tag", "release"]); + let (cancel, out) = quiet(); + let opts = PushOptions { tags: Some(PushTags::All), ..Default::default() }; + let repo = fx.repo(); + let selection = repo.default_push_target(Some("main")).unwrap().unwrap().selection; + let error = repo.push_selected(&selection, None, opts, &cancel, &out).unwrap_err(); + assert!(error.message.contains("already exists"), "{}", error.message); + let Some(ErrorData::PushPartiallyApplied { report }) = error.data else { + panic!("missing partial push report"); + }; + assert_eq!( + report.refs, + [PushRefResult { reference: "refs/heads/main".into(), status: PushRefStatus::FastForward, commits: Some(1) }] + ); + assert_eq!(git_in(&bare, &["rev-parse", "main"]), fx.head()); + assert_eq!(git_in(&bare, &["rev-parse", "release"]), original); +} + +#[test] +fn push_keeps_tracked_branch_recovery_when_tags_were_published() { + use ide_core::error::ErrorData; + + let (fx, bare) = Fixture::with_origin(); + fx.write("local.txt", "Local work\n"); + fx.commit_all("Local work"); + fx.git(&["tag", "ready"]); + fx.push_from_other(&bare, "remote.txt", "Remote work\n"); + fx.git(&["fetch"]); + let repo = fx.repo(); + let (cancel, out) = quiet(); + let selection = repo.default_push_target(Some("main")).unwrap().unwrap().selection; + let opts = PushOptions { tags: Some(PushTags::All), ..Default::default() }; + let error = repo.push_selected(&selection, None, opts, &cancel, &out).unwrap_err(); + let Some(ErrorData::PushRejected { source, upstream, divergence: Some(_), report: Some(report) }) = error.data + else { + panic!("expected tracked branch rejection and published refs: {error:?}"); + }; + assert_eq!((source.as_str(), upstream.as_str()), ("main", "origin/main")); + assert_eq!( + report.refs, + [PushRefResult { reference: "refs/tags/ready".into(), status: PushRefStatus::Created, commits: None }] + ); + assert_eq!(git_in(&bare, &["rev-parse", "refs/tags/ready"]), fx.head()); + fx.git(&["merge", "--no-edit", "@{upstream}"]); + let retry = repo.push_selected(&selection, None, opts, &cancel, &out).unwrap(); + assert!(retry.refs.iter().any(|r| r.reference == "refs/heads/main" && r.status == PushRefStatus::FastForward)); + assert_eq!(git_in(&bare, &["rev-parse", "main"]), fx.head()); +} + +#[test] +fn push_current_branch_tags_are_limited_to_the_selected_commit() { + let (fx, bare) = Fixture::with_origin(); + let initial = fx.head(); + fx.git(&["tag", "-a", "base", "-m", "Annotated base"]); + fx.git(&["tag", "lightweight"]); + fx.write("a.txt", "new work\n"); + fx.commit_all("New work"); + fx.git(&["tag", "-a", "later", "-m", "Annotated later"]); + let (cancel, out) = quiet(); + let selection = PushSelection { + branch: Some("main".into()), + revision: Some(initial.clone()), + remote: "origin".into(), + target: "review/partial".into(), + special_ref: false, + }; + let opts = PushOptions { tags: Some(PushTags::CurrentBranch), ..Default::default() }; + fx.repo().push_selected(&selection, None, opts, &cancel, &out).unwrap(); + assert_eq!(git_in(&bare, &["rev-parse", "review/partial"]), initial); + assert_eq!(git_in(&bare, &["tag", "--list"]), "base"); +} + +#[test] +fn force_push_of_the_selected_branch_does_not_overwrite_a_colliding_tag() { + use ide_core::error::ErrorData; + + let (fx, bare) = Fixture::with_origin(); + let original = fx.head(); + git_in(&bare, &["tag", "release"]); + fx.push_from_other(&bare, "remote.txt", "Remote work\n"); + fx.write("local.txt", "Local work\n"); + fx.commit_all("Local work"); + fx.git(&["tag", "release"]); + let (cancel, out) = quiet(); + let repo = fx.repo(); + let selection = repo.default_push_target(Some("main")).unwrap().unwrap().selection; + let opts = PushOptions { force: true, tags: Some(PushTags::All), ..Default::default() }; + let error = repo.push_selected(&selection, None, opts, &cancel, &out).unwrap_err(); + let Some(ErrorData::PushPartiallyApplied { report }) = error.data else { + panic!("expected a branch update and tag rejection: {error:?}"); + }; + assert_eq!(report.refs[0].status, PushRefStatus::Forced); + assert_eq!(git_in(&bare, &["rev-parse", "main"]), fx.head()); + assert_eq!(git_in(&bare, &["rev-parse", "release"]), original); +} + +#[test] +fn rejected_push_lease_keeps_the_tip_reviewed_before_a_fetch() { + use ide_core::error::ErrorData; + + let (fx, bare) = Fixture::with_origin(); + fx.git(&["branch", "-m", "release"]); + fx.write("local.txt", "local work"); + fx.commit_all("local work"); + let local_tip = fx.head(); + fx.push_from_other(&bare, "remote.txt", "remote work"); + let repo = fx.repo(); + let (cancel, out) = quiet(); + let rejection = || repo.push(false, false, &cancel, &out).unwrap_err(); + + let error = rejection(); + assert!(error.message.contains("(fetch first)"), "{}", error.message); + assert!(matches!( + error.data, + Some(ErrorData::PushRejected { source, upstream, divergence: None, .. }) + if source == "release" && upstream == "origin/main" + )); + + fx.git(&["fetch", "-q"]); + let Some(ErrorData::PushRejected { divergence: Some(divergence), .. }) = rejection().data else { + panic!("missing known divergence for a tracked branch with a different name"); + }; + assert_eq!(divergence.source, "release"); + assert_eq!(divergence.remote, "origin"); + assert_eq!(divergence.target, "main"); + assert_eq!(divergence.local_tip, local_tip); + assert_eq!(divergence.remote_tip, fx.git(&["rev-parse", "origin/main"])); + assert_eq!(divergence.remote_commits, 1); + + fx.push_from_other(&bare, "other.txt", "new remote work"); + fx.git(&["fetch", "-q"]); + let new_tip = fx.git(&["rev-parse", "origin/main"]); + let error = repo.force_push_rejected(&divergence, None, false, &cancel, &out).unwrap_err(); + assert!(error.message.contains("(stale info)"), "{}", error.message); + assert_eq!(git_in(&bare, &["rev-parse", "main"]), new_tip); + + let Some(ErrorData::PushRejected { divergence: Some(divergence), .. }) = rejection().data else { + panic!("missing reviewed divergence after the fetch"); + }; + assert_eq!(divergence.remote_tip, new_tip); + assert_eq!(divergence.remote_commits, 2); + repo.force_push_rejected(&divergence, None, false, &cancel, &out).unwrap(); + assert_eq!(git_in(&bare, &["rev-parse", "main"]), local_tip); +} + +#[test] +fn rejected_push_only_offers_force_for_the_diverged_tracked_destination() { + use ide_core::error::ErrorData; + + let (fx, bare) = Fixture::with_origin(); + let repo = fx.repo(); + let (cancel, out) = quiet(); + fx.push_from_other(&bare, "remote.txt", "remote work"); + fx.git(&["fetch", "-q"]); + let error = repo.push(false, false, &cancel, &out).unwrap_err(); + assert!(error.message.contains("(non-fast-forward)"), "{}", error.message); + assert!(matches!(error.data, Some(ErrorData::PushRejected { divergence: None, .. }))); + + fx.git(&["branch", "other", "origin/main"]); + fx.git(&["push", "-q", "origin", "other"]); + fx.write("local.txt", "local work"); + fx.commit_all("local work"); + fx.git(&["config", "remote.origin.push", "refs/heads/main:refs/heads/other"]); + let error = repo.push(false, false, &cancel, &out).unwrap_err(); + assert!(error.message.contains("(non-fast-forward)"), "{}", error.message); + assert_eq!(error.data, None, "the rejected ref was not the upstream"); +} + +#[test] +fn default_push_target_preserves_tracking_and_configured_destinations() { + let (fx, bare) = Fixture::with_origin(); + fx.git(&["branch", "-m", "release"]); + let repo = fx.repo(); + let default = repo.default_push_target(None).unwrap().unwrap(); + assert_eq!( + (default.selection.branch.as_deref(), default.selection.remote.as_str(), default.selection.target.as_str()), + (Some("release"), "origin", "main") + ); + assert!(!default.set_upstream); + + fx.git(&["config", "--add", "remote.origin.push", "refs/heads/*:refs/heads/publish/*"]); + assert_eq!(repo.default_push_target(None).unwrap().unwrap().selection.target, "publish/release"); + fx.git(&["config", "--add", "remote.origin.push", "+release:refs/for/main"]); + let review = repo.default_push_target(Some("release")).unwrap().unwrap(); + assert_eq!(review.selection.target, "refs/for/main"); + assert!(review.selection.special_ref); + assert!(!review.set_upstream); + let (cancel, out) = quiet(); + let inspection = repo.inspect_push(&review.selection, true, &cancel).unwrap(); + assert!(inspection.remote_checked); + repo.push_selected(&review.selection, Some(&inspection), PushOptions::default(), &cancel, &out).unwrap(); + assert_eq!(git_in(&bare, &["rev-parse", "refs/for/main"]), fx.head()); + + fx.git(&["remote", "add", "mirror/team", bare.to_str().unwrap()]); + fx.git(&["config", "branch.release.pushRemote", "mirror/team"]); + fx.git(&["config", "remote.mirror/team.push", "HEAD:refs/heads/approved"]); + let overridden = repo.default_push_target(None).unwrap().unwrap(); + assert_eq!(overridden.selection.remote, "mirror/team"); + assert_eq!(overridden.selection.target, "approved"); + assert!(!overridden.set_upstream); +} + +#[test] +fn outgoing_commits_follow_the_push_target_and_its_fetch_refspec() { + let (fx, _) = Fixture::with_origin(); + let fork = fx.tmp.path().join("fork.git"); + git_in(fx.tmp.path(), &["init", "-q", "--bare", fork.to_str().unwrap()]); + fx.git(&["remote", "add", "fork", fork.to_str().unwrap()]); + let fetch = "+refs/heads/*:refs/remotes/published/*"; + fx.git(&["config", "remote.fork.fetch", fetch]); + fx.git(&["push", "-q", "fork", "main:refs/heads/review/main"]); + let published = fx.head(); + fx.write("b.txt", "upstream only\n"); + fx.commit_all("Pushed only to the upstream"); + fx.git(&["push", "-q", "origin", "main"]); + fx.write("c.txt", "local only\n"); + fx.commit_all("Still local"); + fx.git(&["config", "branch.main.pushRemote", "fork"]); + fx.git(&["config", "remote.fork.push", "refs/heads/main:refs/heads/review/main"]); + let repo = fx.repo(); + + let info = repo.branch_info().unwrap(); + assert_eq!(info.upstream.as_deref(), Some("origin/main")); + assert_eq!(info.ahead, 1); + let outgoing = info.outgoing.unwrap(); + assert_eq!((&*outgoing.remote, &*outgoing.branch), ("fork", "review/main")); + assert_eq!(outgoing.reference, "refs/remotes/published/review/main"); + assert_eq!(outgoing.count, 2); + let branches = repo.branches().unwrap(); + assert_eq!(branches.iter().find(|b| b.current).unwrap().outgoing.as_ref(), Some(&outgoing)); + let selection = repo.default_push_target(Some("main")).unwrap().unwrap().selection; + assert_eq!((&*selection.remote, &*selection.target), ("fork", "review/main")); + let cancel = CancellationToken::new(); + assert_eq!(repo.inspect_push(&selection, false, &cancel).unwrap().remote_tip.as_deref(), Some(&*published)); + + // A stale ref excluded by the fetch refspec is no longer a basis for the push count. + fx.git(&["config", "--add", "remote.fork.fetch", "^refs/heads/review/main"]); + assert!(repo.branch_info().unwrap().outgoing.is_none()); + fx.git(&["config", "--replace-all", "remote.fork.fetch", fetch]); + let alternate = fx.tmp.path().join("different-push-endpoint.git"); + fx.git(&["remote", "set-url", "--push", "fork", alternate.to_str().unwrap()]); + assert!(repo.branch_info().unwrap().outgoing.is_none()); + assert!(repo.inspect_push(&selection, false, &cancel).unwrap().remote_tip.is_none()); +} + +#[test] +fn push_up_to_commit_prefers_a_containing_local_branch_and_only_publishes_the_selection() { + let (fx, bare) = Fixture::with_origin(); + let base = fx.head(); + fx.git(&["push", "origin", "main:refs/heads/review/partial", "main:refs/heads/detached"]); + fx.git(&["switch", "-c", "topic2"]); + fx.git(&["branch", "--set-upstream-to=origin/review/partial"]); + fx.write("selected.txt", "publish this"); + fx.commit_all("Selected commit"); + let selected = fx.head(); + fx.git(&["branch", "topic10"]); + fx.write("later.txt", "keep this local"); + fx.commit_all("Later commit"); + let later = fx.head(); + fx.git(&["switch", "topic10"]); + let repo = fx.repo(); + let (cancel, out) = quiet(); + assert_eq!(repo.commit_push_target(&selected, &cancel).unwrap().branch.as_deref(), Some("topic10")); + + fx.git(&["switch", "main"]); + assert_eq!(repo.commit_push_target(&base, &cancel).unwrap().branch.as_deref(), Some("main")); + let target = repo.commit_push_target(&selected, &cancel).unwrap(); + assert_eq!(target.branch.as_deref(), Some("topic2")); + let target = target.destination.unwrap(); + assert_eq!(target.selection.target, "review/partial"); + assert_eq!(target.selection.revision.as_deref(), Some(selected.as_str())); + assert!(!target.set_upstream); + repo.push_selected(&target.selection, None, PushOptions::default(), &cancel, &out).unwrap(); + assert_eq!(git_in(&bare, &["rev-parse", "refs/heads/review/partial"]), selected); + assert_eq!(fx.git(&["rev-parse", "topic2"]), later); + assert_eq!(fx.head(), base); + + fx.git(&["tag", "selected", &selected]); + fx.git(&["branch", "-D", "topic2", "topic10"]); + let detached = repo.commit_push_target(&selected, &cancel).unwrap(); + assert!(detached.branch.is_none()); + let target = detached.destination.unwrap(); + assert_eq!(target.selection.target, "main"); + assert_eq!(target.selection.revision.as_deref(), Some(selected.as_str())); + assert_eq!(fx.git(&["symbolic-ref", "--short", "HEAD"]), "main"); + fx.git(&["switch", "--detach"]); + let detached = repo.commit_push_target(&selected, &cancel).unwrap().destination.unwrap(); + assert_eq!(detached.selection.target, "detached2"); +} + +#[test] +fn push_target_choices_use_the_selected_source_and_each_remotes_refspec() { + let (fx, origin) = Fixture::with_origin(); + let fork = tempfile::tempdir().unwrap(); + git_in(fork.path(), &["init", "--bare"]); + fx.git(&["remote", "add", "fork", fork.path().to_str().unwrap()]); + fx.git(&["config", "remote.origin.push", "refs/heads/topic:refs/heads/publish/topic"]); + fx.git(&["config", "remote.fork.push", "+refs/heads/topic:refs/for/topic"]); + fx.git(&["switch", "-qc", "topic"]); + fx.write("selected.txt", "publish only this"); + let selected = fx.commit_all("Selected commit"); + fx.write("later.txt", "keep local"); + let later = fx.commit_all("Later commit"); + fx.git(&["switch", "main"]); + let repo = fx.repo(); + let (cancel, out) = quiet(); + + let named = repo.push_target_choices(Some("topic"), None, &cancel).unwrap(); + assert_eq!(named.branch.as_deref(), Some("topic")); + assert_eq!(named.destination.unwrap().selection.target, "publish/topic"); + let choices = repo.push_target_choices(None, Some(&selected), &cancel).unwrap(); + assert_eq!(choices.branch.as_deref(), Some("topic")); + let chosen = choices.destinations.iter().find(|target| target.selection.remote == "fork").unwrap(); + assert_eq!(chosen.selection.target, "refs/for/topic"); + assert!(chosen.selection.special_ref); + assert!(!chosen.set_upstream); + assert_eq!(chosen.selection.revision.as_deref(), Some(selected.as_str())); + repo.push_selected(&chosen.selection, None, PushOptions::default(), &cancel, &out).unwrap(); + assert_eq!(git_in(fork.path(), &["rev-parse", "refs/for/topic"]), selected); + assert!(git_in(fork.path(), &["for-each-ref", "refs/heads"]).is_empty()); + assert!(git_in(&origin, &["for-each-ref", "refs/heads/publish"]).is_empty()); + assert_eq!(fx.git(&["rev-parse", "refs/heads/topic"]), later); +} + +#[test] +fn detached_push_suggests_a_new_branch_and_pins_the_selected_commit() { + let (fx, bare) = Fixture::with_origin(); + let main = fx.head(); + fx.git(&["push", "origin", "main:refs/heads/detached", "main:refs/heads/detached2"]); + fx.git(&["fetch", "origin"]); + fx.git(&["switch", "--detach"]); + fx.write("detached.txt", "detached change"); + fx.commit_all("detached change"); + let reviewed = fx.head(); + let repo = fx.repo(); + let target = repo.default_push_target(None).unwrap().unwrap(); + let selection = target.selection; + assert!(selection.branch.is_none()); + assert_eq!(selection.revision.as_deref(), Some(reviewed.as_str())); + assert_eq!(selection.target, "detached3"); + assert_eq!(selection.remote, "origin"); + assert!(!target.set_upstream); + let (cancel, out) = quiet(); + let inspection = repo.inspect_push(&selection, true, &cancel).unwrap(); + assert!(inspection.remote_checked); + assert_eq!(inspection.remote_tip.as_deref(), Some("")); + fx.write("another.txt", "HEAD moved after review"); + fx.commit_all("another detached commit"); + + let ambiguous = PushSelection { revision: Some("HEAD".into()), ..selection.clone() }; + assert!(repo.inspect_push(&ambiguous, false, &cancel).is_err()); + let opts = PushOptions { set_upstream: true, ..Default::default() }; + fx.git(&["push", "origin", "main:refs/heads/detached3"]); + let stale = repo.push_selected(&selection, Some(&inspection), opts, &cancel, &out).unwrap_err(); + assert!(stale.message.contains("stale info"), "{}", stale.message); + assert_eq!(git_in(&bare, &["rev-parse", "refs/heads/detached3"]), main); + git_in(&bare, &["update-ref", "-d", "refs/heads/detached3"]); + repo.push_selected(&selection, Some(&inspection), opts, &cancel, &out).unwrap(); + assert_eq!(git_in(&bare, &["rev-parse", "refs/heads/detached3"]), reviewed); + assert_eq!(git_in(&bare, &["rev-parse", "refs/heads/main"]), main); + assert_ne!(fx.head(), reviewed); + assert!(repo.head().unwrap().0.is_none()); + assert_eq!(fx.git(&["for-each-ref", "--format=%(refname:short)", "refs/heads"]), "main"); +} + +#[test] +fn inspect_push_fetches_missing_history_and_preserves_the_reviewed_lease() { + let (fx, bare) = Fixture::with_origin(); + fx.write("local.txt", "local work"); + fx.commit_all("local work"); + fx.push_from_other(&bare, "remote.txt", "remote work"); + let repo = fx.repo(); + let (cancel, out) = quiet(); + let selection = PushSelection { + branch: Some("main".into()), + revision: None, + remote: "origin".into(), + target: "main".into(), + special_ref: false, + }; + + assert_eq!(repo.inspect_push(&selection, false, &cancel).unwrap().state, PushTargetState::Ready); + assert_eq!(repo.inspect_push(&selection, true, &cancel).unwrap().state, PushTargetState::FetchRequired); + repo.fetch_push_target(&selection, &cancel, &out).unwrap(); + let reviewed = repo.inspect_push(&selection, true, &cancel).unwrap(); + assert_eq!(reviewed.state, PushTargetState::Diverged); + assert_eq!(reviewed.remote_commits, 1); + assert_eq!(reviewed.remote_tip, Some(fx.git(&["rev-parse", "origin/main"]))); + assert_eq!(reviewed.local_tip, fx.head()); + + fx.push_from_other(&bare, "another.txt", "new remote work"); + fx.git(&["fetch"]); + let lease = PushOptions { force_with_lease: true, ..Default::default() }; + let error = repo.push_selected(&selection, Some(&reviewed), lease, &cancel, &out).unwrap_err(); + assert!(error.message.contains("stale info"), "{}", error.message); + assert_eq!(git_in(&bare, &["rev-parse", "main"]), fx.git(&["rev-parse", "origin/main"])); + let updated = repo.inspect_push(&selection, true, &cancel).unwrap(); + repo.push_selected(&selection, Some(&updated), lease, &cancel, &out).unwrap(); + assert_eq!(git_in(&bare, &["rev-parse", "main"]), reviewed.local_tip); +} + +#[test] +fn inspect_push_reuses_incoming_observations_when_the_remote_is_unavailable() { + let (fx, bare) = Fixture::with_origin(); + fx.write("local.txt", "local work"); + fx.commit_all("local work"); + fx.push_from_other(&bare, "remote.txt", "remote work"); + let tracked = fx.git(&["rev-parse", "origin/main"]); + let advertised = git_in(&bare, &["rev-parse", "main"]); + let repo = fx.repo(); + let (cancel, out) = quiet(); + let selection = repo.default_push_target(None).unwrap().unwrap().selection; + + assert_eq!(repo.inspect_push(&selection, false, &cancel).unwrap().state, PushTargetState::Ready); + let report = repo.check_incoming_refs(&cancel).unwrap(); + assert!(report.errors.is_empty()); + assert_eq!(report.branches[0].advertised_commit, advertised); + let unavailable = fx.tmp.path().join("unavailable.git"); + std::fs::rename(&bare, &unavailable).unwrap(); + for live in [false, true] { + let result = repo.inspect_push(&selection, live, &cancel).unwrap(); + assert_eq!(result.state, PushTargetState::FetchRequired); + assert_eq!(result.remote_tip.as_deref(), Some(advertised.as_str())); + assert!(!result.remote_checked); + } + assert_eq!(fx.git(&["rev-parse", "origin/main"]), tracked); + + fx.git(&["config", "branch.main.merge", "refs/heads/release"]); + let changed_tracking = repo.inspect_push(&selection, false, &cancel).unwrap(); + assert_eq!(changed_tracking.remote_tip.as_deref(), Some(tracked.as_str())); + fx.git(&["config", "branch.main.merge", "refs/heads/main"]); + let different_endpoint = fx.tmp.path().join("different.git"); + fx.git(&["remote", "set-url", "origin", different_endpoint.to_str().unwrap()]); + let changed_endpoint = repo.inspect_push(&selection, true, &cancel).unwrap(); + assert_eq!(changed_endpoint.remote_tip.as_deref(), Some(tracked.as_str())); + fx.git(&["remote", "set-url", "origin", bare.to_str().unwrap()]); + fx.git(&["remote", "set-url", "--push", "origin", different_endpoint.to_str().unwrap()]); + assert!(repo.inspect_push(&selection, false, &cancel).unwrap().remote_tip.is_none()); + fx.git(&["config", "--unset", "remote.origin.pushurl"]); + std::fs::rename(&unavailable, &bare).unwrap(); + + git_in(&bare, &["update-ref", "-d", "refs/heads/main", &advertised]); + let deleted = repo.inspect_push(&selection, true, &cancel).unwrap(); + assert_eq!(deleted.state, PushTargetState::Ready); + assert!(deleted.remote_checked); + assert_eq!(deleted.remote_tip.as_deref(), Some("")); + git_in(&bare, &["update-ref", "refs/heads/main", &advertised]); + + fx.push_from_other(&bare, "next.txt", "another remote commit"); + let fresh = repo.inspect_push(&selection, true, &cancel).unwrap(); + let new_tip = git_in(&bare, &["rev-parse", "main"]); + assert!(fresh.remote_checked); + assert_eq!(fresh.remote_tip.as_deref(), Some(new_tip.as_str())); + repo.fetch_push_target(&selection, &cancel, &out).unwrap(); + let fetched = repo.inspect_push(&selection, false, &cancel).unwrap(); + assert_eq!(fetched.remote_tip, fresh.remote_tip); + assert_eq!(fetched.state, PushTargetState::Diverged); + assert_eq!(fetched.remote_commits, 2); +} + +#[test] +fn inspect_push_uses_the_push_url_and_keeps_the_fetch_url_tracking_ref() { + let (fx, bare) = Fixture::with_origin(); + let other = fx.tmp.path().join("push.git"); + git_in(fx.tmp.path(), &["clone", "--bare", bare.to_str().unwrap(), other.to_str().unwrap()]); + fx.git(&["remote", "set-url", "--push", "origin", other.to_str().unwrap()]); + let tracking_tip = fx.git(&["rev-parse", "origin/main"]); + fx.push_from_other(&other, "at-push-url.txt", "there is other work at the push endpoint"); + fx.write("local.txt", "local work"); + fx.commit_all("local work"); + let repo = fx.repo(); + let (cancel, out) = quiet(); + let selection = PushSelection { + branch: Some("main".into()), + revision: None, + remote: "origin".into(), + target: "main".into(), + special_ref: false, + }; + + assert_eq!(repo.inspect_push(&selection, true, &cancel).unwrap().state, PushTargetState::FetchRequired); + repo.fetch_push_target(&selection, &cancel, &out).unwrap(); + let reviewed = repo.inspect_push(&selection, true, &cancel).unwrap(); + assert_eq!(reviewed.state, PushTargetState::Diverged); + assert_eq!(reviewed.remote_tip, Some(git_in(&other, &["rev-parse", "main"]))); + assert_eq!(fx.git(&["rev-parse", "origin/main"]), tracking_tip); +} + #[test] fn push_to_another_branch_can_make_it_the_upstream() { let (fx, _bare) = Fixture::with_origin(); @@ -871,6 +2088,50 @@ fn tags_are_pushed_one_at_a_time_deleted_restored_and_deleted_on_the_remote() { assert!(repo.delete_tag("missing").is_err()); } +#[test] +fn deleting_tags_from_configured_remotes_skips_missing_tags_and_keeps_moved_tips() { + let fx = Fixture::new(); + fx.write("base.txt", "base\n"); + fx.commit_all("initial"); + fx.git(&["tag", "-a", "release", "-m", "annotated release"]); + let original = fx.git(&["rev-parse", "refs/tags/release"]); + let base = fx.head(); + let stale = fx.tmp.path().join("tag moved.git"); + let empty = fx.tmp.path().join("tag absent.git"); + let matching = fx.tmp.path().join("tag matching.git"); + for path in [&stale, &empty, &matching] { + git_in(fx.tmp.path(), &["init", "-q", "--bare", path.to_str().unwrap()]); + } + fx.git(&["remote", "add", "a-stale", stale.to_str().unwrap()]); + fx.git(&["remote", "add", "b-empty", empty.to_str().unwrap()]); + fx.git(&["remote", "add", "publish/release", empty.to_str().unwrap()]); + fx.git(&["remote", "set-url", "--push", "publish/release", matching.to_str().unwrap()]); + fx.git(&["push", "-q", "a-stale", "HEAD:refs/tags/release"]); + + let repo = fx.repo(); + let (cancel, out) = quiet(); + assert!(repo.push_tag("release", matching.to_str().unwrap(), &cancel, &out).is_err()); + assert!(git_in(&matching, &["tag"]).is_empty()); + repo.push_tag("release", "publish/release", &cancel, &out).unwrap(); + assert_eq!(git_in(&matching, &["rev-parse", "refs/tags/release"]), original); + assert!(fx.git(&["branch", "-r"]).is_empty()); + + fx.git(&["remote", "set-url", "--add", "--push", "publish/release", empty.to_str().unwrap()]); + let deleted = repo.delete_tag("release").unwrap(); + let err = repo.delete_tag_on_remotes(&deleted, &cancel, &out).unwrap_err(); + assert!(err.message.contains("a-stale")); + assert!(!err.message.contains("b-empty")); + assert!(!err.message.contains("publish/release")); + assert_eq!(git_in(&stale, &["rev-parse", "refs/tags/release"]), base); + assert!(git_in(&matching, &["tag"]).is_empty()); + assert!(git_in(&empty, &["tag"]).is_empty()); + + fx.git(&["remote", "remove", "a-stale"]); + repo.delete_tag_on_remotes(&deleted, &cancel, &out).unwrap(); + repo.restore_tag(&deleted).unwrap(); + assert_eq!(fx.git(&["rev-parse", "refs/tags/release"]), original); +} + #[test] fn fetch_prunes_deleted_remote_branches() { let (fx, bare) = Fixture::with_origin(); @@ -890,6 +2151,404 @@ fn fetch_prunes_deleted_remote_branches() { assert_eq!(repo.branch_info().unwrap().upstream, None); } +#[test] +fn check_incoming_refs_reads_the_remote_without_fetching_objects_or_tracking_refs() { + let (fx, bare) = Fixture::with_origin(); + let old = fx.head(); + fx.git(&["push", "-q", "origin", "main:refs/heads/review/next"]); + fx.git(&["config", "--replace-all", "remote.origin.fetch", "+refs/heads/*:refs/remotes/tracking/*"]); + fx.git(&["fetch", "-q", "origin"]); + fx.git(&["branch", "--track", "review", "tracking/review/next"]); + + fx.git(&["remote", "add", "offline", fx.tmp.path().join("missing.git").to_str().unwrap()]); + fx.git(&["update-ref", "refs/remotes/offline/main", &old]); + fx.git(&["branch", "--track", "broken", "offline/main"]); + let fetch_head = fx.read(".git/FETCH_HEAD"); + fx.push_from_other(&bare, "incoming.txt", "new changes\n"); + let new = git_in(&bare, &["rev-parse", "refs/heads/main"]); + git_in(&bare, &["update-ref", "refs/heads/review/next", &new]); + let repo = fx.repo(); + let (cancel, out) = quiet(); + + let report = repo.check_incoming_refs(&cancel).unwrap(); + assert_eq!(report.errors.len(), 1); + assert_eq!(report.errors[0].remote, "offline"); + assert_eq!(report.branches.len(), 2); + for (name, remote_branch) in [("main", "main"), ("review", "review/next")] { + let found = report.branches.iter().find(|branch| branch.branch == name).unwrap(); + assert_eq!(found.tracked_tip.tracking.remote, "origin"); + assert_eq!(found.tracked_tip.tracking.branch, remote_branch); + assert_eq!(found.tracked_tip.commit, old); + assert_eq!(found.advertised_commit, new); + } + assert!(!repo.has_commit(&new)); + assert_eq!(fx.read(".git/FETCH_HEAD"), fetch_head); + assert_eq!(repo.branch_info().unwrap().behind, 0); + + repo.fetch_remote("origin", &cancel, &out).unwrap(); + assert!(repo.check_incoming_refs(&cancel).unwrap().branches.is_empty()); + assert_eq!(repo.branch_info().unwrap().behind, 1); +} + +#[test] +fn fetch_report_keeps_prunes_from_the_remotes_that_succeeded() { + use ide_core::workflow_settings::FetchTagsMode::{Auto, Sync}; + + let (fx, bare) = Fixture::with_origin(); + let missing = fx.tmp.path().join("missing.git"); + fx.git(&["remote", "add", "a-offline", missing.to_str().unwrap()]); + fx.git(&["remote", "add", "z-skipped", missing.to_str().unwrap()]); + fx.git(&["config", "remote.z-skipped.skipDefaultUpdate", "true"]); + fx.git(&["config", "remote.origin.skipDefaultUpdate", "true"]); + fx.git(&["config", "remote.origin.skipFetchAll", "false"]); + fx.git(&["remote", "add", "release/mirror", bare.to_str().unwrap()]); + fx.git(&["push", "-q", "origin", "main:gone/review"]); + fx.git(&["tag", "release/retired"]); + git_in(&bare, &["branch", "-D", "gone/review"]); + let repo = fx.repo(); + let (cancel, out) = quiet(); + + let report = repo.fetch_report(None, Sync, &cancel, &out).unwrap(); + let [origin, offline, mirror] = report.remotes.as_slice() else { panic!("{report:?}") }; + assert_eq!(offline.remote, "a-offline"); + assert!(offline.error.as_ref().unwrap().message.contains("missing.git")); + assert_eq!(origin.remote, "origin"); + assert!(origin.error.is_none()); + assert_eq!(origin.pruned.len(), 2); + assert!(origin.pruned.contains(&"release/retired".into())); + assert!(origin.pruned.contains(&"origin/gone/review".into())); + assert_eq!(mirror.remote, "release/mirror"); + assert!(mirror.error.is_none()); + assert!(mirror.pruned.is_empty()); + assert!(!fx.git(&["branch", "-r"]).contains("gone/review")); + assert!(fx.git(&["tag", "--list", "release/retired"]).is_empty()); + assert_eq!(fx.read(".git/FETCH_HEAD").lines().count(), 2); + + let background = repo.fetch_in_background(&["a-offline".into()], &cancel, &out).unwrap(); + assert_eq!( + background.remotes.iter().map(|result| result.remote.as_str()).collect::>(), + ["origin", "release/mirror"] + ); + assert!(background.remotes.iter().all(|result| result.error.is_none())); + + // Fetching a named remote intentionally bypasses the exclusion for Fetch All. + let selected = repo.fetch_report(Some("z-skipped"), Auto, &cancel, &out).unwrap(); + assert_eq!(selected.remotes.len(), 1); + assert_eq!(selected.remotes[0].remote, "z-skipped"); + assert!(selected.remotes[0].error.is_some()); +} + +#[test] +fn fetch_report_does_not_claim_a_locked_ref_was_pruned() { + let (fx, bare) = Fixture::with_origin(); + fx.git(&["push", "-q", "origin", "main:gone"]); + git_in(&bare, &["branch", "-D", "gone"]); + fx.write(".git/refs/remotes/origin/gone.lock", ""); + let (cancel, out) = quiet(); + let report = fx + .repo() + .fetch_report(Some("origin"), ide_core::workflow_settings::FetchTagsMode::Auto, &cancel, &out) + .unwrap(); + let remote = &report.remotes[0]; + assert!(remote.error.as_ref().unwrap().message.contains("gone.lock")); + assert!(remote.pruned.is_empty()); + assert!(fx.git(&["branch", "-r"]).contains("origin/gone")); +} + +#[test] +fn fetch_tag_modes_override_git_config_only_when_selected() { + use ide_core::workflow_settings::FetchTagsMode::*; + + let (fx, bare) = Fixture::with_origin(); + let tree = fx.git(&["rev-parse", "HEAD^{tree}"]); + let orphan = fx.git(&["commit-tree", &tree, "-m", "Unrelated archive"]); + fx.git(&["tag", "archived", &orphan]); + fx.git(&["tag", "on-main"]); + fx.git(&["push", "origin", "--tags"]); + fx.git(&["tag", "-d", "archived", "on-main"]); + fx.git(&["tag", "local-only"]); + fx.git(&["config", "remote.origin.tagOpt", "--no-tags"]); + let repo = fx.repo(); + let (cancel, out) = quiet(); + let tags = || fx.git(&["tag", "--list"]); + + repo.fetch_with_tags(None, Auto, &cancel, &out).unwrap(); + assert_eq!(tags(), "local-only"); + fx.git(&["config", "remote.origin.pruneTags", "true"]); + repo.fetch_with_tags(None, Never, &cancel, &out).unwrap(); + assert_eq!(tags(), "local-only"); + repo.fetch_with_tags(Some("origin"), Always, &cancel, &out).unwrap(); + assert_eq!(tags(), "archived\nlocal-only\non-main"); + + git_in(&bare, &["tag", "-d", "archived"]); + fx.git(&["config", "remote.origin.pruneTags", "false"]); + repo.fetch_with_tags(Some("origin"), Sync, &cancel, &out).unwrap(); + assert_eq!(tags(), "on-main"); + + fx.git(&["tag", "-f", "on-main", &orphan]); + let error = repo.fetch_with_tags(Some("origin"), Sync, &cancel, &out).unwrap_err(); + assert!(error.message.contains("would clobber existing tag"), "{}", error.message); + assert_eq!(fx.git(&["rev-parse", "refs/tags/on-main"]), orphan); +} + +#[test] +fn update_project_syncs_tags_with_the_tracked_remote() { + use ide_core::workflow_settings::FetchTagsMode::*; + + let (fx, bare) = Fixture::with_origin(); + fx.git(&["tag", "local-only"]); + fx.push_from_other(&bare, "new.txt", "updated"); + git_in(&bare, &["tag", "received", "main"]); + fx.git(&["config", "remote.origin.pruneTags", "false"]); + let (cancel, out) = quiet(); + fx.repo().pull_checked_branch_with_tags(false, Some("main"), Sync, &cancel, &out).unwrap(); + assert_eq!(fx.git(&["tag", "--list"]), "received"); + assert_eq!(fx.head(), git_in(&bare, &["rev-parse", "main"])); + assert_eq!(fx.git(&["config", "--get", "remote.origin.pruneTags"]), "false"); +} + +#[test] +fn fetch_tag_mode_also_applies_when_updating_selected_branches() { + use ide_core::workflow_settings::FetchTagsMode::*; + + let (fx, bare) = Fixture::with_origin(); + fx.git(&["tag", "local-only"]); + fx.push_from_other(&bare, "new.txt", "updated"); + git_in(&bare, &["tag", "received", "main"]); + let (cancel, out) = quiet(); + let updates = fx.repo().update_branches_with_tags(&["main".into()], Never, &cancel, &out).unwrap(); + assert_eq!(updates[0].status, BranchUpdateStatus::Updated); + assert_eq!(fx.git(&["tag", "--list"]), "local-only"); + assert_eq!(fx.head(), git_in(&bare, &["rev-parse", "main"])); +} + +#[test] +fn fetch_full_history_keeps_head_and_uses_the_clone_remote() { + use ide_core::workflow_settings::FetchTagsMode; + let (fx, bare) = Fixture::with_origin(); + fx.push_from_other(&bare, "new.txt", "remote content"); + let clone = fx.tmp.path().join("shallow"); + git_in( + fx.tmp.path(), + &[ + "clone", + "-q", + "--no-local", + "--depth", + "1", + "--origin", + "upstream", + bare.to_str().unwrap(), + clone.to_str().unwrap(), + ], + ); + let repo = Repo::discover(&clone).unwrap().unwrap(); + let head = git_in(&clone, &["rev-parse", "HEAD"]); + assert!(repo.is_shallow().unwrap()); + assert_eq!(git_in(&clone, &["rev-list", "--count", "HEAD"]), "1"); + + git_in(&bare, &["tag", "old", "main~1"]); + repo.unshallow_with_tags(FetchTagsMode::Always, &CancellationToken::new(), &|_| {}).unwrap(); + assert!(!repo.is_shallow().unwrap()); + assert_eq!(git_in(&clone, &["rev-list", "--count", "HEAD"]), "2"); + assert_eq!(git_in(&clone, &["rev-parse", "HEAD"]), head); + assert_eq!(git_in(&clone, &["tag", "--list"]), "old"); +} + +#[test] +fn clear_stashes_keeps_working_tree_and_index() { + let fx = Fixture::new(); + fx.write("a.txt", "base\n"); + fx.commit_all("initial"); + for message in ["first stash", "second stash"] { + fx.write("a.txt", message); + fx.git(&["stash", "push", "-m", message]); + } + fx.write("a.txt", "staged\n"); + fx.git(&["add", "a.txt"]); + fx.write("a.txt", "unstaged\n"); + let repo = fx.repo(); + assert_eq!(repo.stashes().unwrap().len(), 2); + + repo.stash_clear().unwrap(); + assert!(repo.stashes().unwrap().is_empty()); + assert_eq!(fx.read("a.txt"), "unstaged\n"); + assert_eq!(fx.git(&["show", ":a.txt"]), "staged"); +} + +#[test] +fn revision_patch_applies_only_the_selected_paths() { + let fx = Fixture::new(); + let literal = "note [1].txt"; + let sibling = "note 1.txt"; + fx.write(literal, "first version\r\n"); + fx.write(sibling, "other file\r\n"); + let before = fx.commit_all("initial"); + fx.write(literal, "selected revision\r\n"); + fx.write(sibling, "unselected revision\r\n"); + let after = fx.commit_all("both files changed"); + fx.git(&["checkout", "--detach", &before]); + + let repo = fx.repo(); + let patch = repo.create_revisions_patch(&before, &after, &[PathBuf::from(literal)]).unwrap(); + let outcome = repo.apply_patch(&patch).unwrap(); + assert_eq!(outcome.applied, [literal]); + assert_eq!(fx.read(literal), "selected revision\r\n"); + assert_eq!(fx.read(sibling), "other file\r\n"); + assert!(fx.git(&["diff", "--cached", "--name-only"]).is_empty()); +} + +#[test] +fn selected_patch_keeps_its_conflict_sides_as_files_are_resolved() { + let fx = Fixture::new(); + let files = ["one.txt", "two.txt"]; + for file in files { + fx.write(file, "base\n"); + } + let before = fx.commit_all("Base"); + for file in files { + fx.write(file, "patched\n"); + } + let after = fx.commit_all("Patch"); + let repo = fx.repo(); + let patch = repo.create_commits_patch(&[after], false).unwrap(); + fx.git(&["checkout", "--detach", &before]); + for file in files { + fx.write(file, "local\n"); + } + fx.commit_all("Local changes"); + let outcome = repo.apply_selected_patch(&patch, &files.map(str::to_owned)).unwrap(); + assert_eq!(outcome.conflicts, files); + repo.accept_conflict_side(&[fx.dir.join("one.txt")], ConflictSide::Ours).unwrap(); + assert_eq!(fx.read("one.txt"), "local\n"); + let remaining = fx.dir.join("two.txt"); + let versions = repo.merge_versions(&remaining, encoding_rs::UTF_8).unwrap(); + assert_eq!(versions.sides.operation.as_deref(), Some("apply-patch")); + assert_eq!(versions.ours.as_deref(), Some("local\n")); + assert_eq!(versions.theirs.as_deref(), Some("patched\n")); + repo.accept_conflict_side(&[remaining], ConflictSide::Theirs).unwrap(); + assert_eq!(fx.read("two.txt"), "patched\n"); + assert_eq!(repo.merge_sides().unwrap().operation, None); +} + +#[test] +fn patch_diff_reads_the_local_and_patched_versions_without_writing_the_repository() { + use PatchDiffContent::{Binary, Conflict, Raw, Text}; + let fx = Fixture::new(); + fx.write("clean.txt", "original\n"); + fx.write("conflict.txt", "base\n"); + fx.write("old-name.txt", "moved\n"); + fx.write("delete.txt", "removed\n"); + std::fs::write(fx.dir.join("data.bin"), [0, 1, 255]).unwrap(); + let before = fx.commit_all("before patch"); + fx.write("clean.txt", "patched\n"); + fx.write("conflict.txt", "theirs\n"); + fx.write("add.txt", "added\n"); + fx.git(&["rm", "delete.txt"]); + fx.git(&["mv", "old-name.txt", "new-name.txt"]); + std::fs::write(fx.dir.join("data.bin"), [0, 2, 255]).unwrap(); + let after = fx.commit_all("patch"); + let repo = fx.repo(); + let patch = repo.create_commits_patch(&[after], false).unwrap(); + fx.git(&["checkout", "--detach", &before]); + fx.write("conflict.txt", "ours\n"); + fx.git(&["add", "conflict.txt"]); + let original_index = std::fs::read(fx.dir.join(".git/index")).unwrap(); + let encoding = |_: &Path, _: &[u8]| TextEncoding::from(encoding_rs::UTF_8); + let diff = |file| repo.patch_file_diff(&patch, file, &encoding).unwrap(); + + assert!(matches!( + diff("clean.txt").content, + Text { before: Some(before), after: Some(after) } if before == "original\n" && after == "patched\n" + )); + assert!(matches!( + diff("conflict.txt").content, + Conflict { local: Some(local), base: Some(base), patched: Some(patched) } + if local == "ours\n" && base == "base\n" && patched == "theirs\n" + )); + assert!(matches!(diff("add.txt").content, Text { before: None, after: Some(text) } if text == "added\n")); + assert!(matches!(diff("delete.txt").content, Text { before: Some(text), after: None } if text == "removed\n")); + let rename = diff("new-name.txt"); + assert!(rename.old_path.unwrap().ends_with("old-name.txt")); + assert!(matches!(rename.content, Text { before: Some(before), after: Some(after) } if before == after)); + assert!(matches!(diff("data.bin").content, Binary)); + + let raw = "--- a/conflict.txt\n+++ b/conflict.txt\n@@ -1 +1 @@\n-missing preimage\n+result\n"; + assert!(matches!( + repo.patch_file_diff(raw, "conflict.txt", &encoding).unwrap().content, + Raw { local: Some(local), patch, applies: false } if local == "ours\n" && patch == raw + )); + let outside = "--- a/../external.txt\n+++ b/../external.txt\n@@ -1 +1 @@\n-before\n+after\n"; + assert!(repo.patch_file_diff(outside, "../external.txt", &encoding).is_err()); + assert_eq!(std::fs::read(fx.dir.join(".git/index")).unwrap(), original_index); + assert_eq!(fx.read("clean.txt"), "original\n"); + assert_eq!(fx.read("conflict.txt"), "ours\n"); + assert_eq!(fx.read("delete.txt"), "removed\n"); + assert!(fx.exists("old-name.txt")); + assert!(!fx.exists("new-name.txt")); + assert!(!fx.exists("add.txt")); +} + +#[test] +fn applying_selected_patch_files_keeps_renames_and_binary_data() { + let fx = Fixture::new(); + let from = "before [1].txt"; + let to = "after [1].txt"; + fx.write(from, "rename this file\n"); + fx.write("keep.txt", "original\n"); + std::fs::write(fx.dir.join("data.bin"), [0, 1, 255]).unwrap(); + let before = fx.commit_all("initial"); + fx.git(&["mv", from, to]); + fx.write("keep.txt", "from patch\n"); + std::fs::write(fx.dir.join("data.bin"), [0, 2, 255]).unwrap(); + let after = fx.commit_all("rename, binary and text"); + let repo = fx.repo(); + let patch = repo.create_commits_patch(&[after], false).unwrap(); + fx.git(&["checkout", "--detach", &before]); + fx.write("keep.txt", "already staged\n"); + fx.git(&["add", "keep.txt"]); + assert!(repo.apply_selected_patch(&patch, &[]).is_err()); + assert!(repo.apply_selected_patch(&patch, &[to.to_owned(), "unknown.txt".into()]).is_err()); + assert!(fx.exists(from)); + assert!(!fx.exists(to)); + + let outcome = repo.apply_selected_patch(&patch, &[to.to_owned(), "data.bin".into()]).unwrap(); + assert_eq!(outcome.applied, [to, "data.bin"]); + assert!(outcome.conflicts.is_empty()); + assert!(!fx.exists(from)); + assert_eq!(fx.read(to), "rename this file\n"); + assert_eq!(std::fs::read(fx.dir.join("data.bin")).unwrap(), [0, 2, 255]); + assert_eq!(fx.read("keep.txt"), "already staged\n"); + assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "keep.txt"); + assert_eq!(fx.git(&["show", ":keep.txt"]), "already staged"); +} + +#[test] +fn stashed_untracked_files_have_their_own_revision() { + let fx = Fixture::new(); + fx.write("tracked.txt", "initial\n"); + fx.commit_all("initial"); + fx.write("tracked.txt", "stash tracked change\n"); + fx.write("untracked.txt", "stash untracked content\n"); + fx.git(&["stash", "push", "--include-untracked"]); + + let repo = fx.repo(); + let stashes = repo.stashes().unwrap(); + let untracked = stashes[0].untracked.as_deref().unwrap(); + let files = repo.commit_files(untracked).unwrap(); + assert_eq!(files.len(), 1); + assert_eq!(files[0].path, "untracked.txt"); + assert_eq!(files[0].kind, ChangeKind::Added); + assert!(!fx.exists("untracked.txt")); + + let empty = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"; + let patch = repo.create_revisions_patch(empty, untracked, &[PathBuf::from("untracked.txt")]).unwrap(); + repo.apply_patch(&patch).unwrap(); + assert_eq!(fx.read("untracked.txt"), "stash untracked content\n"); + assert_eq!(fx.read("tracked.txt"), "initial\n"); + assert_eq!(repo.stashes().unwrap().len(), 1); +} + #[test] fn push_new_branch_sets_upstream_and_detached_head_cannot() { let (fx, _bare) = Fixture::with_origin(); @@ -917,6 +2576,52 @@ fn branch_tips_are_reported() { // --------------------------------------------------------------------------- // Rollback +#[test] +fn stage_without_content_marks_an_untracked_file_without_adding_its_contents() { + let fx = Fixture::new(); + fx.write("base.txt", "base\n"); + fx.commit_all("base"); + fx.write("new [1].txt", "keep this text\n"); + let repo = fx.repo(); + repo.stage_without_content(&[fx.path("new [1].txt")]).unwrap(); + assert!(fx.git(&["diff", "--cached", "--name-only"]).trim().is_empty()); + let status = repo.status().unwrap(); + let file = status_of(&status, "new [1].txt").unwrap(); + assert_eq!(file.staged, None); + assert_eq!(file.unstaged, Some(ChangeKind::Added)); + assert_eq!(fx.read("new [1].txt"), "keep this text\n"); + assert!(repo.restore_unstaged(&[fx.path("new [1].txt")]).is_err()); + assert_eq!(fx.read("new [1].txt"), "keep this text\n"); + repo.stage(&[fx.path("new [1].txt")]).unwrap(); + assert_eq!(fx.git(&["diff", "--cached", "--name-only"]).trim(), "new [1].txt"); +} + +#[test] +fn restore_unstaged_keeps_the_index_and_other_worktree_changes() { + let fx = Fixture::new(); + fx.write("selected.txt", "base\n"); + fx.write("removed.txt", "initial\n"); + fx.write("other.txt", "before\n"); + fx.commit_all("base"); + fx.write("selected.txt", "staged\n"); + fx.write("removed.txt", "staged before local deletion\n"); + fx.git(&["add", "selected.txt", "removed.txt"]); + fx.write("selected.txt", "left in the worktree\n"); + fx.write("other.txt", "unrelated\n"); + std::fs::remove_file(fx.path("removed.txt")).unwrap(); + fx.write("untracked.txt", "keep me\n"); + let repo = fx.repo(); + let before = fx.git(&["diff", "--cached", "--binary"]); + assert!(repo.restore_unstaged(&[fx.path("selected.txt"), fx.path("untracked.txt")]).is_err()); + assert_eq!(fx.read("selected.txt"), "left in the worktree\n"); + repo.restore_unstaged(&[fx.path("selected.txt"), fx.path("removed.txt")]).unwrap(); + assert_eq!(fx.read("selected.txt"), "staged\n"); + assert_eq!(fx.read("removed.txt"), "staged before local deletion\n"); + assert_eq!(fx.read("other.txt"), "unrelated\n"); + assert_eq!(fx.read("untracked.txt"), "keep me\n"); + assert_eq!(before, fx.git(&["diff", "--cached", "--binary"])); +} + #[test] fn rollback_newly_added_file() { let fx = Fixture::new(); @@ -991,6 +2696,225 @@ fn rollback_conflicted_file_restores_head() { assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("merge")); } +#[test] +fn commit_crlf_checks_only_selected_content_without_a_git_policy() { + let fx = Fixture::new(); + fx.write(".gitattributes", "normalized.txt eol=lf\nintentional.txt -text\n"); + let original: String = (1..=30).map(|i| format!("line {i}\n")).collect(); + fx.write("partial.txt", &original); + fx.write("retained.txt", &original.replace('\n', "\r\n")); + fx.write("staged.txt", "base\n"); + fx.write("unstaged.txt", "base\n"); + fx.commit_all("base"); + + fx.write("staged.txt", "selected\r\n"); + fx.write("unstaged.txt", "staged LF\n"); + fx.git(&["add", "staged.txt", "unstaged.txt"]); + std::fs::remove_file(fx.path("staged.txt")).unwrap(); + fx.write("unstaged.txt", "unselected CRLF\r\n"); + fx.write("normalized.txt", "normalized\r\n"); + fx.write("intentional.txt", "intentional\r\n"); + fx.write("new file.txt", "new\r\n"); + fx.write("binary.dat", "binary\0\r\n"); + let edited = original.replace("line 2\n", "selected LF\n").replace("line 28\n", "CRLF\r\n"); + fx.write("partial.txt", &edited); + fx.write("retained.txt", &edited); + + let repo = fx.repo(); + let paths: Vec<_> = [ + "staged.txt", + "unstaged.txt", + "normalized.txt", + "intentional.txt", + "new file.txt", + "binary.dat", + "partial.txt", + "retained.txt", + ] + .map(|p| fx.path(p)) + .into(); + let hunks = diff_hunks(&original, &edited); + assert_eq!(hunks.len(), 2); + let options = |h: &LineHunk| CommitOptions { + partial: ["partial.txt", "retained.txt"] + .map(|path| PartialCommitFile { + prepared: None, + path: fx.path(path).into(), + line_hunks: vec![], + hunks: vec![HunkRange { + start: h.start, + lines: h.lines, + old_start: h.old_start, + old_lines: h.old_lines, + }], + }) + .into(), + stage: ["normalized.txt", "intentional.txt", "new file.txt", "binary.dat"].map(|p| fx.path(p).into()).into(), + ..Default::default() + }; + let check = |options: CommitOptions| { + repo.commit_crlf_paths(&paths, &options, &|_| Ok(encoding_rs::UTF_8), &CancellationToken::new()) + .unwrap() + .into_iter() + .map(|p| p.0.file_name().unwrap().to_string_lossy().into_owned()) + .collect::>() + }; + let before = fx.git(&["diff", "--cached"]); + assert_eq!(check(options(&hunks[0])), ["new file.txt", "retained.txt", "staged.txt"]); + assert_eq!(check(options(&hunks[1])), ["new file.txt", "retained.txt", "staged.txt"]); + assert_eq!(fx.git(&["diff", "--cached"]), before); + for value in ["input", "yes", "1"] { + fx.git(&["config", "core.autocrlf", value]); + assert!(check(options(&hunks[1])).is_empty(), "core.autocrlf={value}"); + } +} + +#[test] +fn commit_large_files_checks_selected_sources_and_repository_lfs_config() { + let fx = Fixture::new(); + let original: String = (1..=30).map(|i| format!("l{i:02}\n")).collect(); + fx.write("partial.txt", &original); + fx.write("staged.bin", "base\n"); + fx.write("worktree.txt", "base\n"); + fx.write("disk-only.txt", "base\n"); + fx.commit_all("base"); + + std::fs::write(fx.path("staged.bin"), [0_u8; 219]).unwrap(); + fx.write("disk-only.txt", "small index\n"); + fx.git(&["add", "staged.bin", "disk-only.txt"]); + std::fs::remove_file(fx.path("staged.bin")).unwrap(); + fx.write("worktree.txt", &"a".repeat(198)); + fx.write("disk-only.txt", &"b".repeat(250)); + fx.write("outside-selection.txt", &"c".repeat(300)); + let long_line = format!("{}\n", "字".repeat(70)); + let edited = original.replace("l02\n", &long_line).replace("l29\n", "small change\n"); + fx.write("partial.txt", &edited); + + let repo = fx.repo(); + let paths = ["staged.bin", "worktree.txt", "disk-only.txt", "partial.txt"].map(|p| fx.path(p)); + let hunks = diff_hunks(&original, &edited); + assert_eq!(hunks.len(), 2); + let options = |h: &LineHunk| CommitOptions { + partial: vec![PartialCommitFile { + prepared: None, + path: fx.path("partial.txt").into(), + line_hunks: vec![], + hunks: vec![HunkRange { start: h.start, lines: h.lines, old_start: h.old_start, old_lines: h.old_lines }], + }], + stage: vec![fx.path("worktree.txt").into()], + ..Default::default() + }; + let check = |options: CommitOptions, limit| { + repo.commit_large_files(&paths, &options, limit, &|_| Ok(encoding_rs::UTF_8), &CancellationToken::new()) + .unwrap() + .into_iter() + .map(|file| (file.path.0.file_name().unwrap().to_string_lossy().into_owned(), file.size)) + .collect::>() + }; + let before = fx.git(&["diff", "--cached", "--raw"]); + assert_eq!(check(options(&hunks[1]), 160), [(String::from("staged.bin"), 219), ("worktree.txt".into(), 198)]); + assert_eq!( + check(options(&hunks[0]), 198), + [("staged.bin".into(), 219), ("partial.txt".into(), (original.len() - 4 + long_line.len()) as u64)] + ); + assert_eq!(fx.git(&["diff", "--cached", "--raw"]), before); + fx.git(&["config", "lfs.repositoryformatversion", "0"]); + assert!(check(options(&hunks[0]), 160).is_empty()); +} + +#[test] +fn staging_formatter_edits_uses_the_selected_index_text() { + let fx = Fixture::new(); + fx.write("format.ts", "const value = 1;\r\n"); + fx.commit_all("base"); + fx.write("format.ts", "const value=2;\r\n"); + fx.git(&["add", "format.ts"]); + fx.write("format.ts", "const other = 3;\r\n"); + let repo = fx.repo(); + let path = fx.path("format.ts"); + let before = "const value=2;\n"; + let formatted = "const value = 2;\n"; + repo.stage_formatted_text(&path, before, formatted, encoding_rs::UTF_8).unwrap(); + assert_eq!(repo.file_bytes_at(&path, Some(":0")).unwrap().unwrap(), b"const value = 2;\r\n"); + assert_eq!(fx.read("format.ts"), "const other = 3;\r\n"); + assert!(repo.stage_formatted_text(&path, before, formatted, encoding_rs::UTF_8).is_err()); +} + +#[test] +fn staging_line_hunks_read_the_renamed_index_and_unsaved_working_text() { + let fx = Fixture::new(); + fx.write("before.txt", "one\nhead\nkeep\n"); + fx.commit_all("base"); + fx.git(&["mv", "before.txt", "after.txt"]); + fx.write("after.txt", "one\nindex\nkeep\n"); + fx.git(&["add", "after.txt"]); + let repo = fx.repo(); + let path = fx.path("after.txt"); + let snapshot = repo + .staging_line_hunks(&path, Some(&fx.path("before.txt")), "one\nunsaved\nkeep\n", 1024, |_, _| { + encoding_rs::UTF_8.into() + }) + .unwrap() + .unwrap(); + assert_eq!(snapshot.hunks.len(), 1); + let change = &snapshot.hunks[0]; + assert!(change.staged && change.unstaged); + assert_eq!(change.head_text, "head\n"); + assert_eq!(change.index_text, "index\n"); + assert_eq!( + snapshot.index_version, + repo.staged_text(&path, 1024, |_| encoding_rs::UTF_8.into()).unwrap().unwrap().version + ); + assert_eq!(fx.read("after.txt"), "one\nindex\nkeep\n"); +} + +#[test] +fn editing_staged_text_keeps_worktree_encoding_mode_and_other_entries() { + let fx = Fixture::new(); + let path = fx.path("run.txt"); + let utf16 = + |text: &str| [0xff, 0xfe].into_iter().chain(text.encode_utf16().flat_map(u16::to_le_bytes)).collect::>(); + std::fs::write(&path, utf16("staged\r\nkeep\n")).unwrap(); + fx.write("other.txt", "original\n"); + fx.commit_all("base"); + fx.git(&["update-index", "--chmod=+x", "run.txt"]); + fx.write("run.txt", "working copy\n"); + let repo = fx.repo(); + let encoding = |_: &[u8]| encoding_rs::UTF_16LE.into(); + assert!(repo.staged_text(&path, 3, |_| panic!("large blobs are skipped before decoding")).unwrap().is_none()); + let opened = repo.staged_text(&path, 1024, encoding).unwrap().unwrap(); + assert_eq!(opened.text, "staged\nkeep\n"); + + fx.write("other.txt", "staged separately\n"); + fx.git(&["add", "other.txt"]); + let next = repo.save_staged_text(&path, &opened.version, "edited\nkeep\n", encoding).unwrap(); + assert_ne!(opened.version, next); + assert_eq!(repo.file_mode_at(&path, Some(":0")).unwrap().as_deref(), Some("100755")); + assert_eq!(repo.file_bytes_at(&path, Some(":0")).unwrap().unwrap(), utf16("edited\r\nkeep\n")); + assert_eq!(fx.read("run.txt"), "working copy\n"); + assert_eq!(fx.git(&["show", ":other.txt"]), "staged separately"); + + let error = repo.save_staged_text(&path, &opened.version, "obsolete\n", encoding).unwrap_err(); + assert_eq!(error.kind, ide_core::error::ErrorKind::OutOfSync); + assert_eq!(repo.staged_text(&path, 1024, encoding).unwrap().unwrap().version, next); +} + +#[test] +fn editing_staged_text_rejects_an_index_that_git_is_updating() { + let fx = Fixture::new(); + fx.write("a.txt", "one\n"); + fx.commit_all("base"); + let path = fx.path("a.txt"); + let repo = fx.repo(); + let encoding = |_: &[u8]| encoding_rs::UTF_8.into(); + let opened = repo.staged_text(&path, 1024, encoding).unwrap().unwrap(); + let lock = fx.path(".git/index.lock"); + std::fs::write(&lock, "another writer").unwrap(); + assert!(repo.save_staged_text(&path, &opened.version, "two\n", encoding).is_err()); + assert_eq!(std::fs::read_to_string(lock).unwrap(), "another writer"); + assert_eq!(fx.git(&["show", ":a.txt"]), "one"); +} + #[test] fn rollback_hunk_via_partial_patch_leaves_other_hunks() { let fx = Fixture::new(); @@ -1088,6 +3012,119 @@ fn branch_overwrite_preserves_the_ref_if_checkout_fails() { assert_eq!(fx.git(&["rev-parse", "HEAD"]), tip); } +#[test] +fn scoped_rebase_checks_the_target_and_the_branch_for_rollback() { + let fx = Fixture::new(); + fx.write("base.txt", "base\n"); + let base = fx.commit_all("base"); + fx.git(&["switch", "-qc", "integration"]); + fx.write("target.txt", "integration\n"); + let onto = fx.commit_all("integration"); + fx.git(&["tag", "integration", &base]); + fx.git(&["switch", "-q", "main"]); + fx.write("local.txt", "local\n"); + let original = fx.commit_all("local"); + let repo = fx.repo(); + let cancel = CancellationToken::new(); + let out = |_| {}; + let plan = BranchRebasePlan { + head: HistoryTip { branch: Some("main".into()), commit: original.clone() }, + target: "refs/heads/integration".into(), + onto: onto.clone(), + }; + + let stale = BranchRebasePlan { onto: base, ..plan.clone() }; + assert!(repo.rebase_branch(&stale, &cancel, &out).is_err()); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), original); + + let rebased = repo.rebase_branch(&plan, &cancel, &out).unwrap(); + assert_eq!(rebased.branch.as_deref(), Some("main")); + assert_eq!(fx.git(&["rev-parse", "HEAD^"]), onto); + assert!(repo.branch_info().unwrap().rebase.is_none()); + fx.git(&["switch", "-qc", "same-tip"]); + assert!(repo.restore_head_on_branch(&original, &rebased.commit, Some("main")).is_err()); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), rebased.commit); + fx.git(&["switch", "-q", "main"]); + repo.restore_head_on_branch(&original, &rebased.commit, Some("main")).unwrap(); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), original); +} + +#[test] +fn rollback_branch_creation_restores_the_checkout_and_overwritten_branch() { + let fx = Fixture::new(); + fx.write("a.txt", "base\n"); + let base = fx.commit_all("base"); + let repo = fx.repo(); + repo.create_branch("topic", None, false).unwrap(); + fx.git(&["branch", "--set-upstream-to=main", "topic"]); + fx.write("a.txt", "main\n"); + let tip = fx.commit_all("main"); + let before = ide_vcs::HistoryTip { branch: Some("main".into()), commit: tip.clone() }; + + assert!(repo.create_branch_recorded("topic", None, true, true, Some(&tip)).is_err()); + assert_eq!(fx.git(&["rev-parse", "topic"]), base); + let created = repo.create_branch_recorded("topic", None, true, true, Some(&base)).unwrap(); + assert_eq!(created.tip, tip); + repo.undo_branch_creation("topic", &created, Some(&before)).unwrap(); + assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main")); + assert_eq!(fx.git(&["rev-parse", "topic"]), base); + assert_eq!(fx.git(&["rev-parse", "topic@{upstream}"]), tip); + + let created = repo.create_branch_recorded("new", Some(&base), true, false, None).unwrap(); + repo.undo_branch_creation("new", &created, Some(&before)).unwrap(); + assert!(!repo.branches().unwrap().iter().any(|branch| branch.name == "new")); + assert_eq!(fx.read("a.txt"), "main\n"); + + let created = repo.create_branch_recorded("advanced", Some(&base), false, false, None).unwrap(); + fx.git(&["branch", "--force", "advanced", &tip]); + assert!(repo.undo_branch_creation("advanced", &created, None).is_err()); + assert_eq!(fx.git(&["rev-parse", "advanced"]), tip); +} + +#[test] +fn new_branch_smart_checkout_preserves_local_edits_in_both_directions() { + let fx = Fixture::new(); + fx.write("f.txt", "1\n2\n3\n4\n5\n"); + let base = fx.commit_all("base"); + fx.git(&["switch", "-q", "-c", "source"]); + fx.write("f.txt", "1\nsource\n3\n4\n5\n"); + let source = fx.commit_all("source"); + fx.git(&["switch", "-q", "main"]); + fx.write("f.txt", "1\n2\n3\n4\nlocal\n"); + fx.git(&["add", "--", "f.txt"]); + fx.write("f.txt", "1\n2\n3\n4\nlocal\nunstaged\n"); + let repo = fx.repo(); + let normal = CheckoutOptions::default(); + let blocked = repo.create_branch_with("new", Some("refs/heads/source"), Some(&normal), false, None).unwrap(); + assert_eq!(blocked.checkout, CheckoutOutcome::LocalChanges { files: vec!["f.txt".into()] }); + assert!(blocked.created.is_none()); + assert!(!repo.branches().unwrap().iter().any(|branch| branch.name == "new")); + + let smart = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() }; + let outcome = repo.create_branch_with("new", Some("refs/heads/source"), Some(&smart), false, None).unwrap(); + assert_eq!(outcome.checkout, CheckoutOutcome::Done); + let receipt = outcome.created.unwrap(); + assert_eq!(receipt.tip, source); + assert_eq!(fx.read("f.txt"), "1\nsource\n3\n4\nlocal\nunstaged\n"); + assert_eq!(fx.git(&["show", ":f.txt"]), "1\nsource\n3\n4\nlocal"); + assert!(repo.stashes().unwrap().is_empty()); + + repo.undo_branch_creation("new", &receipt, Some(&HistoryTip { branch: Some("main".into()), commit: base })) + .unwrap(); + assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main")); + assert_eq!(fx.read("f.txt"), "1\n2\n3\n4\nlocal\nunstaged\n"); + assert_eq!(fx.git(&["show", ":f.txt"]), "1\n2\n3\n4\nlocal"); + assert!(!repo.branches().unwrap().iter().any(|branch| branch.name == "new")); + assert!(repo.stashes().unwrap().is_empty()); + + fx.git(&["reset", "-q", "HEAD", "--", "f.txt"]); + fx.write("f.txt", "1\nlocal\n3\n4\n5\n"); + let conflicted = repo.create_branch_with("conflict", Some(&source), Some(&smart), false, None).unwrap(); + assert_eq!(conflicted.checkout, CheckoutOutcome::Conflicts { files: vec!["f.txt".into()] }); + assert_eq!(conflicted.created.unwrap().tip, source); + assert_eq!(repo.stashes().unwrap().len(), 1); +} + #[test] fn new_branch_from_remote_branch_tracks_it_only_under_the_same_name() { let (fx, bare) = Fixture::with_origin(); @@ -1304,6 +3341,8 @@ fn local_changes_come_back_once_a_stopped_rebase_is_continued() { fx.write("f3.txt", "3\nmore\n"); fx.commit_all("c5"); let c5 = fx.git(&["rev-parse", "HEAD"]); + fx.write("f1.txt", "external copy\n"); + let external = fx.git(&["stash", "create"]); fx.write("f1.txt", "staged\n"); fx.git(&["add", "f1.txt"]); let result = repo.interactive_rebase( @@ -1319,13 +3358,144 @@ fn local_changes_come_back_once_a_stopped_rebase_is_continued() { assert!(result.is_err()); assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("rebase")); assert_eq!(fx.read("f1.txt"), "1\n", "put aside while the rebase is stopped"); + let stash = repo.stashes().unwrap().remove(0); + fx.git(&["stash", "store", "-m", "external", &external]); + fx.git(&["stash", "store", "-m", "keep a copy", &stash.id]); + assert_eq!(repo.stashes().unwrap().len(), 3); fx.write("f3.txt", "3\nmore\n"); repo.stage(&[fx.path("f3.txt")]).unwrap(); repo.continue_operation(&cancel, &out).unwrap(); assert_eq!(repo.branch_info().unwrap().operation, None); assert_eq!(fx.read("f1.txt"), "staged\n"); assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "f1.txt"); - assert!(fx.git(&["stash", "list"]).is_empty()); + assert!(matches!( + repo.stashes().unwrap().as_slice(), + [entry, other] if entry.id == stash.id && entry.message == "keep a copy" && other.id == external + )); +} + +#[test] +fn rebase_restores_its_shelf_after_garbage_collection_and_a_settings_change() { + let fx = Fixture::new(); + fx.write("shared.txt", "base\n"); + fx.write("local.txt", "base\n"); + fx.commit_all("base"); + fx.git(&["switch", "-qc", "other"]); + fx.write("shared.txt", "other\n"); + fx.commit_all("other edit"); + fx.git(&["switch", "-q", "main"]); + fx.write("shared.txt", "main\n"); + fx.commit_all("main edit"); + fx.write("local.txt", "staged\n"); + fx.git(&["add", "local.txt"]); + let repo = fx.repo(); + let shelf_dir = fx.path(".openidea/shelf"); + repo.set_automatic_shelf(Some(shelf_dir.clone()), None); + let (cancel, out) = quiet(); + assert!(repo.rebase("other").is_err()); + assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("rebase")); + assert_eq!(fx.read("local.txt"), "base\n"); + assert!(repo.stashes().unwrap().is_empty()); + let entries = shelf::list(&shelf_dir).unwrap(); + assert_eq!(entries.len(), 1); + let marker: serde_json::Value = serde_json::from_str(&fx.read(".git/openidea-saved-changes")).unwrap(); + let snapshot = marker["snapshot"].as_str().unwrap(); + fx.git(&["gc", "--prune=now"]); + assert!(!fx.git(&["rev-list", "--all"]).lines().any(|id| id == snapshot)); + assert!(!Command::new("git").current_dir(&fx.dir).args(["cat-file", "-e", snapshot]).status().unwrap().success()); + + let reopened = fx.repo(); // The settings now select Stash. + reopened.skip_operation(&cancel, &out).unwrap(); + assert_eq!(reopened.branch_info().unwrap().operation, None); + assert_eq!(fx.git(&["show", ":local.txt"]), "staged"); + assert!(shelf::list(&shelf_dir).unwrap().is_empty()); + assert!(!fx.exists(".git/openidea-saved-changes")); +} + +fn pause_rebase_with_grouped_shelves() -> (Fixture, PathBuf) { + let fx = Fixture::new(); + for file in ["shared.txt", "keep.txt", "discard-file.txt", "discard-list.txt", "rename-old.txt"] { + fx.write(file, "base\n"); + } + fx.commit_all("base"); + fx.git(&["switch", "-qc", "other"]); + fx.write("shared.txt", "other\n"); + fx.commit_all("other"); + fx.git(&["switch", "-q", "main"]); + fx.write("shared.txt", "main\n"); + fx.commit_all("main"); + fx.write("keep.txt", "staged\n"); + fx.git(&["add", "keep.txt"]); + fx.write("keep.txt", "base\n"); + fx.write("discard-file.txt", "discard one file\n"); + fx.write("discard-list.txt", "discard the list\n"); + fx.git(&["mv", "rename-old.txt", "rename-new.txt"]); + + let project = fx.tmp.path(); + let shelf_dir = ide_core::project_dir::path(project, "shelf"); + let mut lists = ChangelistState::initial(); + lists.lists.push(Changelist { + id: "discard".into(), + name: "Discard".into(), + comment: String::new(), + applied_commit: None, + }); + lists.files.insert("work/discard-list.txt".into(), "discard".into()); + lists.files.insert("work/rename-new.txt".into(), "discard".into()); + changelists::save(&ide_core::project_dir::path(project, "changelists.json"), &lists).unwrap(); + let repo = fx.repo(); + repo.set_automatic_shelf(Some(shelf_dir.clone()), Some(project.to_path_buf())); + assert!(repo.rebase("other").is_err()); + assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("rebase")); + (fx, shelf_dir) +} + +#[test] +fn rebase_shelves_changelists_separately_and_restores_only_retained_files() { + let (fx, shelf_dir) = pause_rebase_with_grouped_shelves(); + let entries = shelf::list(&shelf_dir).unwrap(); + assert_eq!(entries.len(), 2); + let discard = entries.iter().find(|entry| entry.name.starts_with("[Discard] ")).unwrap(); + assert_eq!( + discard.files.iter().map(|file| file.path.as_str()).collect::>(), + ["discard-list.txt", "rename-new.txt", "rename-old.txt"] + ); + let changes = entries.iter().find(|entry| entry.name.starts_with("[Changes] ")).unwrap(); + assert_eq!(changes.files.len(), 2); + shelf::delete(&shelf_dir, &discard.id).unwrap(); + shelf::delete_path(&shelf_dir, &changes.id, Some("discard-file.txt")).unwrap(); + fx.git(&["gc", "--prune=now"]); + + let (cancel, out) = quiet(); + fx.repo().skip_operation(&cancel, &out).unwrap(); + assert_eq!(fx.git(&["show", ":keep.txt"]), "staged"); + for file in ["keep.txt", "discard-file.txt", "discard-list.txt", "rename-old.txt"] { + assert_eq!(fx.read(file), "base\n"); + } + assert!(!fx.exists("rename-new.txt")); + assert!(shelf::list(&shelf_dir).unwrap().is_empty()); + assert!(std::fs::read_dir(&shelf_dir).unwrap().all(|entry| entry.unwrap().file_name() == ".gitignore")); +} + +#[test] +fn rebase_keeps_shelves_and_archive_if_a_group_cannot_be_read_as_a_patch() { + let (fx, shelf_dir) = pause_rebase_with_grouped_shelves(); + let entries = shelf::list(&shelf_dir).unwrap(); + let patch = shelf_dir.join(&entries[0].id).join("shelved.patch"); + std::fs::write(&patch, "incomplete patch").unwrap(); + + let (cancel, out) = quiet(); + let error = fx.repo().skip_operation(&cancel, &out).unwrap_err(); + assert!(error.message.contains("no file changes found")); + assert_eq!(std::fs::read_to_string(patch).unwrap(), "incomplete patch"); + assert_eq!(shelf::list(&shelf_dir).unwrap().len(), 2); + assert!( + std::fs::read_dir(&shelf_dir).unwrap().any(|entry| entry + .unwrap() + .file_name() + .to_string_lossy() + .starts_with(".snapshot-")) + ); } #[test] diff --git a/crates/ide-vcs/tests/history_ops.rs b/crates/ide-vcs/tests/history_ops.rs index 54ce0dd32..12c9b1400 100644 --- a/crates/ide-vcs/tests/history_ops.rs +++ b/crates/ide-vcs/tests/history_ops.rs @@ -1,7 +1,7 @@ //! Rebase / cherry-pick / revert / reset / tags, the shelf and patches, against //! throwaway repositories created with the git CLI. -use ide_core::CancellationToken; +use ide_core::{CancellationToken, workflow_settings::EmptyCherryPickAction}; use ide_vcs::*; use std::path::{Path, PathBuf}; use std::process::Command; @@ -127,6 +127,9 @@ fn merge_versions_put_the_users_work_on_the_left() { assert_eq!(v.sides.commit.as_deref(), Some(&topic[..8])); // The merged text puts the user's side first, whatever git's stage order. assert_eq!(v.merged.as_deref(), Some("<<<<<<< yours\ntopic\n||||||| base\nbase\n=======\nmain\n>>>>>>> theirs\n")); + repo.accept_conflict_side(&[fx.path("f.txt")], ConflictSide::Ours).unwrap(); + assert_eq!(fx.read("f.txt"), "topic\n"); + assert_eq!(fx.git(&["show", ":f.txt"]), "topic"); let (cancel, out) = quiet(); repo.abort_operation(&cancel, &out).unwrap(); @@ -188,6 +191,19 @@ fn rebase_conflict_then_abort_and_skip() { assert!(repo.abort_operation(&cancel, &out).is_err()); } +#[test] +fn rebase_abort_does_not_abort_a_different_operation() { + let fx = diverged(); + let repo = fx.repo(); + let (cancel, out) = quiet(); + assert!(repo.merge("main").is_err()); + let error = repo.abort_expected_operation(Some("rebase"), &cancel, &out).unwrap_err(); + assert_eq!(error.message, "Git operation changed before it could be aborted"); + assert_eq!(repo.operation().unwrap().as_deref(), Some("merge")); + repo.abort_expected_operation(Some("merge"), &cancel, &out).unwrap(); + assert_eq!(repo.operation().unwrap(), None); +} + #[test] fn merge_conflict_continue_commits() { let fx = diverged(); @@ -204,6 +220,37 @@ fn merge_conflict_continue_commits() { assert_eq!(fx.git(&["rev-list", "--count", "--merges", "HEAD"]), "1"); } +#[test] +fn finish_merge_checks_the_reviewed_heads_and_uses_the_prepared_message() { + let fx = diverged(); + fx.git(&["checkout", "-q", "main"]); + let repo = fx.repo(); + let (cancel, out) = quiet(); + let head = fx.git(&["rev-parse", "HEAD"]); + let target = fx.git(&["rev-parse", "topic"]); + assert!(repo.merge("topic").is_err()); + assert!( + repo.finish_merge(Some("main"), &head, &target, &cancel, &out).is_err(), + "unresolved files block finishing" + ); + fx.write("f.txt", "resolved\n"); + repo.stage(&[fx.path("f.txt")]).unwrap(); + + for (branch, before, incoming) in + [(Some("topic"), &head, &target), (Some("main"), &target, &target), (Some("main"), &head, &head)] + { + let error = repo.finish_merge(branch, before, incoming, &cancel, &out).unwrap_err(); + assert_eq!(error.message, "The merge changed before it could be finished"); + } + assert_eq!(fx.git(&["rev-parse", "HEAD"]), head); + assert_eq!(fx.git(&["rev-parse", "MERGE_HEAD"]), target); + + repo.finish_merge(Some("main"), &head, &target, &cancel, &out).unwrap(); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["log", "-1", "--format=%s%n%P"]), format!("Merge branch 'topic'\n{head} {target}")); + assert_eq!(fx.git(&["show", "HEAD:f.txt"]), "resolved"); +} + #[test] fn cherry_pick_and_conflicting_cherry_pick() { let fx = diverged(); @@ -244,6 +291,411 @@ fn revert_creates_inverse_commit() { assert_eq!(fx.git(&["rev-list", "--count", "HEAD"]), "3"); } +fn mixed_cherry_pick_fixture() -> (Fixture, [String; 3]) { + let fx = Fixture::new(); + fx.write("f.txt", "base\n"); + fx.commit_all("base"); + fx.git(&["checkout", "-q", "-b", "topic"]); + fx.write("setup.txt", "setup\n"); + let setup = fx.commit_all("published setup"); + fx.write("f.txt", "topic\n"); + let edit = fx.commit_all("published edit"); + fx.write("followup.txt", "local\n"); + let local = fx.commit_all("local follow-up"); + fx.git(&["checkout", "-q", "main"]); + fx.write("f.txt", "main\n"); + fx.commit_all("main edit"); + (fx, [setup, edit, local]) +} + +#[test] +fn mixed_cherry_pick_keeps_per_commit_origins_when_resumed() { + let (fx, picks) = mixed_cherry_pick_fixture(); + let (cancel, out) = quiet(); + let repo = fx.repo(); + assert!(repo.cherry_pick_with_origins(&picks, &picks[..2], &cancel, &out).is_err()); + assert_eq!(repo.operation().unwrap().as_deref(), Some("cherry-pick")); + assert_eq!(fx.git(&["rev-parse", "CHERRY_PICK_HEAD"]), picks[1]); + assert!(!fx.path("followup.txt").exists()); + drop(repo); + + let repo = fx.repo(); + fx.write("f.txt", "resolved\n"); + repo.stage(&[fx.path("f.txt")]).unwrap(); + repo.continue_operation(&cancel, &out).unwrap(); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["log", "-3", "--format=%s"]), "local follow-up\npublished edit\npublished setup"); + assert_eq!(fx.git(&["show", "-s", "--format=%b", "HEAD"]), ""); + assert_eq!(fx.git(&["show", "-s", "--format=%b", "HEAD~1"]), format!("(cherry picked from commit {})", picks[1])); + assert_eq!(fx.git(&["show", "-s", "--format=%b", "HEAD~2"]), format!("(cherry picked from commit {})", picks[0])); + assert!(!fx.path(".git/openidea-cherry-pick.json").exists()); +} + +#[test] +fn reviewed_formatting_keeps_the_index_transaction_scoped_and_preserves_worktree_edits() { + let (fx, picks) = mixed_cherry_pick_fixture(); + let (cancel, out) = quiet(); + let repo = fx.repo(); + assert!(repo.cherry_pick_with(&picks, true, &cancel, &out).is_err()); + fx.write("f.txt", "resolved \n"); + repo.stage(&[fx.path("f.txt")]).unwrap(); + fx.write("f.txt", "other unstaged edit\n"); + fx.write("local.txt", "unrelated work\n"); + let encoding = |_: &Path, _: &[u8]| encoding_rs::UTF_8.into(); + let edit = |file, formatted: &str| { + let path = fx.path(file); + let staged = repo.staged_text(&path, 1024, |_| encoding_rs::UTF_8.into()).unwrap().unwrap(); + StagedTextEdit { path: path.into(), version: staged.version, text: formatted.to_string() } + }; + + let review = repo.review_apply_commit(&cancel).unwrap().unwrap(); + let retained = + repo.format_reviewed_apply(&review.checkpoint, &[edit("f.txt", "main\n")], &cancel, encoding).unwrap(); + assert_eq!(retained, review); + assert_eq!(repo.review_apply_commit(&cancel).unwrap().unwrap(), review); + + fx.write("extra.txt", "staged \n"); + repo.stage(&[fx.path("extra.txt")]).unwrap(); + let review = repo.review_apply_commit(&cancel).unwrap().unwrap(); + let unrelated = edit("setup.txt", "not part of the review\n"); + assert!( + repo.format_reviewed_apply(&review.checkpoint, &[edit("f.txt", "resolved\n"), unrelated], &cancel, encoding) + .is_err() + ); + assert_eq!(repo.review_apply_commit(&cancel).unwrap().unwrap(), review); + + let mut stale = edit("extra.txt", "staged\n"); + stale.version.clear(); + assert!( + repo.format_reviewed_apply(&review.checkpoint, &[edit("f.txt", "resolved\n"), stale], &cancel, encoding) + .is_err() + ); + assert_eq!(repo.review_apply_commit(&cancel).unwrap().unwrap(), review); + + fx.write("extra.txt", "external staged edit\n"); + repo.stage(&[fx.path("extra.txt")]).unwrap(); + assert!(repo.format_reviewed_apply(&review.checkpoint, &[edit("f.txt", "resolved\n")], &cancel, encoding).is_err()); + let review = repo.review_apply_commit(&cancel).unwrap().unwrap(); + let formatted = + repo.format_reviewed_apply(&review.checkpoint, &[edit("f.txt", "resolved\n")], &cancel, encoding).unwrap(); + assert_ne!(review.checkpoint, formatted.checkpoint); + assert_eq!(review.paths, formatted.paths); + assert_eq!(repo.review_apply_commit(&cancel).unwrap().unwrap(), formatted); + assert_eq!(fx.git(&["show", ":extra.txt"]), "external staged edit"); + assert_eq!(fx.read("f.txt"), "other unstaged edit\n"); + assert_eq!(fx.read("local.txt"), "unrelated work\n"); + + assert!( + repo.continue_reviewed_apply( + &review.checkpoint, + &review.message, + &Default::default(), + Default::default(), + &cancel, + &out + ) + .is_err() + ); + repo.continue_reviewed_apply( + &formatted.checkpoint, + &formatted.message, + &Default::default(), + Default::default(), + &cancel, + &out, + ) + .unwrap(); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["show", "HEAD:f.txt"]), "resolved"); + assert_eq!(fx.read("f.txt"), "other unstaged edit\n"); +} + +#[test] +fn reviewed_cherry_pick_keeps_the_edited_message_and_resumes_both_kinds_of_queue() { + for mixed in [false, true] { + let (fx, picks) = mixed_cherry_pick_fixture(); + let (cancel, out) = quiet(); + let repo = fx.repo(); + let result = if mixed { + repo.cherry_pick_with_origins(&picks, &picks[..2], &cancel, &out) + } else { + repo.cherry_pick_with(&picks, true, &cancel, &out) + }; + assert!(result.is_err()); + fx.write("f.txt", "resolved\n"); + repo.stage(&[fx.path("f.txt")]).unwrap(); + let review = repo.review_apply_commit(&cancel).unwrap().unwrap(); + assert_eq!(review.kind, ide_vcs::CommitApplyKind::CherryPick); + assert_eq!(review.paths, [ide_core::IpcPath(fx.path("f.txt"))]); + let message = format!("Reviewed pick\n\n# Context\n{}", review.message); + let head = fx.git(&["rev-parse", "HEAD"]); + fx.write("local.txt", "unrelated work\n"); + let options = + ide_vcs::CommitOptions { stage: vec![ide_core::IpcPath(fx.path("local.txt"))], ..Default::default() }; + assert!(repo.commit_with("Ordinary commit", &options, &|_| Ok(encoding_rs::UTF_8)).is_err()); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), head); + assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "f.txt"); + assert_eq!(fx.git(&["rev-parse", "CHERRY_PICK_HEAD"]), picks[1]); + + fx.write("f.txt", "staged after opening the review\n"); + repo.stage(&[fx.path("f.txt")]).unwrap(); + assert!( + repo.continue_reviewed_apply( + &review.checkpoint, + &message, + &Default::default(), + Default::default(), + &cancel, + &out + ) + .is_err() + ); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), head); + assert_eq!(fx.git(&["rev-parse", "CHERRY_PICK_HEAD"]), picks[1]); + + let review = repo.review_apply_commit(&cancel).unwrap().unwrap(); + repo.continue_reviewed_apply( + &review.checkpoint, + &message, + &Default::default(), + Default::default(), + &cancel, + &out, + ) + .unwrap(); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["log", "-3", "--format=%s"]), "local follow-up\nReviewed pick\npublished setup"); + assert!(fx.git(&["show", "-s", "--format=%B", "HEAD~1"]).contains("# Context\npublished edit")); + assert!(fx.git(&["show", "-s", "--format=%B", "HEAD~1"]).contains(&picks[1])); + assert_eq!(fx.git(&["show", "-s", "--format=%b", "HEAD"]).contains(&picks[2]), !mixed); + assert!(!fx.path(".git/openidea-cherry-pick.json").exists()); + } +} + +#[test] +fn reviewed_revert_uses_the_current_author_and_continues_the_sequence() { + let fx = Fixture::new(); + fx.write("a.txt", "base\n"); + fx.write("local.txt", "clean\n"); + fx.commit_all("base"); + fx.write("other.txt", "delete this too\n"); + let other = fx.commit_all("other change"); + fx.write("a.txt", "incoming\n"); + fx.git(&["add", "a.txt"]); + fx.git(&[ + "commit", + "-qm", + "incoming change", + "--author=Author ", + "--date=2022-06-04T13:20:21+05:30", + ]); + let incoming = fx.git(&["rev-parse", "HEAD"]); + fx.write("a.txt", "local head\n"); + fx.commit_all("local head"); + fx.write("local.txt", "unrelated edit\n"); + let repo = fx.repo(); + let (cancel, out) = quiet(); + assert!(repo.revert(&[incoming.clone(), other], &cancel, &out).is_err()); + fx.write("a.txt", "reviewed resolution\n"); + repo.stage(&[fx.path("a.txt")]).unwrap(); + let review = repo.review_apply_commit(&cancel).unwrap().unwrap(); + assert_eq!(review.kind, ide_vcs::CommitApplyKind::Revert); + assert_eq!(review.paths, [ide_core::IpcPath(fx.path("a.txt"))]); + assert!(review.message.contains(&incoming)); + let head = fx.git(&["rev-parse", "HEAD"]); + assert!(repo.commit("Ordinary commit", false, false).is_err()); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), head); + assert_eq!(fx.git(&["rev-parse", "REVERT_HEAD"]), incoming); + repo.continue_reviewed_apply( + &review.checkpoint, + "Reviewed revert\n\n# Why", + &Default::default(), + Default::default(), + &cancel, + &out, + ) + .unwrap(); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["log", "-2", "--format=%s"]), "Revert \"other change\"\nReviewed revert"); + assert_eq!(fx.git(&["show", "-s", "--format=%B", "HEAD~1"]), "Reviewed revert\n\n# Why"); + assert_eq!( + fx.git(&["show", "-s", "--format=%an <%ae>", "HEAD~1"]), + fx.git(&["var", "GIT_AUTHOR_IDENT"]).split('>').next().unwrap().to_owned() + ">" + ); + assert_eq!(fx.git(&["status", "--short"]), "M local.txt"); +} + +#[test] +fn reviewed_commit_options_apply_only_to_the_paused_step() { + let (fx, picks) = mixed_cherry_pick_fixture(); + let repo = fx.repo(); + let (cancel, out) = quiet(); + assert!(repo.cherry_pick_with_origins(&picks[1..], &picks[1..2], &cancel, &out).is_err()); + fx.write("f.txt", "resolved\n"); + repo.stage(&[fx.path("f.txt")]).unwrap(); + fx.git(&["config", "core.hooksPath", ".git/hooks"]); + fx.write( + ".git/hooks/pre-commit", + "#!/bin/sh\nif git diff --cached --name-only -- f.txt | grep -qx f.txt; then\n echo ran >> .git/reviewed-hook-log\n exit 1\nfi\n", + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(fx.path(".git/hooks/pre-commit"), std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let review = repo.review_apply_commit(&cancel).unwrap().unwrap(); + assert!(review.author.is_some()); + assert!(review.author_date.is_some()); + assert!( + repo.continue_reviewed_apply( + &review.checkpoint, + &review.message, + &Default::default(), + Default::default(), + &cancel, + &out, + ) + .is_err() + ); + assert_eq!(fx.git(&["rev-parse", "CHERRY_PICK_HEAD"]), picks[1]); + assert_eq!(fx.read(".git/reviewed-hook-log"), "ran\n"); + let options = ide_vcs::ApplyCommitOptions { + author: Some("Reviewed Author ".into()), + author_date: Some("2024-06-04T13:20:21+05:30".into()), + sign_off: true, + run_hooks: false, + }; + repo.continue_reviewed_apply(&review.checkpoint, &review.message, &options, Default::default(), &cancel, &out) + .unwrap(); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["log", "-2", "--format=%s"]), "local follow-up\npublished edit"); + assert_eq!( + fx.git(&["show", "-s", "--format=%an <%ae>%n%aI", "HEAD^"]), + "Reviewed Author \n2024-06-04T13:20:21+05:30" + ); + let committer = fx.git(&["show", "-s", "--format=%cn <%ce>", "HEAD^"]); + assert!(fx.git(&["show", "-s", "--format=%B", "HEAD^"]).contains(&format!("Signed-off-by: {committer}"))); + assert!(!fx.git(&["show", "-s", "--format=%B", "HEAD"]).contains("Signed-off-by:")); + assert_eq!(fx.read(".git/reviewed-hook-log"), "ran\n"); +} + +#[test] +fn cherry_pick_continues_when_conflict_resolution_leaves_an_empty_commit() { + for action in [EmptyCherryPickAction::Skip, EmptyCherryPickAction::CreateEmpty] { + let (fx, picks) = mixed_cherry_pick_fixture(); + let (cancel, out) = quiet(); + let repo = fx.repo(); + let before = fx.git(&["rev-parse", "HEAD"]); + let options = CherryPickOptions { record_origin: true, empty_action: action, ..Default::default() }; + assert!(repo.cherry_pick_with_options(&picks[1..], options, &cancel, &out).is_err()); + assert_eq!(repo.operation().unwrap().as_deref(), Some("cherry-pick")); + fx.write("f.txt", "main\n"); + repo.stage(&[fx.path("f.txt")]).unwrap(); + + assert_eq!(repo.continue_operation_with(true, action, &cancel, &out).unwrap(), 1); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.read("f.txt"), "main\n"); + assert_eq!(fx.read("followup.txt"), "local\n"); + if action == EmptyCherryPickAction::CreateEmpty { + assert_eq!(fx.git(&["rev-parse", "HEAD~2"]), before); + assert_eq!(fx.git(&["rev-parse", "HEAD~1^{tree}"]), fx.git(&["rev-parse", "HEAD~2^{tree}"])); + assert_eq!( + fx.git(&["show", "-s", "--format=%B", "HEAD~1"]), + format!("published edit\n\n(cherry picked from commit {})", picks[1]), + ); + } else { + assert_eq!(fx.git(&["rev-parse", "HEAD~1"]), before); + } + } +} + +#[test] +fn a_native_cherry_pick_sequence_can_resume_after_its_empty_commit_was_saved() { + let (fx, picks) = mixed_cherry_pick_fixture(); + let (cancel, out) = quiet(); + let repo = fx.repo(); + assert!(repo.cherry_pick(&picks[1..], &cancel, &out).is_err()); + fx.write("f.txt", "main\n"); + repo.stage(&[fx.path("f.txt")]).unwrap(); + fx.git(&["commit", "--allow-empty", "--no-edit"]); + assert!(!fx.path(".git/CHERRY_PICK_HEAD").exists()); + assert!(fx.path(".git/sequencer/todo").exists()); + assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("cherry-pick")); + + repo.continue_operation(&cancel, &out).unwrap(); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.read("followup.txt"), "local\n"); +} + +#[test] +fn creating_an_empty_cherry_pick_after_resolution_continues_a_mixed_batch() { + let (fx, picks) = mixed_cherry_pick_fixture(); + let (cancel, out) = quiet(); + let action = EmptyCherryPickAction::CreateEmpty; + let options = CherryPickOptions { record_origin_for: &picks[..2], empty_action: action, ..Default::default() }; + assert!(fx.repo().cherry_pick_with_options(&picks, options, &cancel, &out).is_err()); + assert!(fx.path(".git/openidea-cherry-pick.json").exists()); + fx.write("f.txt", "main\n"); + let repo = fx.repo(); + repo.stage(&[fx.path("f.txt")]).unwrap(); + + assert_eq!(repo.continue_operation_with(false, action, &cancel, &out).unwrap(), 1); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["log", "-3", "--format=%s"]), "local follow-up\npublished edit\npublished setup"); + assert_eq!(fx.git(&["show", "-s", "--format=%b", "HEAD"]), ""); + assert_eq!(fx.git(&["show", "-s", "--format=%b", "HEAD~1"]), format!("(cherry picked from commit {})", picks[1])); + assert_eq!(fx.git(&["rev-parse", "HEAD~1^{tree}"]), fx.git(&["rev-parse", "HEAD~2^{tree}"])); + assert!(!fx.path(".git/openidea-cherry-pick.json").exists()); +} + +#[test] +fn aborting_a_mixed_cherry_pick_keeps_already_applied_commits() { + let (fx, picks) = mixed_cherry_pick_fixture(); + let (cancel, out) = quiet(); + let repo = fx.repo(); + assert!(repo.cherry_pick_with_origins(&picks, &picks[..2], &cancel, &out).is_err()); + assert!(fx.path(".git/openidea-cherry-pick.json").exists()); + repo.abort_expected_operation(Some("cherry-pick"), &cancel, &out).unwrap(); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["log", "-2", "--format=%s"]), "published setup\nmain edit"); + assert_eq!(fx.read("f.txt"), "main\n"); + assert!(!fx.path("followup.txt").exists()); + assert!(!fx.path(".git/openidea-cherry-pick.json").exists()); +} + +#[test] +fn skipping_a_mixed_cherry_pick_conflict_still_applies_the_remaining_commits() { + let (fx, picks) = mixed_cherry_pick_fixture(); + let (cancel, out) = quiet(); + let repo = fx.repo(); + assert!(repo.cherry_pick_with_origins(&picks, &picks[1..2], &cancel, &out).is_err()); + repo.skip_operation(&cancel, &out).unwrap(); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["log", "-3", "--format=%s"]), "local follow-up\npublished setup\nmain edit"); + assert_eq!(fx.read("f.txt"), "main\n"); + assert_eq!(fx.read("followup.txt"), "local\n"); +} + +#[test] +fn a_cherry_pick_started_externally_does_not_resume_an_abandoned_batch() { + let (fx, picks) = mixed_cherry_pick_fixture(); + let (cancel, out) = quiet(); + let repo = fx.repo(); + assert!(repo.cherry_pick_with_origins(&picks, &picks[..2], &cancel, &out).is_err()); + fx.git(&["cherry-pick", "--abort"]); + fx.git(&["commit", "-q", "--allow-empty", "-m", "new HEAD"]); + let external = Command::new("git").current_dir(&fx.dir).args(["cherry-pick", &picks[1]]).output().unwrap(); + assert!(!external.status.success()); + assert_eq!(fx.git(&["rev-parse", "CHERRY_PICK_HEAD"]), picks[1]); + + fx.write("f.txt", "resolved externally\n"); + repo.stage(&[fx.path("f.txt")]).unwrap(); + repo.continue_operation(&cancel, &out).unwrap(); + assert_eq!(fx.git(&["log", "-2", "--format=%s"]), "published edit\nnew HEAD"); + assert!(!fx.path("followup.txt").exists()); + assert!(!fx.path(".git/openidea-cherry-pick.json").exists()); +} + #[test] fn reset_modes() { let fx = Fixture::new(); @@ -435,6 +887,97 @@ fn create_and_apply_patches() { assert!(repo.patch_preview("not a patch\n").is_err()); } +#[test] +fn staging_patch_exports_only_the_chosen_sides() { + let fx = Fixture::new(); + for file in ["staged.txt", "local.txt", "both.txt", "outside.txt", "rename me.txt"] { + fx.write(file, "HEAD line\n"); + } + fx.commit_all("base"); + for file in ["staged.txt", "local.txt", "both.txt", "outside.txt"] { + fx.write(file, "index line\n"); + } + fx.git(&["add", "."]); + fx.git(&["mv", "rename me.txt", "renamed.txt"]); + for file in ["staged.txt", "local.txt", "both.txt", "outside.txt", "renamed.txt"] { + fx.write(file, "working line\n"); + } + fx.write("new.txt", "untracked text\n"); + fx.write("binary.bin", "\0binary bytes\n"); + let repo = fx.repo(); + let entry = |path, side, renamed_from: Option<&str>| StagingPatchEntry { + path: fx.path(path).into(), + renamed_from: renamed_from.map(|old| fx.path(old).into()), + side, + }; + use StagingPatchSide::{Staged, Unstaged}; + let entries = [ + entry("staged.txt", Staged, None), + entry("local.txt", Unstaged, None), + entry("both.txt", Staged, None), + entry("both.txt", Unstaged, None), + entry("renamed.txt", Staged, Some("rename me.txt")), + entry("new.txt", Unstaged, None), + entry("binary.bin", Unstaged, None), + ]; + let old_index = std::fs::read(fx.path(".git/index")).unwrap(); + let patch = repo.create_staging_patch(&entries, false, "repo/").unwrap(); + let block = |path| patch.split("diff --git ").find(|section| section.starts_with(path)).unwrap_or(""); + assert!(block("a/repo/staged.txt ").contains("-HEAD line\n+index line"), "{patch}"); + assert!(block("a/repo/local.txt ").contains("-index line\n+working line"), "{patch}"); + assert!(block("a/repo/both.txt ").contains("-HEAD line\n+working line"), "{patch}"); + assert_eq!(patch.matches("diff --git a/repo/both.txt ").count(), 1, "{patch}"); + assert!(patch.contains("rename from \"repo/rename me.txt\"\nrename to repo/renamed.txt"), "{patch}"); + assert!(block("a/repo/new.txt ").contains("+untracked text"), "{patch}"); + assert!(block("a/repo/binary.bin ").contains("GIT binary patch"), "{patch}"); + assert!(!patch.contains("outside.txt"), "{patch}"); + let reverse = repo.create_staging_patch(&entries, true, "repo/").unwrap(); + assert!(reverse.contains("diff --git a/repo/local.txt b/repo/local.txt"), "{reverse}"); + assert!(reverse.contains("-working line\n+index line"), "{reverse}"); + assert_eq!(std::fs::read(fx.path(".git/index")).unwrap(), old_index); + assert_eq!(fx.read("staged.txt"), "working line\n"); + assert_eq!(fx.read("new.txt"), "untracked text\n"); + + let target = Fixture::new(); + for (path, text) in [ + ("repo/staged.txt", "HEAD line\n"), + ("repo/local.txt", "index line\n"), + ("repo/both.txt", "HEAD line\n"), + ("repo/rename me.txt", "HEAD line\n"), + ] { + target.write(path, text); + } + target.commit_all("patch base"); + assert!(target.repo().apply_patch(&patch).unwrap().conflicts.is_empty()); + assert!(!target.path("repo/rename me.txt").exists()); + assert_eq!(target.read("repo/renamed.txt"), "HEAD line\n"); + assert_eq!(target.read("repo/both.txt"), "working line\n"); + assert_eq!(target.read("repo/binary.bin"), "\0binary bytes\n"); + assert!(target.repo().apply_patch(&reverse).unwrap().conflicts.is_empty()); + assert!(!target.path("repo/renamed.txt").exists()); + assert_eq!(target.read("repo/rename me.txt"), "HEAD line\n"); + assert_eq!(target.read("repo/local.txt"), "index line\n"); + assert!(!target.path("repo/binary.bin").exists()); +} + +#[test] +fn staging_patch_handles_unborn_head_and_an_index_with_intent_to_add() { + let fx = Fixture::new(); + fx.write("a.txt", "index\n"); + fx.git(&["add", "a.txt"]); + fx.write("a.txt", "working\n"); + fx.write("intent.txt", "intent to add\n"); + fx.git(&["add", "--intent-to-add", "intent.txt"]); + let entries = [ + StagingPatchEntry { path: fx.path("a.txt").into(), renamed_from: None, side: StagingPatchSide::Both }, + StagingPatchEntry { path: fx.path("intent.txt").into(), renamed_from: None, side: StagingPatchSide::Unstaged }, + ]; + let patch = fx.repo().create_staging_patch(&entries, false, "").unwrap(); + assert!(patch.contains("+working\n") && patch.contains("+intent to add\n"), "{patch}"); + assert!(!patch.contains("index\n"), "{patch}"); + assert_eq!(patch.matches("new file mode").count(), 2, "{patch}"); +} + #[test] fn patch_from_commits_applies_elsewhere() { let fx = Fixture::new(); @@ -568,16 +1111,16 @@ fn update_branches_fast_forwards_each_selected_branch() { fx.commit_all("one"); fx.git(&["remote", "add", "origin", bare.to_str().unwrap()]); fx.git(&["push", "-q", "-u", "origin", "main"]); - for b in ["behind", "diverged", "ahead", "same", "elsewhere"] { + for b in ["behind", "diverged", "ahead", "same", "elsewhere", "blocked"] { fx.git(&["push", "-q", "origin", &format!("main:{b}")]); fx.git(&["branch", "-q", "--track", b, &format!("origin/{b}")]); } fx.git(&["branch", "-q", "local-only"]); - // Someone else advances main, behind, diverged and elsewhere on the remote. + // Someone else advances the remote branches. let other = fx._tmp.path().join("other"); git_in(fx._tmp.path(), &["clone", "-q", bare.to_str().unwrap(), other.to_str().unwrap()]); let mut tips = std::collections::HashMap::new(); - for b in ["main", "behind", "diverged", "elsewhere"] { + for b in ["main", "behind", "diverged", "elsewhere", "blocked"] { git_in(&other, &["checkout", "-q", b]); std::fs::write(other.join("a.txt"), format!("{b}\n")).unwrap(); git_in(&other, &["-c", "user.name=O", "-c", "user.email=o@x", "commit", "-q", "-am", b]); @@ -591,14 +1134,18 @@ fn update_branches_fast_forwards_each_selected_branch() { fx.commit_all(b); } fx.git(&["checkout", "-q", "main"]); - // A branch checked out in another worktree is refused rather than moved under it. + // Linked worktrees fast-forward their files along with the ref. let wt = fx._tmp.path().join("wt"); fx.git(&["worktree", "add", "-q", wt.to_str().unwrap(), "elsewhere"]); + let dirty = fx._tmp.path().join("dirty"); + fx.git(&["worktree", "add", "-q", dirty.to_str().unwrap(), "blocked"]); + std::fs::write(dirty.join("a.txt"), "local working changes\n").unwrap(); + let blocked = fx.git(&["rev-parse", "blocked"]); let ahead = fx.git(&["rev-parse", "ahead"]); let repo = fx.repo(); let (cancel, out) = quiet(); - let names = ["main", "behind", "diverged", "ahead", "same", "local-only", "elsewhere"].map(String::from); + let names = ["main", "behind", "diverged", "ahead", "same", "local-only", "elsewhere", "blocked"].map(String::from); let result = repo.update_branches(&names, &cancel, &out).unwrap(); let status: Vec<_> = result.iter().map(|u| (u.branch.as_str(), u.status)).collect(); use BranchUpdateStatus::*; @@ -611,10 +1158,12 @@ fn update_branches_fast_forwards_each_selected_branch() { ("ahead", UpToDate), ("same", UpToDate), ("local-only", NoUpstream), - ("elsewhere", Failed), + ("elsewhere", Updated), + ("blocked", Failed), ] ); - assert!(result[6].message.as_deref().is_some_and(|m| m.contains("checked out")), "{:?}", result[6].message); + let failed_worktree = result[7].worktree.as_ref().unwrap(); + assert_eq!(dunce::canonicalize(&failed_worktree.0).unwrap(), dunce::canonicalize(&dirty).unwrap()); // The checked-out branch is fast-forwarded with its working tree. assert_eq!(fx.git(&["rev-parse", "main"]), tips["main"]); assert_eq!(fx.read("a.txt"), "main\n"); @@ -622,10 +1171,26 @@ fn update_branches_fast_forwards_each_selected_branch() { assert_eq!(fx.git(&["rev-parse", "origin/diverged"]), tips["diverged"]); assert_ne!(fx.git(&["rev-parse", "diverged"]), tips["diverged"]); assert_eq!(fx.git(&["rev-parse", "ahead"]), ahead); - assert_ne!(fx.git(&["rev-parse", "elsewhere"]), tips["elsewhere"]); + assert_eq!(fx.git(&["rev-parse", "elsewhere"]), tips["elsewhere"]); + assert_eq!(std::fs::read_to_string(wt.join("a.txt")).unwrap(), "elsewhere\n"); + assert_eq!(fx.git(&["rev-parse", "blocked"]), blocked); + assert_eq!(std::fs::read_to_string(dirty.join("a.txt")).unwrap(), "local working changes\n"); assert!(repo.update_branches(&["origin/main".into()], &cancel, &out).is_err()); } +#[test] +fn pull_refuses_to_update_a_different_checked_out_branch() { + let fx = Fixture::new(); + fx.write("a.txt", "before\n"); + fx.commit_all("initial"); + fx.write("a.txt", "uncommitted\n"); + let (cancel, out) = quiet(); + let error = fx.repo().pull_checked_branch(false, Some("topic"), &cancel, &out).unwrap_err(); + assert_eq!(error.message, "Branch 'topic' is no longer checked out"); + assert_eq!(fx.read("a.txt"), "uncommitted\n"); + assert!(fx.git(&["stash", "list"]).is_empty()); +} + #[test] fn update_branches_fetches_each_remote_once_and_reports_its_failure() { let fx = Fixture::new(); @@ -671,6 +1236,32 @@ fn update_branches_fetches_each_remote_once_and_reports_its_failure() { /// `"` and tabs are illegal in Windows file names, and only they make Git quote a path. const QUOTED: &str = if cfg!(windows) { "quote '.txt" } else { "quote\"\t.txt" }; +#[test] +fn shelf_capture_does_not_revert_edits_made_after_capture() { + let fx = Fixture::new(); + fx.write("a.txt", "base\n"); + fx.commit_all("base"); + fx.write("a.txt", "captured\n"); + let repo = fx.repo(); + let root = fx._tmp.path(); + let directory = root.join("shelf"); + let part = shelf::ShelfCapture::capture(&repo, root, &[fx.path("a.txt")]).unwrap(); + let entry = shelf::save_combined(&directory, root, "Shared", std::slice::from_ref(&part)).unwrap(); + fx.write("a.txt", "updated after capture\n"); + assert!(part.revert(&repo).unwrap_err().message.contains("Files changed while shelving")); + assert_eq!(fx.read("a.txt"), "updated after capture\n"); + assert!(shelf::patch_of(&directory, &entry.id).unwrap().contains("+captured")); + let selections = shelf::selections(&directory, &entry.id, None).unwrap(); + let diff = selections[0].diff_files(&repo).unwrap().remove(0); + assert_eq!(diff.before.as_deref(), Some("base\n")); + assert_eq!(diff.after.as_deref(), Some("captured\n")); + fx.write("a.txt", "captured\n"); + part.revert(&repo).unwrap(); + assert_eq!(fx.read("a.txt"), "base\n"); + assert_eq!(selections[0].apply(&repo).unwrap().applied, [diff.path]); + assert_eq!(fx.read("a.txt"), "captured\n"); +} + #[test] fn shelf_diff_and_scoped_operations_preserve_siblings() { let fx = Fixture::new(); @@ -782,13 +1373,53 @@ fn cherry_pick_skips_commits_already_applied() { let lines = std::sync::Mutex::new(Vec::new()); let out = |l: String| lines.lock().unwrap().push(l); - repo.cherry_pick_with(&[same.clone(), other], true, &cancel, &out).unwrap(); + let options = CherryPickOptions { record_origin: true, ..Default::default() }; + assert_eq!(repo.cherry_pick_with_options(&[same.clone(), other], options, &cancel, &out).unwrap(), 1); assert_eq!(repo.branch_info().unwrap().operation, None, "nothing left in progress"); assert_eq!(fx.git(&["log", "--format=%s", "-2"]), "other change\nsame change, made on main"); assert!(fx.git(&["log", "-1", "--format=%B"]).contains("(cherry picked from commit")); assert!(lines.lock().unwrap().iter().any(|l| l.starts_with(&same[..8]) && l.contains("skipped"))); } +#[test] +fn cherry_pick_can_keep_redundant_and_originally_empty_commits() { + let fx = Fixture::new(); + fx.write("a.txt", "base\n"); + fx.commit_all("base"); + fx.git(&["checkout", "-q", "-b", "topic"]); + fx.write("a.txt", "change\n"); + let redundant = fx.commit_all("original change"); + fx.git(&[ + "commit", + "-q", + "--allow-empty", + "--author=Original Author ", + "-m", + "originally empty", + ]); + let empty = fx.git(&["rev-parse", "HEAD"]); + fx.git(&["checkout", "-q", "main"]); + fx.write("a.txt", "change\n"); + let before = fx.commit_all("same change on main"); + fx.write("untracked.txt", "leave me alone\n"); + let (cancel, out) = quiet(); + let repo = fx.repo(); + let options = CherryPickOptions { + record_origin: true, + empty_action: EmptyCherryPickAction::CreateEmpty, + ..Default::default() + }; + + assert_eq!(repo.cherry_pick_with_options(&[redundant.clone(), empty.clone()], options, &cancel, &out).unwrap(), 2); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["rev-parse", "HEAD~2"]), before); + assert_eq!(fx.git(&["rev-parse", "HEAD^{tree}"]), fx.git(&["rev-parse", "HEAD~2^{tree}"])); + assert_eq!(fx.git(&["show", "-s", "--format=%an", "HEAD"]), "Original Author"); + assert_eq!(fx.git(&["show", "-s", "--format=%b", "HEAD"]), format!("(cherry picked from commit {empty})")); + assert_eq!(fx.git(&["show", "-s", "--format=%b", "HEAD~1"]), format!("(cherry picked from commit {redundant})")); + assert_eq!(fx.git(&["status", "--short"]), "?? untracked.txt"); +} + #[test] fn revert_of_a_commit_already_reverted_is_skipped() { let fx = Fixture::new(); diff --git a/crates/ide-vcs/tests/log_shape.rs b/crates/ide-vcs/tests/log_shape.rs index 7f0548166..bf9a5c70a 100644 --- a/crates/ide-vcs/tests/log_shape.rs +++ b/crates/ide-vcs/tests/log_shape.rs @@ -170,7 +170,7 @@ fn merge_with_options_and_rebase_onto() { git(dir, &["checkout", "-q", "-b", "topic", &base], None); commit(dir, "t.txt", "topic", 3000); - repo.rebase_with("main", &RebaseOptions::default()).unwrap(); + repo.rebase_with(Some("main"), &RebaseOptions::default()).unwrap(); assert_eq!(git(dir, &["rev-list", "--count", "main..topic"], None), "1"); assert_eq!(git(dir, &["merge-base", "main", "topic"], None), git(dir, &["rev-parse", "main"], None)); } diff --git a/crates/ide-vcs/tests/repo.rs b/crates/ide-vcs/tests/repo.rs index cb30efacc..00ab16702 100644 --- a/crates/ide-vcs/tests/repo.rs +++ b/crates/ide-vcs/tests/repo.rs @@ -1,7 +1,7 @@ //! End-to-end tests against throwaway repositories created with the git CLI. use ide_core::CancellationToken; -use ide_core::error::ErrorKind; +use ide_core::error::{ErrorData, ErrorKind}; use ide_vcs::*; use std::path::{Path, PathBuf}; use std::process::Command; @@ -299,7 +299,10 @@ fn ahead_behind_fetch_push_with_remote() { // Another clone pushes a commit to origin. let other = fx._tmp.path().join("other"); - git_in(fx._tmp.path(), &["clone", "-q", bare.to_str().unwrap(), other.to_str().unwrap()]); + git_in( + fx._tmp.path(), + &["clone", "-q", "-c", "core.autocrlf=false", bare.to_str().unwrap(), other.to_str().unwrap()], + ); configure(&other); std::fs::write(other.join("b.txt"), "remote\n").unwrap(); git_in(&other, &["add", "-A"]); @@ -356,6 +359,175 @@ fn ahead_behind_fetch_push_with_remote() { assert_eq!(info.upstream.as_deref(), Some("origin/feature")); } +#[test] +fn accept_conflict_side_preserves_binary_blob_mode_and_deletion() { + let fx = Fixture::new(); + let binary = fx.path("asset [1].bin"); + let gone = fx.path("gone.txt"); + std::fs::write(&binary, b"base\0\x80\n").unwrap(); + fx.write("gone.txt", "base\n"); + fx.write("asset 1.bin", "unchanged sibling\n"); + fx.commit_all("base"); + fx.git(&["branch", "other"]); + std::fs::write(&binary, b"ours\0\x81\n").unwrap(); + fx.write("gone.txt", "modified\n"); + fx.commit_all("ours"); + fx.git(&["switch", "other"]); + let incoming = b"theirs\0\x82\xff\r\n"; + std::fs::write(&binary, incoming).unwrap(); + // Keep the checkout's mode in step with the index so `core.fileMode` sees no local change. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + fx.git(&["rm", "gone.txt"]); + fx.git(&["--literal-pathspecs", "add", "--chmod=+x", "--", "asset [1].bin"]); + fx.git(&["commit", "-m", "theirs"]); + let blob = fx.git(&["rev-parse", "HEAD:asset [1].bin"]); + fx.git(&["switch", "main"]); + let repo = fx.repo(); + assert!(repo.merge("other").is_err()); + + let versions = repo.merge_versions(&binary, encoding_rs::UTF_8).unwrap(); + assert!(versions.binary && versions.merged.is_none()); + assert!(repo.accept_conflict_side(&[binary.clone(), fx.path("asset 1.bin")], ConflictSide::Theirs).is_err()); + assert_ne!(std::fs::read(&binary).unwrap(), incoming); + + let paths = [binary.clone(), gone.clone()]; + repo.accept_conflict_side(&paths, ConflictSide::Theirs).unwrap(); + assert_eq!(std::fs::read(&binary).unwrap(), incoming); + assert_eq!( + fx.git(&["--literal-pathspecs", "ls-files", "--stage", "--", "asset [1].bin"]), + format!("100755 {blob} 0\tasset [1].bin") + ); + assert!(!gone.exists()); + assert_eq!(fx.read("asset 1.bin"), "unchanged sibling\n"); + assert!(fx.git(&["ls-files", "-u"]).is_empty()); + assert_eq!(repo.resolved_conflicts().unwrap(), paths); + repo.revert_resolved_conflicts(&paths).unwrap(); + assert_eq!(fx.git(&["diff", "--name-only", "--diff-filter=U"]), "asset [1].bin\ngone.txt"); +} + +#[test] +fn manual_unstash_accepts_current_branch_for_yours_and_stash_for_theirs() { + for pop in [false, true] { + let fx = Fixture::new(); + let files = ["local-choice.txt", "stash-choice.txt"]; + for file in files { + fx.write(file, "base\n"); + } + fx.commit_all("base"); + for file in files { + fx.write(file, "stashed\n"); + } + fx.git(&["stash", "push"]); + for file in files { + fx.write(file, "current\n"); + } + fx.commit_all("current"); + let repo = fx.repo(); + let selected = repo.stashes().unwrap().remove(0); + assert_eq!( + repo.unstash_selected(&selected, pop, false, None).unwrap(), + StashApplyResult { index: 0, outcome: StashApplyOutcome::Conflicts { repository: repo.root().into() } } + ); + assert_eq!(repo.stashes().unwrap().len(), 1); + assert!(repo.unstash_selected(&selected, pop, false, None).is_err()); + for (file, side, expected) in + [(files[0], ConflictSide::Ours, "current"), (files[1], ConflictSide::Theirs, "stashed")] + { + let repo = fx.repo(); + let path = fx.path(file); + let versions = repo.merge_versions(&path, encoding_rs::UTF_8).unwrap(); + assert_eq!(versions.sides.operation.as_deref(), Some("stash-apply")); + assert!(!versions.sides.reversed); + assert_eq!(versions.ours.as_deref(), Some("current\n")); + assert_eq!(versions.theirs.as_deref(), Some("stashed\n")); + repo.accept_conflict_side(&[path], side).unwrap(); + assert_eq!(fx.git(&["show", &format!(":{file}")]), expected); + } + assert!(fx.git(&["ls-files", "-u"]).is_empty()); + } +} + +#[test] +fn resolved_conflict_survives_status_and_reopens_only_the_selected_file() { + let fx = Fixture::new(); + for file in ["file [1].txt", "file 1.txt", "untouched.txt"] { + fx.write(file, "base\n"); + } + fx.commit_all("base"); + fx.git(&["branch", "other"]); + for file in ["file [1].txt", "file 1.txt"] { + fx.write(file, "ours\n"); + } + fx.commit_all("ours"); + fx.git(&["switch", "other"]); + for file in ["file [1].txt", "file 1.txt"] { + fx.write(file, "theirs\n"); + } + fx.commit_all("theirs"); + fx.git(&["switch", "main"]); + let repo = fx.repo(); + assert!(repo.merge("other").is_err()); + let selected = fx.path("file [1].txt"); + let sibling = fx.path("file 1.txt"); + for file in ["file [1].txt", "file 1.txt"] { + fx.write(file, "resolved\n"); + } + repo.stage(&[selected.clone(), sibling.clone()]).unwrap(); + std::fs::File::options() + .write(true) + .open(fx.path("untouched.txt")) + .unwrap() + .set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(86400)) + .unwrap(); + let _ = repo.status().unwrap(); + let paths = repo.resolved_conflicts().unwrap(); + assert_eq!(paths, [sibling.clone(), selected.clone()]); + assert!(repo.revert_resolved_conflicts(&[selected.clone(), fx.path("untouched.txt")]).is_err()); + assert_eq!(fx.read("file [1].txt"), "resolved\n"); + + repo.revert_resolved_conflicts(std::slice::from_ref(&selected)).unwrap(); + assert_eq!(fx.git(&["diff", "--name-only", "--diff-filter=U"]), "file [1].txt"); + assert!(fx.read("file [1].txt").contains("<<<<<<<")); + assert_eq!(fx.read("file 1.txt"), "resolved\n"); + assert_eq!(repo.resolved_conflicts().unwrap(), [sibling]); + fx.write("file [1].txt", "resolved again\n"); + repo.stage(std::slice::from_ref(&selected)).unwrap(); + fx.git(&["commit", "-m", "merge"]); + assert!(repo.resolved_conflicts().unwrap().is_empty()); + assert!(repo.revert_resolved_conflicts(&[selected]).is_err()); +} + +#[test] +fn revert_resolved_modify_delete_conflicts_restores_either_surviving_side() { + let fx = Fixture::new(); + fx.write("ours.txt", "base\n"); + fx.write("theirs.txt", "base\n"); + fx.commit_all("base"); + fx.git(&["branch", "other"]); + fx.write("ours.txt", "our content\n"); + fx.git(&["rm", "theirs.txt"]); + fx.commit_all("ours"); + fx.git(&["switch", "other"]); + fx.write("theirs.txt", "their content\n"); + fx.git(&["rm", "ours.txt"]); + fx.commit_all("theirs"); + fx.git(&["switch", "main"]); + let repo = fx.repo(); + assert!(repo.merge("other").is_err()); + fx.git(&["rm", "ours.txt", "theirs.txt"]); + let paths = [fx.path("ours.txt"), fx.path("theirs.txt")]; + assert_eq!(repo.resolved_conflicts().unwrap(), paths); + repo.revert_resolved_conflicts(&paths).unwrap(); + assert_eq!(fx.git(&["diff", "--name-only", "--diff-filter=U"]), "ours.txt\ntheirs.txt"); + assert_eq!(fx.read("ours.txt"), "our content\n"); + assert_eq!(fx.read("theirs.txt"), "their content\n"); + assert!(repo.resolved_conflicts().unwrap().is_empty()); +} + #[test] fn network_failure_maps_to_error() { let fx = Fixture::new(); @@ -733,6 +905,14 @@ fn commits_changes_merge_selected_commits() { .collect::>() }; let s = |x: &String| Some(x.clone()); + let selection = |ids: &[&String]| { + let ids: Vec = ids.iter().map(|s| (*s).clone()).collect(); + repo.commit_selection_changes(&ids, &ide_core::CancellationToken::new()) + .unwrap() + .into_iter() + .map(|c| (c.path, c.kind, c.old_path, c.before, c.after)) + .collect::>() + }; // Contiguous c1..c3: tmp.txt added then deleted drops out; the rename chain collapses. assert_eq!( @@ -753,6 +933,9 @@ fn commits_changes_merge_selected_commits() { ("gone.txt".into(), ChangeKind::Deleted, None, s(&c2), None), ] ); + // Plan edits and autosquash may present a selection out of history order. + assert_eq!(selection(&[&c3, &c1, &c2, &c3]), changes(&[&c1, &c2, &c3])); + assert_eq!(selection(&[&c3, &c1]), changes(&[&c1, &c3])); // The root commit has no parent: everything is added; a duplicate id counts once. let root = changes(&[&c0, &c0]); assert_eq!(root.len(), 4); @@ -868,6 +1051,90 @@ fn stash_push_list_apply_pop() { assert!(repo.stash_drop(0).is_err()); } +#[test] +fn selected_stash_pop_applies_and_drops_the_entry_at_its_new_index() { + let fx = Fixture::new(); + fx.write("s.txt", "base\n"); + fx.commit_all("base"); + let repo = fx.repo(); + fx.write("s.txt", "selected\n"); + repo.stash_push(Some("selected"), false, false, &[]).unwrap(); + let selected = repo.stashes().unwrap().remove(0); + fx.write("s.txt", "later\n"); + fx.git(&["stash", "push", "-qm", "later"]); + let later = repo.stashes().unwrap().remove(0); + + let result = repo.unstash_selected(&selected, true, false, None).unwrap(); + assert_eq!(result, StashApplyResult { index: 1, outcome: StashApplyOutcome::Done }); + assert_eq!(fx.read("s.txt"), "selected\n"); + assert!(matches!(repo.stashes().unwrap().as_slice(), [entry] if entry.id == later.id)); + assert!(repo.unstash_selected(&selected, true, false, None).is_err()); + assert!(repo.drop_selected_stash(&selected).is_err()); + assert!(matches!(repo.stashes().unwrap().as_slice(), [entry] if entry.id == later.id)); +} + +#[test] +fn selected_stash_drop_distinguishes_two_entries_for_the_same_commit() { + let fx = Fixture::new(); + fx.write("s.txt", "base\n"); + fx.commit_all("base"); + let repo = fx.repo(); + fx.write("s.txt", "selected\n"); + repo.stash_push(Some("selected"), false, false, &[]).unwrap(); + let selected = repo.stashes().unwrap().remove(0); + fx.write("s.txt", "later\n"); + fx.git(&["stash", "push", "-qm", "later"]); + let seconds = (selected.time_ms / 1000.0) as i64; + assert!( + Command::new("git") + .current_dir(&fx.dir) + .args(["stash", "store", "-qm", &selected.message, &selected.id]) + .env("GIT_COMMITTER_DATE", format!("@{seconds} +0000")) + .status() + .unwrap() + .success() + ); + assert_eq!(repo.stashes().unwrap().len(), 3); + assert!(repo.drop_selected_stash(&selected).unwrap_err().message.contains("ambiguous")); + assert_eq!(repo.stashes().unwrap().len(), 3); + fx.git(&["stash", "drop", "-q", "stash@{0}"]); + fx.git(&["stash", "store", "-m", "same commit with a different message", &selected.id]); + assert_eq!(repo.drop_selected_stash(&selected).unwrap(), 2); + assert!(matches!( + repo.stashes().unwrap().as_slice(), + [alias, later] if alias.id == selected.id && alias.message.contains("different message") && later.message.contains("later") + )); + assert_eq!(fx.read("s.txt"), "base\n"); +} + +#[test] +fn selected_stash_branch_rechecks_the_list_after_checkout() { + let fx = Fixture::new(); + fx.write("s.txt", "base\n"); + fx.commit_all("base"); + let repo = fx.repo(); + fx.write("s.txt", "selected\n"); + fx.git(&["add", "s.txt"]); + repo.stash_push(Some("selected"), false, false, &[]).unwrap(); + let selected = repo.stashes().unwrap().remove(0); + fx.write("s.txt", "created during checkout\n"); + let payload = fx.git(&["stash", "create"]); + fx.git(&["restore", "s.txt"]); + let hook = ".git/hooks/post-checkout"; + fx.write(hook, &format!("#!/bin/sh\ngit stash store -m 'created during checkout' {payload}\n")); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(fx.path(hook), std::fs::Permissions::from_mode(0o755)).unwrap(); + } + + let result = repo.unstash_selected(&selected, false, false, Some("from-selected")).unwrap(); + assert_eq!(result, StashApplyResult { index: 0, outcome: StashApplyOutcome::Done }); + assert_eq!(fx.git(&["branch", "--show-current"]), "from-selected"); + assert_eq!(fx.git(&["show", ":s.txt"]), "selected"); + assert!(matches!(repo.stashes().unwrap().as_slice(), [entry] if entry.id == payload)); +} + #[test] fn stash_keep_index_reinstate_index_and_branch() { let fx = Fixture::new(); @@ -971,6 +1238,50 @@ fn delete_remote_branch_pushes_deletion() { assert!(repo.delete_remote_branch("feature", &CancellationToken::new(), &|_| {}).is_err()); } +#[test] +fn deleting_the_same_remote_branch_twice_refreshes_both_repositories_and_keeps_a_homonymous_tag() { + let (first, bare) = with_remote(); + first.git(&["tag", "feature"]); + first.git(&["push", "-q", "origin", "main:refs/heads/feature", "refs/tags/feature"]); + let other = Fixture::new(); + other.git(&["remote", "add", "origin", bare.to_str().unwrap()]); + other.git(&["fetch", "-q", "origin"]); + let a = first.repo(); + let b = other.repo(); + for repo in [&a, &b] { + assert!(repo.branches().unwrap().iter().any(|branch| branch.name == "origin/feature")); + repo.delete_remote_branch("origin/feature", &CancellationToken::new(), &|_| {}).unwrap(); + assert!(!repo.branches().unwrap().iter().any(|branch| branch.name == "origin/feature")); + } + assert!(git_in(&bare, &["branch", "--list", "feature"]).is_empty()); + assert_eq!(git_in(&bare, &["tag", "--list", "feature"]), "feature"); +} + +#[test] +fn deleting_a_local_tracking_branch_checks_the_confirmed_tip_and_upstream() { + let (fx, _bare) = with_remote(); + fx.git(&["push", "-q", "origin", "main:refs/heads/feature"]); + fx.git(&["switch", "-qc", "work", "--track", "origin/feature"]); + let base = fx.git(&["rev-parse", "HEAD"]); + fx.write("work.txt", "branch work\n"); + let tip = fx.commit_all("branch work"); + fx.git(&["switch", "-q", "main"]); + let repo = fx.repo(); + repo.delete_remote_branch("origin/feature", &CancellationToken::new(), &|_| {}).unwrap(); + + assert!(repo.delete_tracking_branch("work", &base, "origin/feature").is_err()); + assert!(repo.delete_tracking_branch("work", &tip, "origin/main").is_err()); + assert_eq!(fx.git(&["rev-parse", "refs/heads/work"]), tip); + + let deleted = repo.delete_tracking_branch("work", &tip, "origin/feature").unwrap(); + assert!(deleted.unmerged); + assert!(fx.git(&["branch", "--list", "work"]).is_empty()); + repo.restore_branch(&deleted).unwrap(); + assert_eq!(fx.git(&["rev-parse", "refs/heads/work"]), tip); + assert_eq!(fx.git(&["config", "--get", "branch.work.remote"]), "origin"); + assert_eq!(fx.git(&["config", "--get", "branch.work.merge"]), "refs/heads/feature"); +} + #[test] fn commit_amend_and_signoff() { let fx = Fixture::new(); @@ -1019,9 +1330,26 @@ fn commit_with_author_and_without_hooks() { repo.commit_with("blocked", &hooked, &|_| Ok(encoding_rs::UTF_8)).is_err(), "the failing pre-commit hook runs" ); - let options = CommitOptions { author: Some(" Other ".into()), ..Default::default() }; + let date = "2009-02-13T23:31:30+05:30"; + let options = CommitOptions { + author: Some(" Other ".into()), + author_date: Some(date.into()), + ..Default::default() + }; repo.commit_with("by other", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap(); assert_eq!(fx.git(&["log", "-1", "--format=%an <%ae>"]), "Other "); + assert_eq!(fx.git(&["log", "-1", "--format=%aI"]), date); + assert_ne!(fx.git(&["log", "-1", "--format=%cI"]), date); + + let keep_date = CommitOptions { amend: true, ..Default::default() }; + repo.commit_with("amend with original date", &keep_date, &|_| Ok(encoding_rs::UTF_8)).unwrap(); + assert_eq!(fx.git(&["log", "-1", "--format=%aI"]), date); + + let new_date = "2012-03-05T12:34:56-04:00"; + let update_date = CommitOptions { amend: true, author_date: Some(new_date.into()), ..Default::default() }; + repo.commit_with("amend with another date", &update_date, &|_| Ok(encoding_rs::UTF_8)).unwrap(); + assert_eq!(fx.git(&["log", "-1", "--format=%an <%ae>"]), "Other "); + assert_eq!(fx.git(&["log", "-1", "--format=%aI"]), new_date); } #[test] @@ -1115,6 +1443,20 @@ fn failed_branch_rename_does_not_unset_upstream() { assert_eq!(branch.upstream.as_deref(), Some("origin/main")); } +#[test] +fn unsetting_upstream_in_place_handles_a_missing_tracking_ref_without_renaming() { + let (fx, _bare) = with_remote(); + let repo = fx.repo(); + fx.git(&["config", "branch.main.merge", "refs/heads/gone"]); + let reflog = fx.git(&["reflog", "show", "--format=%gs", "main"]); + repo.rename_branch("main", "main", true).unwrap(); + let info = repo.branch_info().unwrap(); + assert_eq!(info.head.as_deref(), Some("main")); + assert!(info.upstream_tracking.is_none()); + assert_eq!(fx.git(&["reflog", "show", "--format=%gs", "main"]), reflog); + repo.rename_branch("main", "main", true).unwrap(); +} + #[test] fn branch_rename_reports_when_only_unsetting_upstream_fails() { let (fx, _bare) = with_remote(); @@ -1182,6 +1524,126 @@ fn smart_and_force_checkout_with_local_changes_in_the_way() { assert_eq!(fx.read("untouched.txt"), "new\n", "untracked files survive"); } +#[test] +fn merge_reports_staged_blockers_with_spaces_before_preserving_local_changes() { + let fx = Fixture::new(); + for path in ["incoming.txt", "local staged file.txt", "main.txt", "unrelated.txt"] { + fx.write(path, "base\n"); + } + fx.commit_all("base"); + fx.git(&["switch", "-c", "topic"]); + fx.write("incoming.txt", "incoming\n"); + fx.commit_all("topic edit"); + fx.git(&["switch", "main"]); + fx.write("main.txt", "main\n"); + fx.commit_all("main edit"); + fx.write("local staged file.txt", "staged\n"); + fx.git(&["add", "local staged file.txt"]); + fx.write("unrelated.txt", "local\n"); + let repo = fx.repo(); + let before = repo.head().unwrap(); + let staged = vec!["local staged file.txt".to_owned()]; + assert_eq!(repo.merge_affected_files("topic").unwrap(), staged); + let args = ["refs/heads/topic".to_owned()]; + let options = MergeOptions::default(); + assert_eq!(repo.merge_attempt(&args, &options, false).unwrap(), MergeOutcome::LocalChanges { files: staged },); + assert_eq!(repo.head().unwrap(), before); + assert_eq!(fx.git(&["show", ":local staged file.txt"]), "staged"); + assert!(repo.stashes().unwrap().is_empty()); + assert_eq!(repo.merge_attempt(&args, &options, true).unwrap(), MergeOutcome::Done); + assert_eq!(fx.read("incoming.txt"), "incoming\n"); + assert_eq!(fx.git(&["show", ":local staged file.txt"]), "staged"); + assert_eq!(fx.read("unrelated.txt"), "local\n"); + assert!(repo.stashes().unwrap().is_empty()); +} + +#[test] +fn ordinary_merge_carries_unrelated_edits_without_needing_a_shelf() { + let fx = Fixture::new(); + fx.write("incoming.txt", "base\n"); + fx.write("unrelated.txt", "base\n"); + fx.commit_all("base"); + fx.git(&["switch", "-c", "topic"]); + fx.write("incoming.txt", "incoming\n"); + fx.commit_all("topic edit"); + fx.git(&["switch", "main"]); + fx.write("unrelated.txt", "local\n"); + fx.write("invalid-shelf", "not a directory\n"); + let repo = fx.repo(); + repo.set_automatic_shelf(Some(fx.path("invalid-shelf")), None); + assert!(repo.merge_affected_files("topic").unwrap().is_empty()); + assert_eq!(repo.merge_attempt(&["topic".into()], &MergeOptions::default(), false).unwrap(), MergeOutcome::Done); + assert_eq!(fx.read("incoming.txt"), "incoming\n"); + assert_eq!(fx.read("unrelated.txt"), "local\n"); +} + +#[test] +fn merge_reports_commits_prepared_changes_and_up_to_date_branches() { + let fx = Fixture::new(); + fx.write("incoming.txt", "base\n"); + let base = fx.commit_all("base"); + fx.git(&["switch", "-c", "topic"]); + fx.write("incoming.txt", "incoming\n"); + let tip = fx.commit_all("incoming"); + fx.git(&["switch", "main"]); + let repo = fx.repo(); + let source = ["topic".into()]; + let squash = MergeOptions { squash: true, ..Default::default() }; + let no_commit = MergeOptions { no_commit: true, ..Default::default() }; + + assert_eq!(repo.merge_attempt(&source, &squash, false).unwrap(), MergeOutcome::Squashed); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), base); + assert_eq!(repo.operation().unwrap(), None); + assert_eq!(fx.git(&["show", ":incoming.txt"]), "incoming"); + fx.git(&["reset", "--hard", "HEAD"]); + + let stop = MergeOptions { no_ff: true, ..no_commit.clone() }; + assert_eq!(repo.merge_attempt(&source, &stop, false).unwrap(), MergeOutcome::ReadyToCommit); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), base); + assert_eq!(repo.operation().unwrap().as_deref(), Some("merge")); + fx.git(&["merge", "--abort"]); + + assert_eq!(repo.merge_attempt(&source, &no_commit, false).unwrap(), MergeOutcome::Done); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), tip); + assert_eq!(repo.merge_attempt(&source, &MergeOptions::default(), false).unwrap(), MergeOutcome::AlreadyUpToDate); + assert_eq!(repo.merge_attempt(&source, &squash, false).unwrap(), MergeOutcome::AlreadyUpToDate); +} + +#[test] +fn checkout_reports_staged_and_unstaged_paths_without_changing_the_repository() { + let fx = Fixture::new(); + for file in ["staged.txt", "unstaged.txt", "unrelated.txt"] { + fx.write(file, "base\n"); + } + fx.commit_all("base"); + fx.git(&["switch", "-c", "other"]); + for file in ["staged.txt", "unstaged.txt"] { + fx.write(file, "other\n"); + } + fx.commit_all("other branch"); + fx.git(&["switch", "main"]); + for file in ["staged.txt", "unstaged.txt", "unrelated.txt", "untracked.txt"] { + fx.write(file, "local\n"); + } + fx.git(&["add", "staged.txt"]); + let repo = fx.repo(); + let index = std::fs::read(fx.path(".git/index")).unwrap(); + let affected = vec!["staged.txt".to_owned(), "unstaged.txt".to_owned()]; + assert_eq!(repo.checkout_affected_files("other").unwrap(), affected); + assert_eq!(std::fs::read(fx.path(".git/index")).unwrap(), index); + assert_eq!(repo.head().unwrap().0.as_deref(), Some("main")); + assert_eq!(fx.read("staged.txt"), "local\n"); + assert_eq!(fx.read("unstaged.txt"), "local\n"); + assert_eq!( + repo.checkout_with("other", false, &CheckoutOptions::default()).unwrap(), + CheckoutOutcome::LocalChanges { files: affected }, + ); + fx.git(&["restore", "--source=HEAD", "--staged", "--worktree", "staged.txt", "unstaged.txt"]); + assert!(repo.checkout_affected_files("other").unwrap().is_empty()); + assert_eq!(fx.read("unrelated.txt"), "local\n"); + assert_eq!(fx.read("untracked.txt"), "local\n"); +} + #[test] fn checkout_of_a_branch_held_by_another_worktree_reports_it_and_changes_nothing() { let fx = Fixture::new(); @@ -1272,6 +1734,40 @@ fn checkout_remote_branch_with_existing_local_namesake() { assert_eq!(repo.branch_info().unwrap().upstream.as_deref(), Some("origin/main")); } +#[test] +fn checkout_uses_the_exact_ref_when_local_and_remote_names_collide() { + let (fx, bare) = with_remote(); + let base = fx.git(&["rev-parse", "HEAD"]); + fx.git(&["push", "-q", "origin", "main:topic"]); + fx.git(&["remote", "add", "team/ops", bare.to_str().unwrap()]); + fx.git(&["fetch", "-q", "team/ops"]); + fx.write("a.txt", "local branch\n"); + let local = fx.commit_all("local"); + fx.git(&["branch", "team/ops/topic"]); + fx.git(&["tag", "team/ops/topic", &base]); + let repo = fx.repo(); + let normal = CheckoutOptions::default(); + + assert_eq!(repo.checkout_with("refs/remotes/team/ops/topic", false, &normal).unwrap(), CheckoutOutcome::Done); + let info = repo.branch_info().unwrap(); + assert_eq!(info.head.as_deref(), Some("topic")); + assert_eq!(info.head_commit.as_deref(), Some(base.as_str())); + assert_eq!(info.upstream.as_deref(), Some("team/ops/topic")); + assert_eq!(fx.git(&["rev-parse", "refs/heads/team/ops/topic"]), local); + + assert_eq!(repo.checkout_with("refs/heads/team/ops/topic", false, &normal).unwrap(), CheckoutOutcome::Done); + assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("team/ops/topic")); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), local); + assert_eq!(repo.checkout_with("refs/tags/team/ops/topic", false, &normal).unwrap(), CheckoutOutcome::Done); + assert_eq!(repo.branch_info().unwrap().head, None); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), base); + fx.git(&["branch", &base, &local]); + let revision = format!("{base}^{{commit}}"); + assert_eq!(repo.checkout_with(&revision, false, &normal).unwrap(), CheckoutOutcome::Done); + assert_eq!(repo.branch_info().unwrap().head, None); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), base); +} + #[test] fn delete_branch_without_asking_and_restore_it() { let (fx, _bare) = with_remote(); @@ -1285,9 +1781,14 @@ fn delete_branch_without_asking_and_restore_it() { let merged = repo.delete_branch_restorable("merged").unwrap(); assert!(!merged.unmerged); assert_eq!(merged.upstream.as_deref(), Some("origin/main")); + assert_eq!( + merged.remote_upstream, + Some(ide_vcs::UpstreamTracking { remote: "origin".into(), branch: "main".into() }) + ); let work = repo.delete_branch_restorable("work").unwrap(); assert!(work.unmerged, "not fully merged branches are force-deleted and reported"); + assert_eq!(work.unmerged_base.as_deref(), Some(fx.git(&["rev-parse", "main"]).as_str())); assert_eq!(work.tip, work_tip); assert!(!repo.branches().unwrap().iter().any(|b| b.name == "work")); assert!(repo.delete_branch_restorable("main").is_err(), "the current branch cannot be deleted"); @@ -1300,10 +1801,114 @@ fn delete_branch_without_asking_and_restore_it() { assert_eq!(find("merged").upstream.as_deref(), Some("origin/main")); } +#[test] +fn cleanup_uses_head_and_preserves_the_deleted_branch_for_restore() { + let (fx, _bare) = with_remote(); + let repo = fx.repo(); + let name = "work=topic"; + fx.git(&["checkout", "-q", "-b", name, "--track", "origin/main"]); + let original = fx.git(&["rev-parse", "HEAD"]); + fx.write("w.txt", "work\n"); + let tip = fx.commit_all("work"); + fx.git(&["checkout", "-q", "main"]); + fx.git(&["branch", "shared", &tip]); + fx.git(&["branch", "--set-upstream-to=shared", name]); + assert!(repo.delete_merged_branch(name, &tip).is_err()); + fx.git(&["branch", "--set-upstream-to=origin/main", name]); + fx.git(&["merge", "--ff-only", name]); + assert!(repo.delete_merged_branch(name, &original).is_err()); + assert_eq!(fx.git(&["rev-parse", name]), tip); + + let linked = tempfile::tempdir().unwrap(); + fx.git(&["worktree", "add", linked.path().to_str().unwrap(), name]); + assert!(repo.delete_merged_branch(name, &tip).is_err()); + fx.git(&["worktree", "remove", linked.path().to_str().unwrap()]); + + let deleted = repo.delete_merged_branch(name, &tip).unwrap(); + assert!(!deleted.unmerged); + assert_eq!(deleted.tip, tip); + assert_eq!(deleted.upstream.as_deref(), Some("origin/main")); + assert!(!repo.branches().unwrap().iter().any(|branch| branch.name == name)); + repo.restore_branch(&deleted).unwrap(); + assert_eq!(fx.git(&["rev-parse", name]), tip); + assert_eq!(fx.git(&["rev-parse", &format!("{name}@{{upstream}}")]), original); +} + +#[test] +fn deleting_a_tracked_branch_records_the_upstream_as_the_unmerged_base() { + let (fx, _bare) = with_remote(); + let base = fx.git(&["rev-parse", "origin/main"]); + fx.git(&["switch", "-qc", "work", "--track", "origin/main"]); + fx.write("work.txt", "branch work\n"); + let tip = fx.commit_all("branch work"); + fx.git(&["switch", "-q", "main"]); + fx.write("main.txt", "main work\n"); + let head = fx.commit_all("main work"); + assert_ne!(base, head); + + let deleted = fx.repo().delete_branch_restorable("work").unwrap(); + assert!(deleted.unmerged); + assert_eq!(deleted.unmerged_base.as_deref(), Some(base.as_str())); + assert_eq!(deleted.tip, tip); +} + fn range(h: &LineHunk) -> HunkRange { HunkRange { start: h.start, lines: h.lines, old_start: h.old_start, old_lines: h.old_lines } } +#[test] +fn partial_commit_selects_additions_and_deletions_inside_the_same_hunk() { + let fx = Fixture::new(); + let base = "start\nold one\nold two\nend\n"; + let edited = "start\nnew one\nnew two\nend\n"; + fx.write("f.txt", base); + let before = fx.commit_all("base"); + let repo = fx.repo(); + fx.write("f.txt", edited); + let hunks = diff_hunks(base, edited); + assert_eq!(hunks.len(), 1); + let options = CommitOptions { + partial: vec![PartialCommitFile { + prepared: None, + path: fx.path("f.txt").into(), + hunks: vec![], + line_hunks: vec![ide_vcs::PartialCommitHunk { + range: range(&hunks[0]), + old_text: "old one\nold two\n".into(), + new_text: "new one\nnew two\n".into(), + deletions: vec![0], + additions: vec![1], + }], + }], + ..Default::default() + }; + fx.write("f.txt", "start\nnew one\nlate edit\nend\n"); + let file = &options.partial[0]; + assert!(repo.preview_partial_commit(file, encoding_rs::UTF_8).unwrap_err().message.contains("changed on disk")); + let stale = repo.commit_with("stale", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap_err(); + assert!(stale.message.contains("changed on disk")); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), before); + + fx.write("f.txt", edited); + let preview = repo.preview_partial_commit(file, encoding_rs::UTF_8).unwrap(); + assert_eq!(preview, "start\nold two\nnew two\nend\n"); + assert_eq!(fx.git(&["show", ":f.txt"]), base.trim_end()); + let mut options = options; + let cleaned = "start\nold two\ncleaned two\nend\n".to_owned(); + options.partial[0].prepared = + Some(ide_vcs::PreparedPartialCommit { before: "another selection".into(), text: cleaned.clone() }); + assert!(repo.commit_with("stale cleanup", &options, &|_| Ok(encoding_rs::UTF_8)).is_err()); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), before); + assert_eq!(fx.git(&["show", ":f.txt"]), base.trim_end()); + + options.partial[0].prepared.as_mut().unwrap().before = preview; + assert_eq!(repo.preview_partial_commit(&options.partial[0], encoding_rs::UTF_8).unwrap(), cleaned); + repo.commit_with("selected lines", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap(); + assert_eq!(fx.git(&["show", "HEAD:f.txt"]), cleaned.trim_end()); + assert_eq!(fx.git(&["show", ":f.txt"]), cleaned.trim_end()); + assert_eq!(std::fs::read_to_string(fx.path("f.txt")).unwrap(), edited); +} + #[test] fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() { let fx = Fixture::new(); @@ -1324,7 +1929,12 @@ fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() { // Commit the first hunk of f.txt plus the staged other.txt; staged.txt is not staged. let options = CommitOptions { - partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }], + partial: vec![PartialCommitFile { + prepared: None, + path: fx.path("f.txt").into(), + line_hunks: vec![], + hunks: vec![range(&hunks[0])], + }], ..Default::default() }; repo.commit_with("partial", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap(); @@ -1345,7 +1955,12 @@ fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() { // A stale hunk (the file changed since the UI computed it) refuses to commit anything. let before = fx.git(&["rev-parse", "HEAD"]); let stale = CommitOptions { - partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }], + partial: vec![PartialCommitFile { + prepared: None, + path: fx.path("f.txt").into(), + line_hunks: vec![], + hunks: vec![range(&hunks[0])], + }], ..Default::default() }; let err = repo.commit_with("stale", &stale, &|_| Ok(encoding_rs::UTF_8)).unwrap_err(); @@ -1358,7 +1973,12 @@ fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() { let rest = diff_hunks(&repo.file_at(&fx.path("f.txt"), None, encoding_rs::UTF_8).unwrap().unwrap(), edited); assert_eq!(rest.len(), 1); let options = CommitOptions { - partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&rest[0])] }], + partial: vec![PartialCommitFile { + prepared: None, + path: fx.path("f.txt").into(), + line_hunks: vec![], + hunks: vec![range(&rest[0])], + }], ..Default::default() }; repo.commit_with("rest", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap(); @@ -1380,7 +2000,12 @@ fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() { let hunks = diff_hunks(edited, &fx.read("f.txt")); let options = CommitOptions { run_hooks: true, - partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }], + partial: vec![PartialCommitFile { + prepared: None, + path: fx.path("f.txt").into(), + line_hunks: vec![], + hunks: vec![range(&hunks[0])], + }], ..Default::default() }; assert!(repo.commit_with("hooked", &options, &|_| Ok(encoding_rs::UTF_8)).is_err()); @@ -1423,7 +2048,12 @@ fn pending_changes_show_what_the_commit_would_hold_without_touching_the_index() // A selection: the first hunk of f.txt, the binary and the new file, staged.txt left out. let hunks = diff_hunks(base, edited); let options = CommitOptions { - partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }], + partial: vec![PartialCommitFile { + prepared: None, + path: fx.path("f.txt").into(), + line_hunks: vec![], + hunks: vec![range(&hunks[0])], + }], stage: vec![fx.path("bin.dat").into(), fx.path("added.txt").into()], exclude: vec![fx.path("staged.txt").into()], ..Default::default() @@ -1796,7 +2426,9 @@ fn encoded_java_hunks_staging_blame_and_partial_commit_preserve_bytes() { repo.unstage(std::slice::from_ref(&path)).unwrap(); let options = CommitOptions { partial: vec![PartialCommitFile { + prepared: None, path: path.clone().into(), + line_hunks: vec![], hunks: vec![HunkRange { start: hunks[0].start, lines: hunks[0].lines, @@ -2065,6 +2697,162 @@ fn smart_checkout_keeps_staged_changes_staged() { assert!(repo.stashes().unwrap().is_empty()); } +#[test] +fn smart_checkout_restores_its_own_stash() { + let fx = Fixture::new(); + fx.write("f.txt", "1\n2\n3\n4\n5\n"); + fx.write("staged.txt", "base\n"); + fx.write("extra.txt", "base\n"); + fx.commit_all("base"); + fx.git(&["switch", "-qc", "other"]); + fx.write("f.txt", "1\nother\n3\n4\n5\n"); + fx.commit_all("other edit"); + fx.git(&["switch", "-q", "main"]); + + fx.write("extra.txt", "from the hook\n"); + let payload = fx.git(&["stash", "create"]); + fx.git(&["restore", "extra.txt"]); + let hook = ".git/hooks/post-checkout"; + fx.write(hook, &format!("#!/bin/sh\ngit stash store -m 'created during checkout' {payload}\n")); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(fx.path(hook), std::fs::Permissions::from_mode(0o755)).unwrap(); + } + + fx.write("f.txt", "1\n2\n3\n4\nlocal\n"); + fx.write("staged.txt", "staged\n"); + fx.git(&["add", "staged.txt"]); + let repo = fx.repo(); + let opts = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() }; + assert_eq!(repo.checkout_with("other", false, &opts).unwrap(), CheckoutOutcome::Done); + assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other")); + assert_eq!(fx.read("f.txt"), "1\nother\n3\n4\nlocal\n"); + assert_eq!(fx.git(&["show", ":staged.txt"]), "staged"); + assert_eq!(fx.read("extra.txt"), "base\n"); + assert!(matches!(repo.stashes().unwrap().as_slice(), [entry] if entry.id == payload)); +} + +#[test] +fn smart_checkout_from_shelf_restores_edits_that_only_exist_in_the_index() { + check_smart_checkout_from_shelf(None); +} + +#[test] +fn smart_checkout_waits_for_the_shelf_batch_before_restoring_the_index() { + check_smart_checkout_from_shelf(Some("checkout-batch")); +} + +fn check_smart_checkout_from_shelf(batch: Option<&str>) { + let fx = Fixture::new(); + fx.write("f.txt", "1\n2\n3\n4\n5\n"); + fx.write("s.txt", "base\n"); + fx.write(".openidea/.gitignore", "# Project ignores\n"); + fx.commit_all("base"); + fx.git(&["switch", "-qc", "other"]); + fx.write("f.txt", "1\nother\n3\n4\n5\n"); + fx.commit_all("other edit"); + fx.git(&["switch", "-q", "main"]); + fx.write("f.txt", "1\n2\n3\n4\nlocal\n"); + fx.write("s.txt", "staged\n"); + fx.git(&["add", "s.txt"]); + fx.write("s.txt", "base\n"); + fx.write(".openidea/.gitignore", "# Local project ignores\n"); + + let repo = fx.repo(); + let shelf_dir = fx.path(".openidea/shelf"); + repo.set_automatic_shelf(Some(shelf_dir.clone()), None); + let opts = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() }; + let checkout = || repo.checkout_with("other", false, &opts).unwrap(); + if let Some(batch) = batch { + let scope = shelf::ShelfBatch::new(batch.to_owned(), fx.dir.clone()); + assert_eq!(scope.run(checkout), CheckoutOutcome::Done); + assert_eq!(fx.git(&["branch", "--show-current"]), "other"); + assert_eq!(fx.read("f.txt"), "1\nother\n3\n4\n5\n"); + assert_eq!(fx.git(&["show", ":s.txt"]), "base"); + assert_eq!(shelf::list(&shelf_dir).unwrap().len(), 1); + repo.finish_shelf_batch(batch).unwrap(); + } else { + assert_eq!(checkout(), CheckoutOutcome::Done); + } + assert_eq!(fx.git(&["branch", "--show-current"]), "other"); + assert_eq!(fx.read("f.txt"), "1\nother\n3\n4\nlocal\n"); + assert_eq!(fx.read("s.txt"), "base\n"); + assert_eq!(fx.git(&["show", ":s.txt"]), "staged"); + assert_eq!(fx.read(".openidea/.gitignore"), "# Local project ignores\n"); + assert!(fx.git(&["ls-files", "--others", "--exclude-standard"]).is_empty()); + assert!(repo.stashes().unwrap().is_empty()); + assert!(shelf::list(&shelf_dir).unwrap().is_empty()); +} + +#[test] +fn smart_checkout_keeps_conflicting_saved_changes_on_the_shelf() { + let fx = Fixture::new(); + fx.write("f.txt", "base\n"); + fx.write("clean.txt", "base\n"); + fx.commit_all("base"); + fx.git(&["switch", "-qc", "other"]); + fx.write("f.txt", "other\n"); + fx.commit_all("other edit"); + fx.git(&["switch", "-q", "main"]); + fx.write("f.txt", "local\n"); + fx.write("clean.txt", "clean local\n"); + let mut lists = ChangelistState::initial(); + lists.lists.push(Changelist { + id: "conflict".into(), + name: "Conflict".into(), + comment: String::new(), + applied_commit: None, + }); + lists.files.insert("f.txt".into(), "conflict".into()); + changelists::save(&fx.path(".openidea/changelists.json"), &lists).unwrap(); + + let repo = fx.repo(); + let shelf_dir = fx.path(".openidea/shelf"); + repo.set_automatic_shelf(Some(shelf_dir.clone()), Some(fx.dir.clone())); + let opts = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() }; + assert_eq!( + repo.checkout_with("other", false, &opts).unwrap(), + CheckoutOutcome::Conflicts { files: vec!["f.txt".into()] } + ); + assert_eq!(fx.git(&["show", ":2:f.txt"]), "other"); + assert_eq!(fx.git(&["show", ":3:f.txt"]), "local"); + let sides = repo.merge_sides().unwrap(); + assert_eq!(sides.operation.as_deref(), Some("unshelve")); + assert!(sides.reversed); + assert!(repo.stashes().unwrap().is_empty()); + let entries = shelf::list(&shelf_dir).unwrap(); + assert_eq!(entries.len(), 1); + assert!(entries[0].name.starts_with("[Conflict] ")); + assert!(shelf::patch_of(&shelf_dir, &entries[0].id).unwrap().contains("+local")); + assert_eq!(fx.read("clean.txt"), "clean local\n"); +} + +#[test] +fn smart_checkout_puts_changes_back_if_it_cannot_create_the_shelf() { + let fx = Fixture::new(); + fx.write("f.txt", "base\n"); + fx.commit_all("base"); + fx.git(&["switch", "-qc", "other"]); + fx.write("f.txt", "other\n"); + fx.commit_all("other edit"); + fx.git(&["switch", "-q", "main"]); + fx.write("f.txt", "staged\n"); + fx.git(&["add", "f.txt"]); + fx.write("f.txt", "local\n"); + fx.write(".openidea/shelf", "not a directory"); + + let repo = fx.repo(); + repo.set_automatic_shelf(Some(fx.path(".openidea/shelf")), None); + let opts = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() }; + assert!(repo.checkout_with("other", false, &opts).is_err()); + assert_eq!(fx.git(&["branch", "--show-current"]), "main"); + assert_eq!(fx.git(&["show", ":f.txt"]), "staged"); + assert_eq!(fx.read("f.txt"), "local\n"); + assert!(repo.stashes().unwrap().is_empty()); + assert!(!fx.path(".git/openidea-saved-changes").exists()); +} + #[test] fn checkout_reports_untracked_files_it_would_overwrite() { let fx = Fixture::new(); @@ -2146,6 +2934,222 @@ fn reword_keeps_local_changes_and_can_be_undone() { assert!(repo.restore_head(&change.before, &change.after).is_err()); } +#[test] +fn amend_earlier_commit_replays_descendants_and_preserves_the_remaining_index() { + let fx = Fixture::new(); + fx.write("target.txt", "original\n"); + fx.write("excluded.txt", "original\n"); + fx.git(&["add", "-A"]); + let original_date = "2009-02-13T23:31:30+05:30"; + fx.git(&[ + "commit", + "-m", + "target", + "--author=Original Author ", + &format!("--date={original_date}"), + ]); + let target = fx.git(&["rev-parse", "HEAD"]); + fx.write("descendant.txt", "later\n"); + let before = fx.commit_all("descendant"); + fx.write("target.txt", "included in the earlier commit\n"); + fx.write("excluded.txt", "still staged\n"); + fx.git(&["add", "-A"]); + fx.write("target.txt", "local edit beyond the staged version\n"); + fx.write("untracked.txt", "untracked\n"); + fx.git(&["update-index", "--split-index"]); + + let options = CommitOptions { + amend: true, + amend_target: Some(AmendTarget { + commit: target, + head: HistoryTip { branch: Some("main".into()), commit: before.clone() }, + protected_branches: vec![], + }), + exclude: vec![fx.path("excluded.txt").into()], + run_hooks: true, + ..Default::default() + }; + let head = fx.repo().commit_with("amended target\n\nmessage body", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap(); + assert_ne!(before, head); + assert_eq!(fx.git(&["log", "--format=%s"]), "descendant\namended target"); + assert_eq!(fx.git(&["log", "-1", "--format=%B", "HEAD~1"]), "amended target\n\nmessage body"); + assert_eq!(fx.git(&["log", "-1", "--format=%an <%ae>", "HEAD~1"]), "Original Author "); + assert_eq!(fx.git(&["log", "-1", "--format=%aI", "HEAD~1"]), original_date); + assert_eq!(fx.git(&["show", "HEAD~1:target.txt"]), "included in the earlier commit"); + assert_eq!(fx.git(&["show", "HEAD:descendant.txt"]), "later"); + assert_eq!(fx.git(&["show", ":excluded.txt"]), "still staged"); + assert_eq!(fx.git(&["show", "HEAD:excluded.txt"]), "original"); + assert_eq!(fx.read("target.txt"), "local edit beyond the staged version\n"); + assert_eq!(fx.read("untracked.txt"), "untracked\n"); + assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "excluded.txt"); +} + +#[test] +fn amend_earlier_commit_is_atomic_on_conflict_and_rejects_protected_history() { + let fx = Fixture::new(); + fx.write("overlap.txt", "original\n"); + let target = fx.commit_all("target"); + fx.write("overlap.txt", "later\n"); + let before = fx.commit_all("descendant"); + fx.write("overlap.txt", "selected change\n"); + fx.git(&["add", "overlap.txt"]); + fx.write("overlap.txt", "unstaged change\n"); + let index = fx.git(&["write-tree"]); + + let mut options = CommitOptions { + amend: true, + amend_target: Some(AmendTarget { + commit: target.clone(), + head: HistoryTip { branch: Some("main".into()), commit: before.clone() }, + protected_branches: vec!["origin/main".into()], + }), + ..Default::default() + }; + fx.git(&["update-ref", "refs/remotes/origin/main", &target]); + let repo = fx.repo(); + let attempt = + |options: &CommitOptions| repo.commit_with("new message", options, &|_| Ok(encoding_rs::UTF_8)).unwrap_err(); + assert!(attempt(&options).message.contains("pushed to protected branch")); + fx.git(&["update-ref", "-d", "refs/remotes/origin/main"]); + assert!(attempt(&options).message.contains("would cause a conflict")); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), before); + assert_eq!(fx.git(&["write-tree"]), index); + assert_eq!(fx.read("overlap.txt"), "unstaged change\n"); + + options.amend_target.as_mut().unwrap().head.commit = target; + assert!(attempt(&options).message.contains("branch has changed")); +} + +#[test] +fn amend_earlier_commit_can_change_only_the_message() { + let fx = Fixture::new(); + fx.write("root.txt", "one\n"); + let target = fx.commit_all("target"); + fx.write("later.txt", "two\n"); + let head = fx.commit_all("descendant"); + let before = fx.git(&["rev-parse", "HEAD^{tree}"]); + let options = CommitOptions { + amend: true, + amend_target: Some(AmendTarget { + commit: target, + head: HistoryTip { branch: Some("main".into()), commit: head }, + protected_branches: vec![], + }), + ..Default::default() + }; + fx.repo().commit_with("updated", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap(); + assert_eq!(fx.git(&["log", "--format=%s"]), "descendant\nupdated"); + assert_eq!(fx.git(&["rev-parse", "HEAD^{tree}"]), before); + assert_eq!(fx.git(&["status", "--porcelain"]), ""); +} + +#[test] +fn amend_earlier_commit_can_override_only_its_author_date() { + let fx = Fixture::new(); + fx.write("root.txt", "one\n"); + fx.git(&["add", "root.txt"]); + fx.git(&["commit", "-qm", "target", "--author=Original "]); + let target = fx.git(&["rev-parse", "HEAD"]); + fx.write("later.txt", "later\n"); + let head = fx.commit_all("descendant"); + let descendant_date = fx.git(&["log", "-1", "--format=%aI", &head]); + let date = "2012-03-05T12:34:56-04:00"; + let options = CommitOptions { + amend: true, + amend_target: Some(AmendTarget { + commit: target, + head: HistoryTip { branch: Some("main".into()), commit: head }, + protected_branches: vec![], + }), + author_date: Some(date.into()), + ..Default::default() + }; + fx.repo().commit_with("target", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap(); + assert_eq!(fx.git(&["log", "-1", "--format=%an <%ae>", "HEAD~1"]), "Original "); + assert_eq!(fx.git(&["log", "-1", "--format=%aI", "HEAD~1"]), date); + assert_eq!(fx.git(&["log", "-1", "--format=%aI"]), descendant_date); +} + +#[test] +fn amend_earlier_commit_can_keep_the_prepared_conflict_without_overwriting_staged_edits() { + let fx = Fixture::new(); + fx.write("overlap.txt", "original\n"); + fx.write("unrelated.txt", "original\n"); + let target = fx.commit_all("same subject"); + fx.write("overlap.txt", "later\n"); + let before = fx.commit_all("same subject"); + fx.write("overlap.txt", "selected change\n"); + fx.git(&["add", "overlap.txt"]); + fx.write("overlap.txt", "unstaged change\n"); + fx.write("pending.txt", "prepared addition\n"); + fx.git(&["add", "-N", "pending.txt"]); + let staged = fx.git(&["write-tree"]); + let hook = fx.path(".git/hooks/pre-commit"); + fx.write(".git/hooks/pre-commit", "#!/bin/sh\nprintf x >> .git/hooks-ran\n"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + assert!(hook.is_file()); + let date = "2019-04-01T02:34:56+02:00"; + let options = CommitOptions { + amend: true, + amend_target: Some(AmendTarget { + commit: target.clone(), + head: HistoryTip { branch: Some("main".into()), commit: before.clone() }, + protected_branches: vec![], + }), + run_hooks: true, + author: Some("Edited Author ".into()), + author_date: Some(date.into()), + stage: vec![fx.path("pending.txt").into()], + ..Default::default() + }; + let repo = fx.repo(); + let error = repo.commit_with("new message\n\nnew body", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap_err(); + let Some(ErrorData::AmendConflict { commit }) = error.data else { panic!("{error}") }; + assert_eq!(fx.git(&["log", "-1", "--format=%aI", &commit]), date); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), before); + assert_eq!(fx.git(&["write-tree"]), staged); + assert_eq!(fx.read("overlap.txt"), "unstaged change\n"); + + fx.git(&["checkout", "-qb", "other"]); + assert!(repo.keep_amend_commit(&commit).unwrap_err().message.contains("branch has changed")); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), before); + fx.git(&["checkout", "-q", "main"]); + + fx.write("pending.txt", ""); + fx.git(&["add", "pending.txt"]); + assert!(repo.keep_amend_commit(&commit).unwrap_err().message.contains("Staged changes")); + assert_eq!(fx.git(&["diff", "--cached", "--name-only", "--", "pending.txt"]), "pending.txt"); + fx.git(&["reset", "-q", "HEAD", "--", "pending.txt"]); + fx.write("pending.txt", "prepared addition\n"); + fx.git(&["add", "-N", "pending.txt"]); + + fx.git(&["add", "overlap.txt"]); + assert!(repo.keep_amend_commit(&commit).unwrap_err().message.contains("Staged changes")); + assert_eq!(fx.git(&["show", ":overlap.txt"]), "unstaged change"); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), before); + fx.write("overlap.txt", "selected change\n"); + fx.git(&["add", "overlap.txt"]); + fx.write("overlap.txt", "latest local edit\n"); + fx.write("unrelated.txt", "new staging after the conflict\n"); + fx.git(&["add", "unrelated.txt"]); + + assert_eq!(repo.keep_amend_commit(&commit).unwrap(), commit); + assert_eq!(fx.git(&["rev-parse", "HEAD^"]), before); + assert_eq!(fx.git(&["log", "-1", "--format=%B"]), format!("amend! {target}\n\nnew message\n\nnew body")); + assert_eq!(fx.git(&["log", "-1", "--format=%an <%ae>"]), "Edited Author "); + assert_eq!(fx.git(&["show", "HEAD:overlap.txt"]), "selected change"); + assert_eq!(fx.git(&["show", "HEAD:pending.txt"]), "prepared addition"); + assert_eq!(fx.read("overlap.txt"), "latest local edit\n"); + assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "unrelated.txt"); + assert_eq!(fx.git(&["show", ":unrelated.txt"]), "new staging after the conflict"); + assert_eq!(fx.read(".git/hooks-ran"), "x"); + assert!(repo.keep_amend_commit(&commit).unwrap_err().message.contains("no longer available")); +} + #[test] fn reword_refuses_commits_outside_the_current_branch() { let fx = Fixture::new(); @@ -2158,6 +3162,160 @@ fn reword_refuses_commits_outside_the_current_branch() { assert!(fx.repo().reword(&side, "other").is_err()); } +#[test] +fn extract_renamed_and_deleted_files_from_an_older_commit() { + let fx = Fixture::new(); + fx.write("old [1].txt", "renamed\n"); + fx.write("old 1.txt", "before\n"); + fx.write("removed.txt", "removed\n"); + let base = fx.commit_all("base"); + fx.git(&["mv", "old [1].txt", "new [1].txt"]); + fx.git(&["rm", "removed.txt"]); + fx.write("old 1.txt", "after\n"); + let target = fx.commit_all("original subject\n\noriginal body"); + fx.write("later.txt", "later\n"); + let head = fx.commit_all("later"); + fx.write("new [1].txt", "local work\n"); + fx.write("staged.txt", "staged\n"); + fx.git(&["add", "staged.txt"]); + let status = fx.git(&["status", "--porcelain"]); + let paths = ["old [1].txt", "new [1].txt", "removed.txt"].map(PathBuf::from); + let repo = fx.repo(); + let expected = HistoryTip { commit: head.clone(), branch: Some("main".into()) }; + let result = repo.extract_commit_changes(&target, &expected, &paths, "extract rename and deletion").unwrap(); + assert_eq!(fx.git(&["rev-parse", "HEAD~1"]), result.commit); + assert_eq!(fx.git(&["rev-parse", "HEAD~3"]), base); + assert_eq!(fx.git(&["log", "-1", "--format=%B", "HEAD~2"]), "original subject\n\noriginal body"); + assert_eq!(fx.git(&["show", "--format=", "--name-status", "HEAD~2"]), "M\told 1.txt"); + assert_eq!( + fx.git(&["show", "--format=", "--name-status", "-M", "HEAD~1"]), + "R100\told [1].txt\tnew [1].txt\nD\tremoved.txt" + ); + assert_eq!(fx.git(&["rev-parse", "HEAD^{tree}"]), fx.git(&["rev-parse", &format!("{head}^{{tree}}")])); + assert_eq!(fx.git(&["status", "--porcelain"]), status); + assert_eq!(fx.read("new [1].txt"), "local work\n"); + repo.restore_head(&result.head.before, &result.head.after).unwrap(); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), head); + assert_eq!(fx.git(&["status", "--porcelain"]), status); +} + +#[test] +fn extract_from_root_rejects_all_changes_and_respects_detached_head() { + let fx = Fixture::new(); + fx.write("one.txt", "one\n"); + fx.write("two.txt", "two\n"); + let root = fx.commit_all("root"); + let repo = fx.repo(); + let first = PathBuf::from("one.txt"); + let both = [first.clone(), PathBuf::from("two.txt")]; + let mut expected = HistoryTip { commit: root.clone(), branch: Some("main".into()) }; + assert!(repo.extract_commit_changes(&root, &expected, &both, "all").is_err()); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), root); + fx.git(&["switch", "--detach", &root]); + assert!(repo.extract_commit_changes(&root, &expected, std::slice::from_ref(&first), "stale").is_err()); + expected.branch = None; + repo.extract_commit_changes(&root, &expected, &[first], "extract first").unwrap(); + assert_eq!(fx.git(&["ls-tree", "--name-only", "HEAD~1"]), "two.txt"); + assert_eq!(fx.git(&["rev-parse", "refs/heads/main"]), root); + assert_eq!(fx.git(&["branch", "--show-current"]), ""); +} + +#[test] +fn drop_selected_changes_from_older_commit_and_undo_keeps_local_changes() { + let fx = Fixture::new(); + fx.git(&["config", "rebase.autoSquash", "true"]); + fx.write("old [1].txt", "renamed\n"); + fx.write("removed.txt", "removed\n"); + fx.write("local.txt", "original\n"); + let base = fx.commit_all("base"); + fx.git(&["mv", "old [1].txt", "new [1].txt"]); + fx.git(&["rm", "removed.txt"]); + fx.write("kept.txt", "kept\n"); + let target = fx.commit_all("original changes"); + fx.write("later.txt", "later\n"); + let head = fx.commit_all("fixup! original changes"); + fx.write("local.txt", "unstaged\n"); + fx.write("staged.txt", "staged\n"); + fx.git(&["add", "staged.txt"]); + let status = fx.git(&["status", "--porcelain"]); + + let paths = ["old [1].txt", "new [1].txt", "removed.txt"].map(PathBuf::from); + let expected = HistoryTip { commit: head.clone(), branch: Some("main".into()) }; + let repo = fx.repo(); + let result = repo.drop_commit_changes(&target, &expected, &paths, &CancellationToken::new(), &|_| {}).unwrap(); + assert_eq!(fx.git(&["rev-parse", "HEAD~1"]), result.commit); + assert_eq!(fx.git(&["rev-parse", "HEAD~2"]), base); + assert_eq!(fx.git(&["log", "-2", "--format=%s"]), "fixup! original changes\noriginal changes"); + assert_eq!(fx.git(&["show", "--format=", "--name-status", "HEAD~1"]), "A\tkept.txt"); + assert_eq!(fx.read("old [1].txt"), "renamed\n"); + assert_eq!(fx.read("removed.txt"), "removed\n"); + assert!(!fx.path("new [1].txt").exists()); + assert_eq!(fx.read("later.txt"), "later\n"); + assert_eq!(fx.git(&["status", "--porcelain"]), status); + + repo.restore_head(&result.head.before, &result.head.after).unwrap(); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), head); + assert_eq!(fx.read("new [1].txt"), "renamed\n"); + assert_eq!(fx.git(&["status", "--porcelain"]), status); +} + +#[test] +fn drop_selected_changes_from_root_works_on_detached_head() { + let fx = Fixture::new(); + fx.write("keep.txt", "kept\n"); + fx.write("drop.txt", "dropped\n"); + let root = fx.commit_all("root"); + fx.git(&["switch", "--detach", &root]); + let expected = HistoryTip { commit: root.clone(), branch: None }; + let repo = fx.repo(); + let paths = [PathBuf::from("drop.txt")]; + let cancel = CancellationToken::new(); + let all = [PathBuf::from("drop.txt"), PathBuf::from("keep.txt")]; + assert!(repo.drop_commit_changes(&root, &expected, &all, &cancel, &|_| {}).is_err()); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), root); + let result = repo.drop_commit_changes(&root, &expected, &paths, &cancel, &|_| {}).unwrap(); + assert_eq!(result.commit, result.head.after); + assert_eq!(fx.git(&["rev-parse", "refs/heads/main"]), root); + assert_eq!(fx.git(&["branch", "--show-current"]), ""); + assert_eq!(fx.git(&["ls-tree", "--name-only", "HEAD"]), "keep.txt"); + assert!(!fx.path("drop.txt").exists()); +} + +#[test] +fn drop_selected_changes_leaves_replay_conflicts_resolvable_or_abortable() { + let fx = Fixture::new(); + fx.write("conflict.txt", "base\n"); + fx.commit_all("base"); + fx.write("conflict.txt", "target\n"); + fx.write("kept.txt", "kept\n"); + let target = fx.commit_all("target"); + fx.write("conflict.txt", "descendant\n"); + let head = fx.commit_all("descendant"); + fx.write("staged.txt", "staged\n"); + fx.git(&["add", "staged.txt"]); + let expected = HistoryTip { commit: head.clone(), branch: Some("main".into()) }; + let repo = fx.repo(); + let paths = [PathBuf::from("conflict.txt")]; + let cancel = CancellationToken::new(); + let run = || repo.drop_commit_changes(&target, &expected, &paths, &cancel, &|_| {}); + + assert!(run().is_err()); + assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("rebase")); + assert_eq!(fx.git(&["diff", "--name-only", "--diff-filter=U"]), "conflict.txt"); + repo.abort_operation(&cancel, &|_| {}).unwrap(); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), head); + assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "staged.txt"); + + assert!(run().is_err()); + fx.write("conflict.txt", "resolved\n"); + repo.stage(&[fx.path("conflict.txt")]).unwrap(); + repo.continue_operation(&cancel, &|_| {}).unwrap(); + assert_eq!(repo.branch_info().unwrap().operation, None); + assert_eq!(fx.git(&["show", "HEAD~1:conflict.txt"]), "base"); + assert_eq!(fx.read("conflict.txt"), "resolved\n"); + assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "staged.txt"); +} + #[cfg(unix)] #[test] fn status_skips_a_directory_it_cannot_read() { @@ -2267,6 +3425,24 @@ fn sets_the_commit_identity_in_the_repository() { assert_eq!(blank.kind, ErrorKind::InvalidInput); } +#[test] +fn reads_boolean_config_using_gits_syntax() { + let fx = Fixture::new(); + let repo = fx.repo(); + let key = "openidea.booleanFixture"; + assert_eq!(repo.config_get_bool(key).unwrap(), None); + let config = fx.path(".git/config"); + let existing = std::fs::read_to_string(&config).unwrap(); + std::fs::write(&config, format!("{existing}\n[openidea]\n\tbooleanFixture\n")).unwrap(); + assert_eq!(repo.config_get_bool(key).unwrap(), Some(true)); + for value in ["", "OFF"] { + fx.git(&["config", "--local", key, value]); + assert_eq!(repo.config_get_bool(key).unwrap(), Some(false)); + } + fx.git(&["config", "--local", key, "not-a-boolean"]); + assert!(repo.config_get_bool(key).is_err()); +} + #[test] fn status_from_the_git_command_line_matches_the_in_process_one() { let fx = Fixture::new(); diff --git a/crates/ide-vcs/tests/submodule_update.rs b/crates/ide-vcs/tests/submodule_update.rs new file mode 100644 index 000000000..c4eff6ad0 --- /dev/null +++ b/crates/ide-vcs/tests/submodule_update.rs @@ -0,0 +1,289 @@ +use ide_core::{CancellationToken, workflow_settings::FetchTagsMode}; +use ide_vcs::{Repo, Repos, SubmoduleRollbackSource}; +use std::{fs, path::Path, process::Command}; + +fn git(root: &Path, args: &[&str]) -> String { + let result = Command::new("git") + .current_dir(root) + .args(["-c", "protocol.file.allow=always", "-c", "core.autocrlf=false"]) + .args(args) + .output() + .unwrap(); + assert!(result.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&result.stderr)); + String::from_utf8(result.stdout).unwrap().trim().to_owned() +} + +fn init(root: &Path, file: &str) { + fs::create_dir(root).unwrap(); + git(root, &["init", "-qb", "main"]); + git(root, &["config", "user.name", "Update fixture"]); + git(root, &["config", "user.email", "test@example.com"]); + git(root, &["config", "core.autocrlf", "false"]); + fs::write(root.join(file), "before\n").unwrap(); +} + +fn commit(root: &Path, subject: &str) -> String { + git(root, &["add", "-A"]); + git(root, &["commit", "--no-gpg-sign", "-qm", subject]); + git(root, &["rev-parse", "HEAD"]) +} + +fn follow(root: &Path, commit: &str) { + git(root, &["fetch", "origin"]); + git(root, &["checkout", "-q", "--detach", commit]); +} + +#[test] +fn submodule_rollback_restores_the_chosen_version_without_discarding_child_edits() { + let temp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(temp.path()).unwrap(); + let library = root.join("library"); + let workspace = root.join("workspace"); + init(&library, "library.txt"); + let initial = commit(&library, "initial library"); + init(&workspace, "root.txt"); + git(&workspace, &["submodule", "add", "--", library.to_str().unwrap(), "modules/library"]); + commit(&workspace, "initial parent"); + + fs::write(library.join("library.txt"), "updated\n").unwrap(); + let updated = commit(&library, "update library"); + let module = workspace.join("modules/library"); + follow(&module, &updated); + git(&workspace, &["add", "--", "modules/library"]); + git(&module, &["checkout", "-q", "--detach", &initial]); + fs::write(module.join("staged.txt"), "local staging\n").unwrap(); + git(&module, &["add", "staged.txt"]); + fs::write(module.join("local.txt"), "untracked\n").unwrap(); + + let parent = Repo::discover(&workspace).unwrap().unwrap(); + parent.set_execution_allowed(true); + let child_head = || git(&module, &["rev-parse", "HEAD"]); + let staged_link = || git(&workspace, &["rev-parse", ":modules/library"]); + parent.rollback_submodule(&module, SubmoduleRollbackSource::Index, true).unwrap(); + assert_eq!(child_head(), updated); + assert_eq!(staged_link(), updated); + assert_eq!(git(&module, &["show", ":staged.txt"]), "local staging"); + + fs::write(module.join("library.txt"), "unselected conflicting edit\n").unwrap(); + assert!(parent.rollback_submodule(&module, SubmoduleRollbackSource::Head, true).is_err()); + assert_eq!(child_head(), updated); + assert_eq!(staged_link(), updated); + assert_eq!(fs::read_to_string(module.join("library.txt")).unwrap(), "unselected conflicting edit\n"); + + parent.rollback_submodule(&module, SubmoduleRollbackSource::Head, false).unwrap(); + assert_eq!(child_head(), updated); + assert_eq!(staged_link(), initial); + git(&module, &["restore", "--", "library.txt"]); + parent.rollback_submodule(&module, SubmoduleRollbackSource::Head, true).unwrap(); + assert_eq!(child_head(), initial); + assert_eq!(staged_link(), initial); + assert_eq!(git(&module, &["show", ":staged.txt"]), "local staging"); + assert_eq!(fs::read_to_string(module.join("local.txt")).unwrap(), "untracked\n"); + + let new_checkout = workspace.join("new"); + git(&workspace, &["submodule", "add", "--", library.to_str().unwrap(), "new"]); + parent.rollback_submodule(&new_checkout, SubmoduleRollbackSource::Head, true).unwrap(); + assert!(git(&workspace, &["ls-files", "--", "new"]).is_empty()); + assert_eq!(git(&new_checkout, &["rev-parse", "HEAD"]), updated); + assert!(parent.rollback_submodule(&workspace.join("root.txt"), SubmoduleRollbackSource::Head, true).is_err()); +} + +#[test] +fn submodule_rollback_recreates_missing_directories_from_head_or_index() { + let temp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(temp.path()).unwrap(); + let workspace = root.join("workspace"); + init(&workspace, "root.txt"); + let recorded = commit(&workspace, "root"); + let names = ["modules/from-index", "modules/from-head", "modules/unselected"]; + for name in names { + git(&workspace, &["update-index", "--add", "--cacheinfo", &format!("160000,{recorded},{name}")]); + } + git(&workspace, &["commit", "--no-gpg-sign", "-qm", "record submodules"]); + git(&workspace, &["update-index", "--force-remove", "modules/from-head"]); + + let parent = Repo::discover(&workspace).unwrap().unwrap(); + parent.set_execution_allowed(true); + for (name, source) in [(names[0], SubmoduleRollbackSource::Index), (names[1], SubmoduleRollbackSource::Head)] { + let path = workspace.join(name); + assert!(!path.exists()); + parent.rollback_submodule(&path, source, true).unwrap(); + assert!(path.is_dir()); + assert!(fs::read_dir(path).unwrap().next().is_none()); + assert_eq!(git(&workspace, &["rev-parse", &format!(":{name}")]), recorded); + assert!(git(&workspace, &["status", "--short", "--", name]).is_empty()); + } + assert!(!workspace.join(names[2]).exists()); +} + +#[test] +fn worktrees_report_the_submodule_checkout_from_either_worktree() { + let temp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(temp.path()).unwrap(); + let library = root.join("library"); + let workspace = root.join("workspace"); + init(&library, "library.txt"); + commit(&library, "initial library"); + init(&workspace, "root.txt"); + git(&workspace, &["submodule", "add", "--", library.to_str().unwrap(), "modules/library"]); + commit(&workspace, "initial parent"); + + let linked = root.join("linked library"); + let module = workspace.join("modules/library"); + git(&module, &["worktree", "add", "--detach", "--", linked.to_str().unwrap(), "HEAD"]); + for checkout in [&module, &linked] { + let repo = ide_vcs::Repo::discover(checkout).unwrap().unwrap(); + repo.set_execution_allowed(true); + let trees = repo.worktrees().unwrap(); + assert_eq!(trees.len(), 2); + assert_eq!(trees[0].path.0, module, "worktrees listed from {checkout:?} at {:?}", repo.metadata_dirs()); + assert!(trees[0].main && trees[0].submodule, "{checkout:?}: {trees:?}"); + assert!(!trees[1].main && trees[1].submodule); + assert_eq!(trees[1].path.0, linked); + } + let parent = ide_vcs::Repo::discover(&workspace).unwrap().unwrap(); + parent.set_execution_allowed(true); + let trees = parent.worktrees().unwrap(); + assert_eq!(trees[0].path.0, workspace); + assert!(!trees[0].submodule); +} + +#[test] +fn diff_entries_keep_committed_index_and_checkout_gitlinks_distinct() { + let temp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(temp.path()).unwrap(); + let library = root.join("library"); + let workspace = root.join("workspace"); + init(&library, "library.txt"); + let committed = commit(&library, "initial library"); + init(&workspace, "root.txt"); + git(&workspace, &["submodule", "add", "--", library.to_str().unwrap(), "modules/library"]); + let revision = commit(&workspace, "initial parent"); + + fs::write(library.join("library.txt"), "staged revision\n").unwrap(); + let staged = commit(&library, "staged revision"); + fs::write(library.join("library.txt"), "checkout revision\n").unwrap(); + let working = commit(&library, "checkout revision"); + let module = workspace.join("modules/library"); + follow(&module, &staged); + git(&workspace, &["add", "--", "modules/library"]); + follow(&module, &working); + + let repos = Repos::discover(&workspace, &|_| false).unwrap(); + let parent = repos.for_path(&module).unwrap(); + assert_eq!(parent.root(), workspace); + for (rev, expected) in [(revision.as_str(), &committed), ("HEAD", &committed), (":0", &staged), ("WT", &working)] { + let entry = parent.diff_entry_at(&module, rev).unwrap().unwrap(); + assert_eq!(entry.mode, "160000"); + assert_eq!(entry.gitlink.as_ref(), Some(expected)); + if rev != "WT" { + assert!(parent.file_bytes_at(&module, Some(rev)).unwrap().is_none()); + } + } + let file = parent.diff_entry_at(&workspace.join("root.txt"), "HEAD").unwrap().unwrap(); + assert_eq!(file.mode, "100644"); + assert!(file.gitlink.is_none()); + + git(&root, &["clone", "-q", "workspace", "without-checkout"]); + let clone = root.join("without-checkout"); + let gitlink = clone.join("modules/library"); + let parent = ide_vcs::Repo::discover(&clone).unwrap().unwrap(); + assert_eq!(parent.diff_entry_at(&gitlink, "HEAD").unwrap().unwrap().gitlink, Some(committed)); + let unavailable = parent.diff_entry_at(&gitlink, "WT").unwrap().unwrap(); + assert_eq!(unavailable.mode, "160000"); + assert!(unavailable.gitlink.is_none()); +} + +#[test] +fn project_update_follows_detached_gitlinks_and_preserves_staged_changes() { + let temp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(temp.path()).unwrap(); + let upstream = root.join("upstream"); + let library = root.join("library"); + let leaf = root.join("leaf"); + init(&leaf, "leaf.txt"); + let leaf_before = commit(&leaf, "initial leaf"); + init(&library, "library.txt"); + git(&library, &["submodule", "add", "--", leaf.to_str().unwrap(), "vendor/leaf"]); + let module_before = commit(&library, "initial library"); + init(&upstream, "root.txt"); + git(&upstream, &["submodule", "add", "--", library.to_str().unwrap(), "modules/library"]); + let root_before = commit(&upstream, "initial root"); + + git(&root, &["clone", "-q", "--recurse-submodules", "upstream", "workspace"]); + let workspace = root.join("workspace"); + let module = workspace.join("modules/library"); + let nested = module.join("vendor/leaf"); + for repo in [&workspace, &module, &nested] { + git(repo, &["config", "protocol.file.allow", "always"]); + git(repo, &["config", "core.autocrlf", "false"]); + git(repo, &["config", "user.name", "Update fixture"]); + git(repo, &["config", "user.email", "test@example.com"]); + } + // Even when configured to recurse, Update Project owns sequencing and preservation. + git(&workspace, &["config", "submodule.recurse", "true"]); + fs::write(module.join("local.txt"), "staged local work\n").unwrap(); + git(&module, &["add", "local.txt"]); + fs::write(module.join("local.txt"), "staged local work\nextra unstaged line\n").unwrap(); + fs::write(nested.join("untracked.txt"), "untracked local work\n").unwrap(); + + fs::write(leaf.join("leaf.txt"), "updated leaf\n").unwrap(); + let leaf_after = commit(&leaf, "update leaf"); + follow(&library.join("vendor/leaf"), &leaf_after); + fs::write(library.join("library.txt"), "updated library\n").unwrap(); + let module_after = commit(&library, "update library and leaf pointer"); + follow(&upstream.join("modules/library"), &module_after); + fs::write(upstream.join("root.txt"), "updated root\n").unwrap(); + let root_after = commit(&upstream, "update root and library pointer"); + + let repos = Repos::discover(&workspace, &|_| false).unwrap(); + assert_eq!(repos.roots(), [workspace.clone(), module.clone(), nested.clone()]); + for repo in repos.all() { + repo.set_execution_allowed(true); + } + let plan = repos.project_update_plan(&[Some(workspace.clone())]).unwrap(); + let paths = plan.iter().map(|target| target.root.0.as_path()).collect::>(); + assert_eq!(paths, [workspace.as_path(), module.as_path(), nested.as_path()]); + assert!(!plan[0].detached_submodule); + assert!(plan[1].detached_submodule && plan[2].detached_submodule); + assert_eq!(plan[1].parent.as_ref().unwrap().0, workspace); + assert_eq!(plan[2].parent.as_ref().unwrap().0, module); + assert_eq!(repos.project_update_plan(&[Some(nested.clone())]).unwrap().len(), 1); + + let parent = repos.at_root(&workspace).unwrap(); + let child = repos.at_root(&module).unwrap(); + let grandchild = repos.at_root(&nested).unwrap(); + let cancel = CancellationToken::new(); + let output = |_| {}; + assert_eq!(parent.head().unwrap().1.as_deref(), Some(root_before.as_str())); + parent.pull_for_project_update(false, FetchTagsMode::Auto, &cancel, &output).unwrap(); + assert_eq!(parent.head().unwrap().1.as_deref(), Some(root_after.as_str())); + assert_eq!(child.head().unwrap().1.as_deref(), Some(module_before.as_str())); + assert_eq!(grandchild.head().unwrap().1.as_deref(), Some(leaf_before.as_str())); + child.update_from_superproject(parent, &cancel, &output).unwrap(); + grandchild.update_from_superproject(child, &cancel, &output).unwrap(); + assert_eq!(child.head().unwrap(), (None, Some(module_after))); + assert_eq!(grandchild.head().unwrap(), (None, Some(leaf_after))); + assert_eq!(git(&module, &["show", ":local.txt"]), "staged local work"); + assert_eq!(fs::read_to_string(module.join("local.txt")).unwrap(), "staged local work\nextra unstaged line\n"); + assert_eq!(fs::read_to_string(nested.join("untracked.txt")).unwrap(), "untracked local work\n"); + assert!(git(&module, &["stash", "list"]).is_empty()); + + git(&module, &["switch", "-qc", "local-topic"]); + assert_eq!(repos.project_update_plan(&[Some(workspace.clone())]).unwrap().len(), 1); + assert_eq!(repos.project_update_plan(&[]).unwrap().len(), 3); + let attached = repos.project_update_plan(&[Some(module.clone())]).unwrap(); + assert!(!attached[0].detached_submodule); + assert!(attached[1].detached_submodule); + assert!(child.update_from_superproject(parent, &cancel, &output).is_err()); + assert_eq!(child.head().unwrap().0.as_deref(), Some("local-topic")); + + git(&module, &["commit", "--no-gpg-sign", "-qam", "local topic work"]); + git(&module, &["branch", "--set-upstream-to=origin/main", "local-topic"]); + fs::write(library.join("library.txt"), "next upstream library\n").unwrap(); + let next = commit(&library, "advance library independently"); + child.pull_for_project_update(true, FetchTagsMode::Auto, &cancel, &output).unwrap(); + assert_eq!(child.head().unwrap().0.as_deref(), Some("local-topic")); + assert_eq!(git(&module, &["rev-parse", "HEAD^"]), next); + assert_eq!(git(&module, &["show", "HEAD:local.txt"]), "staged local work\nextra unstaged line"); +} diff --git a/crates/ide-vfs/src/watch.rs b/crates/ide-vfs/src/watch.rs index 01277a65c..2dd46d533 100644 --- a/crates/ide-vfs/src/watch.rs +++ b/crates/ide-vfs/src/watch.rs @@ -800,7 +800,10 @@ impl EventFilter { // registration event (`git init`, the first `git worktree add`); // they must surface even though the depth below them is handled // separately. - [one] => matches!(one.to_str(), Some("HEAD" | "index" | "packed-refs" | "refs" | "worktrees" | "info")), + [one] => matches!( + one.to_str(), + Some("HEAD" | "index" | "config" | "config.worktree" | "packed-refs" | "refs" | "worktrees" | "info") + ), [first, ..] => { let metadata = *first == "refs" // Linked-worktree gitdirs: a worktree added or removed below @@ -1480,6 +1483,9 @@ mod tests { assert_eq!(g("src/main.rs"), None); assert_eq!(g(".git/HEAD"), Some(true)); assert_eq!(g(".git/index"), Some(true)); + assert_eq!(g(".git/config"), Some(true)); + assert_eq!(g(".git/config.worktree"), Some(true)); + assert_eq!(g(".git/config.lock"), Some(false)); assert_eq!(g(".git/refs/heads/main"), Some(true)); assert_eq!(g(".git/refs/heads/main.lock"), Some(false)); assert_eq!(g(".git/objects/aa/bb"), Some(false)); diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index 4df90b15b..7f125782c 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -910,6 +910,7 @@ mod tests { "nonModal": true, "clearInitialMessage": false, "analyzeCode": true, + "postponeSlowChecks": true, "checkTodo": true, "reformat": false, "optimizeImports": false, @@ -924,6 +925,7 @@ mod tests { "disabledPluginChecks": [], "doubleClickOpensDiff": null, "includeChangesByDefault": true, + "commitAllWhenNothingStaged": true, "agentInstructions": "", "agent": "", "agentModel": "", @@ -977,13 +979,17 @@ mod tests { } #[test] - fn commit_default_inclusion_persists() { + fn commit_inclusion_options_persist() { let tmp = tempfile::tempdir().unwrap(); let store = SettingsStore::load(tmp.path(), None); assert!(store.effective().vcs.commit.include_changes_by_default); let settings = store.set(SettingsScope::Global, "vcs.commit.includeChangesByDefault", json!(false)).unwrap(); assert!(!settings.vcs.commit.include_changes_by_default); - assert!(!SettingsStore::load(tmp.path(), None).effective().vcs.commit.include_changes_by_default); + assert!(settings.vcs.commit.commit_all_when_nothing_staged); + store.set(SettingsScope::Global, "vcs.commit.commitAllWhenNothingStaged", json!(false)).unwrap(); + let reloaded = SettingsStore::load(tmp.path(), None).effective(); + assert!(!reloaded.vcs.commit.include_changes_by_default); + assert!(!reloaded.vcs.commit.commit_all_when_nothing_staged); } #[test] diff --git a/docs/en/guide/vcs.mdx b/docs/en/guide/vcs.mdx index cbab12b7b..1cb089dbb 100644 --- a/docs/en/guide/vcs.mdx +++ b/docs/en/guide/vcs.mdx @@ -40,10 +40,12 @@ It reads repository state (status, diffs, blame, log) in-process, and runs the ` ## Get a repository - **Git › Clone…** opens **Clone Repository**. Enter a **URL:** and **Directory:**, and optionally check **Shallow clone with a history truncated to** N commits. The **GitHub** source in the sidebar lists your GitHub repositories (see [GitHub](/en/guide/github)). +- Cloning includes nested submodules by default. To clone the main repository by itself, turn off **Recursively clone submodules** in **Settings › Version Control › Git**. +- In a shallow clone, use **Fetch Full History** in the **Git** menu or the **Log** tab to download the missing commits. - When creating a project, check **Create Git repository** in the New Project dialog. - **Git › Create Git Repository…** runs `git init` in a folder you pick (the project root by default) and registers the new repository right away; a repository created in the terminal is picked up the same way. -OpenIDEA finds the repository that contains the project and nested repositories up to four levels deep (skipping folders such as `node_modules`, `target` and `build`). Status, commit, fetch and update cover all of them; branch operations from the branches popup cover all of them too (see [Branches](#branches)); log actions work on the selected repository. Submodules show as nested repositories, without submodule commands. +OpenIDEA finds the repository that contains the project and nested repositories up to four levels deep (skipping folders such as `node_modules`, `target` and `build`). Status, commit, fetch and update cover all of them; branch operations from the branches popup cover all of them too (see [Branches](#branches)); log actions work on the selected repository. Submodules show as nested repositories. Update Project can update detached submodules with their parent repository. ## Commit changes @@ -72,7 +74,7 @@ Double-click a file (or press `Enter`) to see its diff; **Preview Diff** shows i ### Partial commits -To commit only part of a file, open its diff from the Commit tool window. Each changed block has an **Include in commit** checkbox in the gutter; uncheck the blocks to leave out. The file's checkbox in the tree becomes partly checked. OpenIDEA commits the selected blocks through a temporary index, so your working tree and staging area stay as they are. Selection works per block, not per line. +To commit only part of a file, open its diff from the Commit tool window. Use the **Include in commit** gutter checkbox to include or exclude a whole block. For individual lines, select them in the side-by-side or unified viewer and use **Include Selected Lines in Commit** or **Exclude Selected Lines from Commit** from the context menu. In the unified viewer, drag across deleted and added lines to select both at once. The file's checkbox in the tree shows partial inclusion. OpenIDEA commits the selection through a temporary index, preserving the working file and unrelated staged changes. The diff toolbar also has **Stage Change (git add hunk)** if you prefer the staging area. @@ -90,9 +92,19 @@ The gear button (**Commit Options**) next to **Commit** has: - **Author:** to commit as someone else (`Name `), and **Sign-off commit**. - **Commit Checks**: **Reformat code**, **Optimize imports**, **Cleanup** (applies fix-all code actions) and **Run Git hooks** (off adds `--no-verify`). -- **Advanced Commit Checks**: **Analyze code** (errors and warnings from the language servers) and **Check TODO** (TODO and FIXME in added lines). +- **Advanced Commit Checks**: **Analyze code** (errors and warnings from the language servers) and **Check TODO** (matches from **Settings › Editor › TODO** in changed lines). -Before committing, OpenIDEA also warns about committing in detached HEAD or during a rebase, file names that cause problems on other systems, files larger than 50 MB, and CRLF line endings. A warning stops the commit once; click **Commit Anyway** to go ahead. There is no "run tests" check. +Create named TODO filters in **Settings › Editor › TODO**. Choose one from **Configure** beside **Check TODO** to check only its patterns. The Commit tool window and TODO tool window save their selections separately for each project. **Review TODOs** opens a tab in the TODO tool window with every finding and a preview of the checked content. Open a finding to jump to its source or diff. If a selected file cannot be checked, the result lists the file and the reason so you can address it before retrying. + +In the Commit tool window, choose a run configuration and turn on **Run Tests** to add it to the advanced checks. OpenIDEA saves the selection locally for the project. Tests run against the current working tree, which can include changes outside the commit selection. Choose **Review Run Output** to open the failed run. + +**Run advanced checks after commit** lets a local commit finish before code analysis, TODO checks, and tests run in the background. The Push dialog shows their status for outgoing commits. **Commit and Push** and **Run Commit Checks** wait for the enabled checks to finish. + +Before committing, OpenIDEA also warns about committing in detached HEAD or during a rebase, file names that cause problems on other systems, files larger than 50 MB, and CRLF line endings. A warning stops the commit once; click **Commit Anyway** to go ahead. + +### Sign commits with GPG + +Open **Settings › Version Control › Git › Configure GPG Signature** in a trusted project. Choose the repository, enable **Sign commits with GPG**, and select an OpenPGP signing key. OpenIDEA saves the settings to that repository's Git config. Subsequent commits use the repository's configured signer. ### Modal commit @@ -132,12 +144,15 @@ Other ways to compare: Click the branch widget in the title bar (or **Git › Branches…**) to open the branches popup. Type to search branches and actions. The popup shows **Recent**, **Local**, **Remote** and **Tags**, and at the top **Update Project…**, **Commit…**, **Push…**, **New Branch…** and **Checkout Tag or Revision…**. The gear button toggles grouping by prefix, recent branches and tags. +**Checkout Tag or Revision…** suggests branches and tags shared by the affected repositories. You can also enter a commit hash or revision expression. With branch synchronization enabled, the top-level action detaches HEAD at the selected revision in each repository. Open the action from a repository submenu to scope it to that repository. + Click the incoming or outgoing marker next to the branch name in the title bar (or **Incoming and Outgoing Commits…** in the branches popup) to list the commits to pull or push, newest first. Click a commit for its diff, or **Open in Git Log** to show it in the Git log. Select a branch (`→` or `Enter`) for its actions: - **Checkout**, **New Branch from '…'…**, **Checkout and Rebase onto '…'** -- **Compare with '…'**, **Show Diff with Working Tree**, **Show History** + (local edits are restored after the rebase finishes or is aborted) +- **Compare with '…'** opens an editor tab with one Git Log for each direction. Each pane has its own filters and commit details. **Show Branch Diff** opens the file differences for the comparison. **Show Diff with Working Tree** and **Show History** are also available. - **Rebase '…' onto '…'**, **Merge '…' into '…'**, and for remote branches **Pull into '…' Using Rebase** / **Using Merge** - **Update**, **Push…**, **Rename…**, **Add to Favorites**, **Delete** @@ -159,13 +174,17 @@ HTTPS passwords and SSH passphrases are asked for in a dialog and can be remembe **Git › Merge…** and **Git › Rebase…** open dialogs with the common Git options (`--no-ff`, `--ff-only`, `--squash`, `--no-commit`; `--onto`, `--rebase-merges`, `--keep-empty`). While a merge, rebase, cherry-pick or revert is in progress, the title bar shows a widget with **Resolve Conflicts…** and **Continue** / **Abort**, and the Git menu enables **Abort Merge**, **Continue Rebase**, **Skip Commit**, **Abort Rebase** and the cherry-pick and revert equivalents. A merge is concluded by committing. +In **Git › Rebase…**, enable `--interactive` under **Modify options** to edit the replay plan. For a linear plan, select **Reword** to edit the commit message in the details pane before starting the rebase. OpenIDEA applies the edited messages as Git reaches each commit, including when you continue in the IDE after a conflict. Plans with merge instructions open in a text editor. + When conflicts appear, a notification and the **Conflicts** dialog list the files. For each file choose **Accept Yours**, **Accept Theirs** or **Merge…**. +While the Git operation is paused, the dialog keeps both unresolved and resolved files. Choose **Revert Resolved** in the dialog or the Commit view to reopen selected files. Review your resolutions before continuing the operation or committing the merge. + **Merge…** opens a three-way merge editor: your side, the result and their side. - Click the arrows in the gutter to accept a change, or the cross to ignore it. Hold the modifier key to resolve the whole conflict with one side. - The toolbar applies all non-conflicting changes (from the left, the right or both), **Resolve Simple Conflicts**, compares any two of the versions, and shows how many changes and conflicts remain. -- Click **Apply** to save the result and mark the file resolved, or **Accept Yours** / **Accept Theirs** for the whole file. +- Click **Apply** to save an edited text result and mark it resolved. **Accept Yours** and **Accept Theirs** take the entire chosen version, including binary files, file modes and deletions. The binary merge view offers these whole-file choices. Files with conflict markers show a banner with **Resolve conflicts…**, and the markers are reported as errors. **Accept Yours / Theirs / Both (Conflict at Caret)** resolve one conflict in the text editor. @@ -177,23 +196,33 @@ The **Log** tab of the Git tool window shows the commit graph. - **Go to Hash/Branch/Tag** (`⌘F` / `Ctrl+F` in the log). - **Graph Options**: sort by date, topologically or incoming first; first parent only; no merges. - **View Options**: reference display, details pane, and columns (**Author**, **Date**, **Hash**, **Signature**, **GitHub Commit Checks**). +- **View Options › Highlight › Not Cherry-Picked Commits**: choose a source branch or use the log's current branch filter. The log dims commits already present on the checked-out branch and keeps pending commits easy to spot. In **Compare with**, each pane compares its branch with the other branch. - The branches pane on the left filters the log by branch and has branch actions. Select several local branches and choose **Update Selected** to fast-forward each to its tracked branch, fetching each remote once; one notification lists the branches that were updated and those that could not be fast-forwarded or have no tracked branch. - With several repositories, the branches pane lists each branch once; a branch that only some repositories have shows their names after it in grey, and its actions run in those repositories. **Group by Repository** in the pane's toolbar shows one subtree per repository instead. - The details pane shows the changed files, the commit message, who committed it, which branches contain it and its signature. +- In the **Signature** column, hover over a badge to see the verification result, signer, and key fingerprint when available. After changing your verification keys or trust settings, click **Refresh** in the log toolbar to check again. -Right-click a commit for **Copy Revision Number** (`⌥⇧⌘C` / `Ctrl+Alt+Shift+C`), **Create Patch…**, **Cherry-Pick**, **Checkout Revision**, **Browse Repository at Revision**, **Compare with Local**, **Reset Current Branch to Here…**, **Revert Commit**, **Undo Commit…**, **New Branch…**, **New Tag…**, **View in Browser** and more. With two commits selected, **Compare Versions** diffs them. +Right-click a commit for **Copy Revision Number** (`⌥⇧⌘C` / `Ctrl+Alt+Shift+C`), **Create Patch…**, **Cherry-Pick**, **Checkout Revision**, **Show Repository at Revision**, **Compare with Local**, **Reset Current Branch to Here…**, **Revert Commit**, **Undo Commit…**, **New Branch…**, **New Tag…**, **View in Browser** and more. With two commits selected, **Compare Versions** diffs them. With the commit list focused, `F2` edits the commit message, `⌥⌘N` / `Ctrl+Alt+N` creates a branch, `←` / `→` go to the child or parent commit, and `F3` / `F11` toggles a commit bookmark (`⌥F3` / `Ctrl+F11` with a mnemonic). + +In the changed-files pane, use **Apply Selected Changes** to bring only the selected files' changes into the working tree. +Use **Extract Selected Changes** on part of a commit to move those files' changes into a new commit immediately after it. The operation preserves the tip's tree, local edits, and staged changes. The success notification offers **Undo** while HEAD still points to the rewritten tip. +Use **Drop Selected Changes** to remove those files' changes from that commit and replay later commits. If replay stops on a conflict, resolve it and continue the rebase, or abort to restore the original history. A drop that completes directly offers **Undo**. ### Rewrite history From the log you can **Edit Commit Message…**, **Fixup…**, **Squash Into…**, **Drop Commit**, **Squash Commits…** and **Interactively Rebase from Here…**. The interactive rebase dialog lets you pick, reword, edit, squash, fixup, drop and reorder commits. These actions also work for commits that are already pushed: rewriting them is confirmed first, and pushing afterwards needs a force push. Commits already pushed from a protected branch cannot be rewritten. -Limits: interactive rebase doesn't support ranges with merge commits, and **Undo Commit…** works only on the latest commit (its changes go back to a changelist). +**Interactively Rebase from Here…** in the log requires a linear range. **Undo Commit…** works on the latest commit and puts its changes back in a changelist. ### Tags, reset and worktrees - **Git › New Tag…** creates a tag on a commit (annotated when you enter a message). **New Tag…** in the log creates a lightweight tag. +- The tag menu offers **Push to** for each configured remote, including a new remote with no tracking branches. After local deletion, **Restore** recreates the original tag. **Delete on Remote** removes the tag only where it still points to the same commit or annotated tag object. - **Git › Reset HEAD…** and **Reset Current Branch to Here…** reset with **Soft**, **Mixed** (default), **Hard** or **Keep**. -- **Git › New Worktree…** and **Worktrees…** create, list, remove and open worktrees in a new window. +- Use **Git › New Worktree…** or the menu of a branch or tag to create a worktree. **Create and Open** opens it in a separate window. +- Use **Create .worktreeinclude…** or **Edit .worktreeinclude…** in **New Worktree** to open the selected repository's include file. List one Git ignore pattern per line. The editor banner can add OpenIDEA project settings and run configurations to an existing file. Choose **Return to New Worktree** to save the file and resume with your branch and path selections. When **Copy local files listed in .worktreeinclude** is selected, matching local files are copied and files already in the new checkout are preserved. +- Select **Run setup script** and choose an executable script on the project host to initialize the worktree. It runs after configuration is copied and receives the new worktree path as its first argument and working directory. **Skip Setup** stops it and keeps the checkout. A failed or timed-out script also leaves the worktree available. +- **Git › Worktrees…** opens the **Worktrees** tab. From there you can open, lock, unlock, move or remove a worktree. Select several worktrees of one repository to remove them together, or use **Prune Worktrees…** to clean up Git records for missing directories. ## Stash, shelf and patches @@ -201,7 +230,8 @@ Limits: interactive rebase doesn't support ranges with merge commits, and **Undo - **Stash Changes…**: a message, **Keep index** and **Include untracked files**; it stashes the whole working tree. **Stash Selected Files…** in the changes tree's context menu stashes only the selected files. - **Unstash Changes…**: apply or pop a stash, reinstate the index, or create a branch from it. -- The **Stash** tab of the Commit tool window lists stashes with apply, pop and drop. +- **Git › Uncommitted Changes › Show Stash** opens the stash list. Right-click a stash to apply, pop or drop it, use **Unstash As…** for options on that stash, or use **Clear Stashes…** to clear its repository's stashes. +- Select a stash to view its changes, including any untracked files, in the adjacent files pane. Select one or more files to show their diffs, compare them with local files, or use **Apply Selected Changes** to restore only those changes and keep the stash. **Shelf** is managed by the IDE and stored as patches in `.openidea/shelf`: @@ -243,7 +273,7 @@ Retention is set in the **Local History** section of **Settings › Appearance & | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Commit** | Non-modal commit interface, clearing the message after commit, message inspections (blank line after subject, subject and body length, right margin), default commit checks. | | **Confirmation** | What to do when files are created or deleted, **Show options before Update**, confirm before dropping commits, highlight modified folders in the Project view, history row limit. | -| **Directory Mappings** | The detected repositories (read-only). | +| **Directory Mappings** | Add and remove Git repository mappings and exclude auto-detected repositories from Git integration. | | **Issue Navigation** | Regex patterns that turn issue IDs in commit messages into links (presets for JIRA, YouTrack and GitHub). | | **Log** | Reference and time display, visible columns. | | **Shelf** | Remove applied files from the shelf. | @@ -253,6 +283,4 @@ Retention is set in the **Local History** section of **Settings › Appearance & ## Not supported - Mercurial, Subversion, Perforce and other systems. -- Submodule commands and editable directory mappings. -- Per-line partial commits (block level only). - Git LFS beyond the large-file warning. diff --git a/docs/zh/guide/vcs.mdx b/docs/zh/guide/vcs.mdx index bad3a577e..f89dd9469 100644 --- a/docs/zh/guide/vcs.mdx +++ b/docs/zh/guide/vcs.mdx @@ -40,10 +40,12 @@ OpenIDEA 内置 Git 支持,Git 也是它唯一支持的版本控制系统。 ## 获取仓库 - **Git › 克隆…** 打开 **克隆仓库**。填写 **URL:** 和 **目录:**,需要时勾选 **浅克隆,历史记录截断为** N 个提交。侧栏中的 **GitHub** 会列出你的 GitHub 仓库(见 [GitHub](/zh/guide/github))。 +- 克隆时默认包含嵌套子模块。如只需克隆主仓库,可在 **设置 › 版本控制 › Git** 中关闭 **递归克隆子模块**。 +- 对于浅克隆,可以在 **Git** 菜单或 **日志** 标签页选择 **获取完整历史**,下载缺失的提交。 - 新建项目时,在新建项目对话框中勾选 **创建 Git 仓库**。 - **Git › 创建 Git 仓库…** 会在你选择的目录(默认是项目根目录)里执行 `git init`,并立即注册这个新仓库;在终端里创建的仓库同样会被识别。 -OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓库(跳过 `node_modules`、`target`、`build` 等目录)。状态、提交、获取和更新覆盖所有仓库;分支弹窗中的分支操作同样覆盖所有仓库(见[分支](#分支));日志操作针对所选仓库。子模块显示为嵌套仓库,但没有子模块相关命令。 +OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓库(跳过 `node_modules`、`target`、`build` 等目录)。状态、提交、获取和更新覆盖所有仓库;分支弹窗中的分支操作同样覆盖所有仓库(见[分支](#分支));日志操作针对所选仓库。子模块显示为嵌套仓库。更新项目时,可以随父仓库一起更新处于分离 HEAD 的子模块。 ## 提交更改 @@ -70,7 +72,7 @@ OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓 ### 部分提交 -只想提交文件的一部分时,从提交工具窗口打开它的差异。每个变更块在边栏中都有 **包含在提交中** 复选框,取消勾选不想提交的块即可,树中该文件的复选框会变为部分选中。OpenIDEA 通过临时索引提交选中的块,工作区和暂存区都保持不变。选择粒度是代码块,不是单行。 +只想提交文件的一部分时,从提交工具窗口打开它的差异。用边栏的 **包含在提交中** 复选框选择整个变更块。要具体到单行,在并排或统一视图中选中这些行,然后使用右键菜单中的 **提交所选行** 或 **从提交中排除所选行**。在统一视图中,可拖过删除行和新增行一次选中两侧的改动。树中的复选框会显示部分选中的状态。OpenIDEA 通过临时索引提交选中的内容,保留工作区文件和其他已暂存的改动。 习惯使用暂存区的话,差异工具栏里也有 **暂存更改 (git add hunk)**。 @@ -88,9 +90,19 @@ OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓 - **作者:**:以其他身份提交(`Name `),以及 **签署提交**。 - **提交检查**:**重新格式化代码**、**优化导入**、**清理**(应用 fix-all 代码操作)和 **运行 Git 钩子**(关闭时加 `--no-verify`)。 -- **高级提交检查**:**分析代码**(语言服务器报告的错误和警告)和 **检查 TODO**(新增行中的 TODO 和 FIXME)。 +- **高级提交检查**:**分析代码**(语言服务器报告的错误和警告)和 **检查 TODO**(检查改动行是否匹配 **设置 › 编辑器 › TODO** 中的规则)。 -提交前,OpenIDEA 还会对以下情况发出警告:在分离 HEAD 或变基过程中提交、文件名在其他系统上可能有问题、文件大于 50 MB、CRLF 换行符。出现警告时第一次提交会被拦下,点击 **仍然提交** 继续。没有“运行测试”这一检查。 +在 **设置 › 编辑器 › TODO** 中创建命名筛选器,再通过 **检查 TODO** 旁的 **配置** 选择要检查的模式组。提交工具窗口和 TODO 工具窗口分别按项目保存选择。点击 **查看 TODO** 会在 TODO 工具窗口打开结果标签页,可以浏览全部匹配项和检查时的内容,并跳转到对应源码或差异。若所选文件无法检查,结果会列出文件和原因,便于处理后重试。 + +在提交工具窗口选择运行配置,再开启 **运行测试**,即可将其加入高级检查。配置选择保存在本地,按项目生效。测试针对当前工作树运行,可能包含本次未选中的改动。点击 **查看运行输出** 可打开失败的运行。 + +开启 **提交后运行高级检查** 后,本地提交完成后会在后台运行代码分析、TODO 检查和测试。推送对话框会显示待推送提交的检查状态。**提交并推送** 和 **运行提交检查** 会等待已启用的检查完成。 + +提交前,OpenIDEA 还会对以下情况发出警告:在分离 HEAD 或变基过程中提交、文件名在其他系统上可能有问题、文件大于 50 MB、CRLF 换行符。出现警告时第一次提交会被拦下,点击 **仍然提交** 继续。 + +### 使用 GPG 为提交签名 + +在受信任的项目中打开 **设置 › 版本控制 › Git › 配置 GPG 签名**。选择仓库,开启 **使用 GPG 为提交签名**,然后选择 OpenPGP 签名密钥。OpenIDEA 将设置保存到所选仓库的 Git 配置,后续提交使用该仓库配置的签名程序。 ### 模态提交 @@ -130,12 +142,15 @@ OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓 点击标题栏的分支微件(或 **Git › 分支…**)打开分支弹窗,输入文字即可搜索分支和操作。弹窗中有 **最近**、**本地**、**远程** 和 **标签** 分组,顶部有 **更新项目…**、**提交…**、**推送…**、**新建分支…** 和 **签出标签或修订…**。齿轮按钮可以切换按前缀分组、显示最近分支和显示标签。 +**签出标签或修订…** 会建议目标仓库共有的分支和标签,也支持输入提交哈希或修订表达式。开启分支同步后,顶层操作会在各仓库中将 HEAD 分离到所选修订。从某个仓库的子菜单打开时,操作只作用于该仓库。 + 点击标题栏分支名旁的传入或传出标记(或分支弹窗中的 **传入和传出的提交…**)即可列出待拉取或待推送的提交(最新的在前)。点击某个提交查看其差异,或点 **在 Git 日志中打开** 在 Git 日志中显示它。 选中分支(`→` 或 `Enter`)查看它的操作: - **签出**、**从 '…' 新建分支…**、**签出并变基到 '…'** -- **与 '…' 比较**、**显示与工作树的差异**、**显示历史记录** + (变基结束或中止后恢复本地改动) +- **与 '…' 比较**在编辑器中打开双面板 Git 日志。两侧各有独立的筛选和提交详情。点击 **显示分支差异** 可查看两个分支之间的文件差异。分支菜单还提供 **显示与工作树的差异** 和 **显示历史记录**。 - **将 '…' 变基到 '…'**、**将 '…' 合并到 '…'**;远程分支还有 **使用变基拉取到 '…'** / **使用合并拉取到 '…'** - **更新**、**推送…**、**重命名…**、**添加到收藏夹**、**删除** @@ -157,13 +172,17 @@ HTTPS 密码和 SSH 口令通过对话框询问,可以选择记住;保存的 **Git › 合并…** 和 **Git › 变基…** 打开对话框,提供常用的 Git 选项(`--no-ff`、`--ff-only`、`--squash`、`--no-commit`;`--onto`、`--rebase-merges`、`--keep-empty`)。合并、变基、拣选或还原进行中时,标题栏会显示一个微件,提供 **解决冲突…** 以及继续 / 中止;Git 菜单中的 **中止合并**、**继续变基**、**跳过提交**、**中止变基** 以及拣选、还原对应的操作也会变为可用。合并通过提交来完成。 +在 **Git › 变基…** 中,从 **修改选项** 启用 `--interactive` 即可编辑重放计划。在线性计划中,选择 **改写** 后,可以在开始变基前从详情区域编辑提交消息。OpenIDEA 会在 Git 重放到对应提交时应用改写后的消息,解决冲突后从 IDE 继续变基时也一样。包含合并指令的计划会在文本编辑器中打开。 + 出现冲突时,通知和 **冲突** 对话框会列出相关文件。对每个文件选择 **接受您的**、**接受他们的** 或 **合并…**。 +Git 操作暂停期间,冲突对话框会保留未解决和已解决的文件。可在对话框或提交视图中选择 **回退已解决的冲突** 重新打开选中的文件。检查结果后再继续操作或提交合并。 + **合并…** 打开三方合并编辑器:左侧是你的版本,中间是结果,右侧是他们的版本。 - 点击边栏中的箭头接受某处更改,点叉号忽略它。按住修饰键可以用某一侧解决整个冲突。 - 工具栏可以应用所有不冲突的更改(左侧、右侧或两侧)、**解决简单冲突**、任意比较其中两个版本,并显示剩余的更改和冲突数。 -- 点击 **应用** 保存结果并标记为已解决,或者对整个文件选择 **接受您的** / **接受他们的**。 +- 点击 **应用** 保存编辑后的文本结果并标记为已解决。**接受您的** 和 **接受他们的** 会采用所选一侧的完整版本,包括二进制内容、文件模式或删除操作。二进制合并视图也提供这两个选项。 带冲突标记的文件顶部会显示横幅和 **解决冲突…**,冲突标记也会作为错误报告。在文本编辑器中,**接受您的(光标处的冲突)**、**接受他们的(光标处的冲突)**、**全部接受(光标处的冲突)** 可以逐个解决冲突。 @@ -175,23 +194,33 @@ Git 工具窗口的 **日志** 标签页显示提交图。 - **转到哈希/分支/标签**(在日志中按 `⌘F` / `Ctrl+F`)。 - **图形选项**:按日期、拓扑或传入优先排序;仅第一父提交;不显示合并提交。 - **视图选项**:引用显示方式、详情面板,以及列(**作者**、**日期**、**哈希**、**签名**、**GitHub 提交检查**)。 +- **视图选项 › 高亮 › 未拣选的提交**:选择源分支,或使用日志当前筛选的分支。日志会淡化已进入签出分支的提交,方便查看仍待拣选的提交。在分支比较中,每个面板以另一侧的分支为比较目标。 - 左侧的分支面板可以按分支过滤日志,并提供分支操作。选中多个本地分支后选择 **Update Selected**,会把每个分支快进到它的跟踪分支,每个远程只 fetch 一次;结果汇总在一条通知里,列出已更新的分支,以及因不能快进或没有跟踪分支而未更新的分支。 - 有多个仓库时,分支面板中每个分支只列一次;只存在于部分仓库的分支,后面会以灰字列出这些仓库,对它的操作会在这些仓库中执行。点击面板工具栏中的**按仓库分组**,可改为每个仓库一棵子树。 - 详情面板显示变更文件、提交消息、提交者、包含该提交的分支以及签名。 +- 将鼠标悬停在 **签名** 列的图标上,可查看验签结果,以及可用的签名者和密钥指纹。更改验签密钥或信任设置后,点击日志工具栏的 **刷新** 重新验签。 -右键提交可以选择 **复制修订号**(`⌥⇧⌘C` / `Ctrl+Alt+Shift+C`)、**创建补丁…**、**拣选**、**签出修订**、**浏览此修订版本的仓库**、**与本地比较**、**将当前分支重置到此处…**、**还原提交**、**撤消提交…**、**新建分支…**、**新建标签…**、**在浏览器中查看** 等。选中两个提交时,**比较版本** 会比较它们。 +右键提交可以选择 **复制修订号**(`⌥⇧⌘C` / `Ctrl+Alt+Shift+C`)、**创建补丁…**、**拣选**、**签出修订**、**显示此修订版本的仓库**、**与本地比较**、**将当前分支重置到此处…**、**还原提交**、**撤消提交…**、**新建分支…**、**新建标签…**、**在浏览器中查看** 等。选中两个提交时,**比较版本** 会比较它们。提交列表获得焦点时,`F2` 编辑提交消息,`⌥⌘N` / `Ctrl+Alt+N` 新建分支,`←` / `→` 跳到子提交或父提交,`F3` / `F11` 切换提交书签(`⌥F3` / `Ctrl+F11` 带助记符)。 ### 改写历史 在日志中可以 **编辑提交消息…**、**修补提交…**、**压缩到…**、**丢弃提交**、**压缩提交…** 和 **从此处进行交互式变基…**。交互式变基对话框可以对提交执行 pick、reword、edit、squash、fixup、drop,并调整顺序。这些操作也可以用于已推送的提交:改写前会先确认,之后推送需要强制推送。受保护分支上已推送的提交不能被改写。 -限制:交互式变基不支持包含合并提交的范围;**撤消提交…** 只能用于最新的提交(其更改会放回某个更改列表)。 +日志中的 **从此处进行交互式变基…** 要求提交范围是线性的。**撤消提交…** 可用于最新的提交,并将其更改放回更改列表。 + +在更改文件窗格里选择 **应用所选更改**,可将选中文件的变更应用到工作区。 +选择提交中的部分文件后,可用 **提取所选更改** 将这些文件的变更移到紧接原提交的新提交中。分支末端的文件内容、本地修改和暂存区都会保留。HEAD 仍指向改写后的末端时,可以从成功通知中撤销提取。 +用 **移除所选更改** 可从该提交移除这些文件的变更,再重放后续提交。遇到冲突时可以解决后继续变基,也可以中止以恢复原历史。操作直接完成后可从通知中撤销。 ### 标签、重置与工作树 - **Git › 新建标签…** 在某个提交上创建标签(填写消息时为附注标签)。日志中的 **新建标签…** 创建轻量标签。 +- 标签菜单的 **推送到** 列出已配置的远程,包括尚无跟踪分支的远程。删除本地标签后,**恢复** 可重建原标签。**在远程删除** 只会删除仍指向原提交或原附注标签对象的远程标签。 - **Git › 重置 HEAD…** 和 **将当前分支重置到此处…** 支持 **软**、**混合**(默认)、**硬** 和 **保留** 四种模式。 -- **Git › 新建工作树…** 和 **工作树…** 用于创建、列出、删除工作树,以及在新窗口中打开。 +- 从 **Git › 新建工作树…** 或分支、标签的菜单创建工作树。选择 **创建并打开** 会在独立窗口打开它。 +- 在 **新建工作树** 中选择 **创建 .worktreeinclude…** 或 **编辑 .worktreeinclude…**,打开所选仓库的配置文件。每行写一条 Git 忽略规则。编辑器横幅可将 OpenIDEA 项目设置和运行配置加入现有文件。点击 **返回新建工作树** 会保存文件,并保留已选的分支和路径。勾选 **复制 .worktreeinclude 中列出的本地文件** 后,匹配的本地文件会复制过去,新工作树中已有的文件会保留。 +- 选中 **运行初始化脚本** 并选择项目所在主机上的可执行脚本。脚本在配置复制完成后运行,以新工作树为工作目录,首个参数也是新工作树路径。**跳过初始化** 会停止脚本并保留工作树。脚本失败或超时也会保留工作树。 +- **Git › 工作树…** 打开 **工作树** 标签页,可在这里打开、锁定、解锁、移动或移除工作树。同一仓库的工作树可以多选后一起移除。用 **清理工作树…** 可清理目录已缺失的 Git 记录。 ## 贮藏、搁置与补丁 @@ -199,7 +228,8 @@ Git 工具窗口的 **日志** 标签页显示提交图。 - **贮藏更改…**:填写消息,可选 **保留索引** 和 **包括未跟踪的文件**,贮藏整个工作区;更改树右键菜单中的 **贮藏所选文件…** 只贮藏选中的文件。 - **取消贮藏更改…**:应用或弹出某个贮藏,恢复索引,或基于它新建分支。 -- 提交工具窗口的 **贮藏** 标签页列出所有贮藏,可以应用、弹出和删除。 +- **Git › 未提交的更改 › 显示储藏** 打开储藏列表。右键选中的储藏可以应用、弹出或丢弃它,也可以用 **恢复储藏为…** 设置恢复选项,或用 **清空储藏…** 清空它所属仓库的储藏。 +- 选择储藏后,可在相邻的文件窗格中查看更改,包括一并保存的未跟踪文件。可选择一个或多个文件查看差异、与本地文件比较,或使用 **应用所选更改** 仅恢复选中的更改并保留储藏。 **搁置** 由 IDE 管理,以补丁形式保存在 `.openidea/shelf` 中: @@ -241,7 +271,7 @@ Git 工具窗口的 **日志** 标签页显示提交图。 | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **提交** | 非模态提交界面、提交后清空消息、提交消息检查(主题与正文之间空行、主题和正文长度、右边距)、默认提交检查。 | | **确认** | 新建或删除文件时的处理方式、**更新前显示选项**、丢弃提交前确认、在项目视图中高亮包含修改的目录、历史记录行数上限。 | -| **目录映射** | 检测到的仓库(只读)。 | +| **目录映射** | 添加和移除 Git 仓库映射,或将自动检测到的仓库排除在 Git 集成之外。 | | **问题导航** | 把提交消息中的问题编号变成链接的正则规则(内置 JIRA、YouTrack 和 GitHub 预设)。 | | **日志** | 引用和时间的显示方式、显示哪些列。 | | **搁置** | 应用后从搁置中移除文件。 | @@ -251,6 +281,4 @@ Git 工具窗口的 **日志** 标签页显示提交图。 ## 暂不支持 - Mercurial、Subversion、Perforce 等其他版本控制系统。 -- 子模块命令、编辑目录映射。 -- 按行的部分提交(只支持按代码块)。 - 除大文件警告外的 Git LFS 支持。 diff --git a/e2e/applyPatchLayout.spec.ts b/e2e/applyPatchLayout.spec.ts index bcf7d5187..8b727e50b 100644 --- a/e2e/applyPatchLayout.spec.ts +++ b/e2e/applyPatchLayout.spec.ts @@ -1,5 +1,5 @@ import type { Page } from "@playwright/test"; -import type { PatchFile } from "../src/bindings"; +import type { ChangelistState, PatchDirectoryMatches, PatchFile, PatchPathMapping } from "../src/bindings"; import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; const repo = "/dev/billing"; @@ -13,25 +13,79 @@ const invoice: PatchFile = { removed: 1, binary: false, applies: true, + missingBase: false, }; -async function openPatch(page: Page, source: "file" | "clipboard", files: PatchFile[]) { +async function openPatch( + page: Page, + source: "file" | "clipboard", + files: PatchFile[], + project?: string, + discovery?: { directoryMatches: PatchDirectoryMatches[]; automaticMappings: PatchPathMapping[] }, +) { await page.evaluate( - async ({ source, repo, path, patch, files }) => { + async ({ source, repo, path, patch, files, project, discovery }) => { const handlers = window.__ipc.handlers; - handlers.fs_read_text = () => patch; + handlers.vcs_read_patch = () => patch; handlers.clipboard_text = () => patch; - handlers.vcs_patch_preview = () => files; + handlers.vcs_patch_preview = ({ target, mappings }) => { + const manual = (mappings ?? []) as PatchPathMapping[]; + const automaticMappings = + target === null + ? (discovery?.automaticMappings ?? []).filter((entry) => !manual.some((m) => m.path === entry.path)) + : []; + const effective = [...manual, ...automaticMappings]; + const mapping = (file: PatchFile) => effective.find((entry) => entry.path === file.path); + return { + files: files.map((file) => { + const map = mapping(file); + const resolved = !!(map?.file || map?.directory); + const applies = target !== "repository" && (file.applies || resolved); + return { ...file, applies, missingBase: file.missingBase && !resolved }; + }), + base: target === "repository" ? null : (project ?? null), + placements: effective.length + ? files.map((file) => { + const map = mapping(file); + return { + path: file.path, + target: + map?.file ?? + `${map?.directory ?? project ?? repo}/${file.path + .split("/") + .slice(map?.strip ?? 0) + .join("/")}`, + error: null, + }; + }) + : null, + directoryMatches: discovery?.directoryMatches ?? [], + automaticMappings, + }; + }; handlers.vcs_apply_patch = () => ({ applied: [files[0]?.path], conflicts: [] }); + handlers.vcs_apply_project_patch = ({ paths }) => ({ + outcome: { applied: paths ?? files.map((file) => file.path), conflicts: [] }, + conflictedRepositories: [], + failures: [], + }); + handlers.vcs_apply_mapped_patch = handlers.vcs_apply_project_patch; const store = "/src/features/vcs/store.ts"; const context = "/src/platform/context.ts"; const actions = "/src/platform/actions.ts"; - (await import(/* @vite-ignore */ store)).useVcs.setState({ available: true, root: repo, repo, roots: [repo] }); + const changelists = "/src/features/vcs/changelists.ts"; + (await import(/* @vite-ignore */ changelists)).useChangelists.setState({ loaded: true }); + (await import(/* @vite-ignore */ store)).useVcs.setState({ + available: true, + root: project ?? repo, + repo, + roots: project ? [repo, `${project}/reports`] : [repo], + }); (await import(/* @vite-ignore */ context)).setContext("vcsAvailable", true); const { executeAction } = await import(/* @vite-ignore */ actions); await executeAction(source === "file" ? "vcs.applyPatch" : "vcs.applyPatchFromClipboard", path); }, - { source, repo, path, patch, files }, + { source, repo, path, patch, files, project, discovery }, ); } @@ -48,7 +102,7 @@ test("Apply Patch keeps the source, repository and file status aligned in a narr const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true }); const source = dialog.getByRole("textbox", { name: "Patch source", exact: true }); const target = dialog.getByRole("textbox", { name: "Repository", exact: true }); - const list = dialog.getByRole("listbox", { name: "Patch files", exact: true }); + const list = dialog.getByRole("tree", { name: "Patch files", exact: true }); await expect(source).toHaveValue(path); await expect(source).not.toBeEditable(); @@ -91,5 +145,489 @@ test("Apply Patch previews clipboard contents and applies them to the previewed await expect(apply).toBeEnabled(); await apply.click(); await expect(dialog).toBeHidden(); - await expect.poll(() => ipcCalls(page, "vcs_apply_patch")).toEqual([{ repo, patch }]); + await expect.poll(() => ipcCalls(page, "vcs_apply_patch")).toEqual([{ repo, patch, paths: null }]); +}); + +test("Apply Patch applies only included files and updates the merge count", async ({ workbench: page }) => { + await stubDesktop(page); + const receipt = { ...invoice, path: "ledger/receipt.ts", applies: false }; + await openPatch(page, "file", [invoice, receipt]); + const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true }); + const apply = dialog.getByRole("button", { name: "Apply", exact: true }); + const all = dialog.getByRole("checkbox", { name: "Include all files", exact: true }); + const receiptBox = dialog.getByRole("checkbox", { name: `Include ${receipt.path}`, exact: true }); + await expect(all).toBeChecked(); + await expect(dialog.getByRole("status")).toBeVisible(); + await all.uncheck(); + await expect(apply).toBeDisabled(); + await expect(dialog.getByRole("status")).toHaveCount(0); + await all.check(); + await expect(receiptBox).toBeChecked(); + const tree = dialog.getByRole("tree", { name: "Patch files", exact: true }); + await tree.press("End"); + await tree.press("Space"); + await expect(receiptBox).not.toBeChecked(); + await expect(all).toHaveAttribute("aria-checked", "mixed"); + await expect(dialog.getByRole("status")).toHaveCount(0); + await expect(dialog.getByText("1 of 2 selected")).toBeVisible(); + await apply.click(); + await expect(dialog).toBeHidden(); + await expect.poll(() => ipcCalls(page, "vcs_apply_patch")).toEqual([{ repo, patch, paths: [invoice.path] }]); +}); + +test("Apply Patch opens a read-only diff for the selected row and loads its neighbours on demand", async ({ + workbench: page, +}) => { + await stubDesktop(page); + const project = "/dev"; + const billing = { ...invoice, path: "billing/invoice.ts" }; + const reports = { ...invoice, path: "reports/invoice.ts", applies: false }; + const notes = { ...invoice, path: "reports/notes.ts", applies: false }; + await page.evaluate( + ({ billing, reports, project }) => { + window.__ipc.handlers.vcs_patch_file_diff = ({ path }) => ({ + path: `${project}/${path}`, + oldPath: null, + content: + path === billing + ? { kind: "text", before: "const total = 100;\n", after: "const total = 120;\n" } + : path === reports + ? { + kind: "conflict", + local: "const cap = 140;\n", + base: "const cap = 100;\n", + patched: "const cap = 120;\n", + } + : { + kind: "raw", + local: "const total = 90;\n", + patch: "@@ -1 +1 @@\n-const total = 100;\n+const total = 120;\n", + applies: false, + }, + }); + }, + { billing: billing.path, reports: reports.path, project }, + ); + await openPatch(page, "file", [billing, reports, notes], project); + const apply = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true }); + const includeBilling = apply.getByRole("checkbox", { name: `Include ${billing.path}`, exact: true }); + await includeBilling.uncheck(); + expect(await ipcCalls(page, "vcs_patch_file_diff")).toEqual([]); + await apply.getByRole("button", { name: "Show Diff", exact: true }).click(); + const diff = (path: string) => page.getByRole("dialog", { name: `Patch Diff: ${path}`, exact: true }); + const clean = diff(billing.path); + await expect(clean.locator(".cm-content").first()).toContainText("const total = 100;"); + await expect(clean.locator(".cm-content").last()).toContainText("const total = 120;"); + await expect(clean.locator(".cm-content").last()).not.toBeEditable(); + expect(await ipcCalls(page, "vcs_patch_file_diff")).toEqual([ + { repo, base: project, patch, path: billing.path, mappings: null }, + ]); + + await clean.getByRole("button", { name: "Compare Next File", exact: true }).click(); + const conflict = diff(reports.path); + await expect(conflict.locator('.cm-content[aria-label="Local Version"]')).toContainText("const cap = 140;"); + await expect(conflict.locator('.cm-content[aria-label="Base"]')).toContainText("const cap = 100;"); + await expect(conflict.locator('.cm-content[aria-label="Patched Version"]')).toContainText("const cap = 120;"); + await conflict.getByRole("button", { name: "Close", exact: true }).last().click(); + await expect(includeBilling).not.toBeChecked(); + const tree = apply.getByRole("tree", { name: "Patch files", exact: true }); + await tree.press("End"); + await tree.press("Meta+d"); + const fallback = diff(notes.path); + await expect(fallback.getByRole("status")).toHaveText("The patch does not match the local file."); + await expect(fallback.getByText("+const total = 120;", { exact: false })).toBeVisible(); + await fallback.getByRole("button", { name: "Close", exact: true }).last().click(); + await expect(apply).toBeVisible(); + await expect(includeBilling).not.toBeChecked(); + expect(await ipcCalls(page, "vcs_apply_patch")).toEqual([]); + expect(await ipcCalls(page, "vcs_apply_project_patch")).toEqual([]); + expect(await ipcCalls(page, "vcs_patch_file_diff")).toEqual( + [billing, reports, notes].map((file) => ({ repo, base: project, patch, path: file.path, mappings: null })), + ); +}); + +test("Apply Patch keeps project mappings through preview, target changes and partial selection", async ({ + workbench: page, +}) => { + await stubDesktop(page); + const project = "/dev"; + const billing = { ...invoice, path: "billing/invoice.ts" }; + const reports = { ...invoice, path: "reports/invoice.ts" }; + await openPatch(page, "file", [billing, reports], project); + const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true }); + const target = dialog.getByRole("button", { name: "Patch target", exact: true }); + await expect(target).toHaveText("Project paths"); + await expect(target).toHaveAttribute("title", project); + await expect(dialog.getByRole("status")).toHaveCount(0); + await target.click(); + await page.getByRole("option", { name: /^reports/ }).click(); + await expect(target).toHaveText("reports"); + await expect(dialog.getByRole("status")).toContainText("2 files will be merged"); + await target.click(); + await page.getByRole("option", { name: /^Project paths/ }).click(); + await expect(target).toHaveText("Project paths"); + await expect(dialog.getByRole("status")).toHaveCount(0); + const excluded = dialog.getByRole("checkbox", { name: `Include ${reports.path}`, exact: true }); + await excluded.uncheck(); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect(dialog).toBeHidden(); + await expect + .poll(() => ipcCalls(page, "vcs_apply_project_patch")) + .toEqual([{ base: project, patch, paths: [billing.path] }]); + expect(await ipcCalls(page, "vcs_apply_patch")).toEqual([]); + expect(await ipcCalls(page, "vcs_patch_preview")).toEqual([ + { repo, patch, target: null, mappings: null }, + { repo: "/dev/reports", patch, target: "repository", mappings: null }, + { repo, patch, target: "project", mappings: null }, + ]); +}); + +test("Apply Patch maps a selected file and strips path components for both Diff and Apply", async ({ + workbench: page, +}) => { + await stubDesktop(page); + const project = "/dev"; + const directory = "/dev/reports/incoming"; + const moved = { + ...invoice, + path: "legacy/deep/renamed.ts", + oldPath: "legacy/deep/original.ts", + kind: "renamed" as const, + }; + await page.evaluate( + ({ directory, path }) => { + const handlers = window.__ipc.handlers; + handlers["plugin:dialog|open"] = () => directory; + handlers.vcs_patch_file_diff = () => ({ + path: `${directory}/${path}`, + oldPath: `${directory}/original.ts`, + content: { kind: "text", before: "const rate = 1;\n", after: "const rate = 2;\n" }, + }); + }, + { directory, path: "renamed.ts" }, + ); + await openPatch(page, "file", [invoice, moved], project); + const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true }); + const other = dialog.getByRole("checkbox", { name: `Include ${invoice.path}`, exact: true }); + const row = dialog.getByRole("treeitem").filter({ hasText: "renamed.ts" }); + const menu = dialog.getByRole("button", { name: "Change Directory Paths", exact: true }); + await other.uncheck(); + await row.click(); + await menu.click(); + await page.getByRole("menuitem", { name: "Map Directory…", exact: true }).click(); + const displayed = "reports/incoming"; + await expect(row.getByText(`${displayed}/legacy/deep`, { exact: true })).toBeVisible(); + + await row.click({ button: "right" }); + await page.getByRole("menuitem", { name: "Remove All Leading Directories", exact: true }).click(); + await expect(row.getByText(displayed, { exact: true })).toBeVisible(); + await menu.click(); + await page.getByRole("menuitem", { name: "Restore Leading Directory", exact: true }).click(); + await expect(row.getByText(`${displayed}/deep`, { exact: true })).toBeVisible(); + await menu.click(); + await page.getByRole("menuitem", { name: "Remove Leading Directory", exact: true }).click(); + await expect(row.getByText(displayed, { exact: true })).toBeVisible(); + await expect(other).not.toBeChecked(); + + const mappings = [{ path: moved.path, directory, strip: 2, file: null }]; + await row.dblclick(); + const diff = page.getByRole("dialog", { name: /^Patch Diff: .*incoming\/renamed\.ts$/ }); + await expect(diff.locator(".cm-content").last()).toContainText("const rate = 2;"); + expect(await ipcCalls(page, "vcs_patch_file_diff")).toEqual([ + { repo, base: project, patch, path: moved.path, mappings }, + ]); + await diff.getByRole("button", { name: "Close", exact: true }).last().click(); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_apply_mapped_patch")) + .toEqual([{ repo, base: project, patch, paths: [moved.path], mappings }]); + expect(await ipcCalls(page, "vcs_apply_project_patch")).toEqual([]); + expect(await ipcCalls(page, "vcs_apply_patch")).toEqual([]); +}); + +test("Apply Patch lets a missing base use an existing file without renaming it", async ({ workbench: page }) => { + await stubDesktop(page); + const missing = { + ...invoice, + path: "legacy/renamed.ts", + oldPath: "legacy/original.ts", + kind: "renamed" as const, + applies: false, + missingBase: true, + }; + const replacement = "/dev/billing/current/local name.ts"; + await page.evaluate((replacement) => { + const handlers = window.__ipc.handlers; + let choices = 0; + handlers["plugin:dialog|open"] = () => (++choices < 3 ? null : replacement); + handlers.vcs_patch_file_diff = () => ({ + path: replacement, + oldPath: null, + content: { kind: "text", before: "const rate = 1;\n", after: "const rate = 2;\n" }, + }); + }, replacement); + await openPatch(page, "file", [missing, invoice]); + const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true }); + const include = dialog.getByRole("checkbox", { name: `Include ${missing.path}`, exact: true }); + await dialog.getByRole("checkbox", { name: `Include ${invoice.path}`, exact: true }).uncheck(); + const tree = dialog.getByRole("tree", { name: "Patch files", exact: true }); + await tree.press("Home"); + await expect(include).toBeDisabled(); + await expect(include).not.toBeChecked(); + await expect(dialog.getByRole("button", { name: "Apply", exact: true })).toBeDisabled(); + await expect(dialog.getByRole("button", { name: "Show Diff", exact: true })).toBeDisabled(); + await expect(dialog.getByText(/will be merged/)).toHaveCount(0); + + await dialog.getByRole("button", { name: "Select missing base…", exact: true }).click(); + await expect.poll(() => ipcCalls(page, "plugin:dialog|open")).toHaveLength(1); + await expect(include).toBeDisabled(); + await tree.press("Home"); + await tree.press("Space"); + await expect.poll(() => ipcCalls(page, "plugin:dialog|open")).toHaveLength(2); + await expect(include).toBeDisabled(); + await tree.getByRole("treeitem").filter({ hasText: "renamed.ts" }).dblclick(); + await expect(tree.getByText("local name.ts", { exact: true })).toBeVisible(); + await expect(include).toBeChecked(); + + const mappings = [{ path: missing.path, directory: null, strip: 0, file: replacement }]; + const row = tree.getByRole("treeitem").filter({ hasText: "local name.ts" }); + await row.dblclick(); + const diff = page.getByRole("dialog", { name: /^Patch Diff: .*local name\.ts$/ }); + await expect(diff.locator(".cm-content").last()).toContainText("const rate = 2;"); + expect(await ipcCalls(page, "vcs_patch_file_diff")).toEqual([ + { repo, base: null, patch, path: missing.path, mappings }, + ]); + await diff.getByRole("button", { name: "Close", exact: true }).last().click(); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_apply_mapped_patch")) + .toEqual([{ repo, base: null, patch, paths: [missing.path], mappings }]); +}); + +test("Apply Patch detects a matching directory and leaves equally good matches for review", async ({ + workbench: page, +}) => { + await stubDesktop(page); + const missing = { ...invoice, applies: false, missingBase: true }; + const settings = { ...missing, path: "checkout/src/settings.ts" }; + const report = { ...missing, path: "checkout/src/report.ts" }; + const candidate = (directory: string, name: string, applies: boolean) => ({ + directory, + source: `${directory}/src/${name}.ts`, + strip: 1, + applies, + }); + const suggested = candidate("/dev/billing/current", "settings", true); + const alpha = candidate("/dev/reports/alpha", "report", true); + const beta = candidate("/dev/reports/beta", "report", true); + const auto = { path: settings.path, directory: suggested.directory, strip: 1, file: null }; + const chosen = { path: report.path, directory: beta.directory, strip: 1, file: null }; + await page.evaluate((target) => { + window.__ipc.handlers.vcs_patch_file_diff = () => ({ + path: target, + oldPath: null, + content: { kind: "text", before: "const total = 10;\n", after: "const total = 15;\n" }, + }); + }, beta.source); + await openPatch(page, "file", [settings, report], "/dev", { + automaticMappings: [auto], + directoryMatches: [ + { path: settings.path, candidates: [suggested, candidate("/dev/reports/other", "settings", false)] }, + { path: report.path, candidates: [alpha, beta] }, + ], + }); + const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true }); + const tree = dialog.getByRole("tree", { name: "Patch files", exact: true }); + const mapped = tree.getByRole("treeitem").filter({ hasText: "settings.ts" }); + await expect(mapped.getByText("billing/current/src", { exact: true })).toBeVisible(); + await expect(mapped.getByRole("checkbox")).toBeChecked(); + const review = tree.getByRole("treeitem").filter({ hasText: "report.ts" }); + await expect(review.getByRole("checkbox")).toBeDisabled(); + await review.getByRole("button", { name: "Choose matching directory…", exact: true }).click(); + const menu = page.getByRole("menu", { name: "Choose Matching Directory", exact: true }); + await expect(menu.getByRole("menuitemcheckbox", { name: "reports/alpha/src/report.ts" })).toBeVisible(); + await expect(menu.getByRole("menuitem", { name: "Choose Directory…", exact: true })).toBeVisible(); + await menu.getByRole("menuitemcheckbox", { name: "reports/beta/src/report.ts" }).click(); + await expect(review.getByText("reports/beta/src", { exact: true })).toBeVisible(); + await expect(review.getByRole("checkbox")).toBeChecked(); + await expect(mapped.getByRole("checkbox")).toBeChecked(); + await review.dblclick(); + const diff = page.getByRole("dialog", { name: /^Patch Diff: .*beta\/src\/report\.ts$/ }); + await expect(diff.locator(".cm-content").last()).toContainText("const total = 15;"); + const mappings = [chosen, auto]; + expect(await ipcCalls(page, "vcs_patch_file_diff")).toEqual([ + { repo, base: "/dev", patch, path: report.path, mappings }, + ]); + await diff.getByRole("button", { name: "Close", exact: true }).last().click(); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_apply_mapped_patch")) + .toEqual([{ repo, base: "/dev", patch, paths: null, mappings }]); +}); + +test("Apply Patch keeps a new file selected when its directory has several matches", async ({ workbench: page }) => { + await stubDesktop(page); + const welcome = { ...invoice, kind: "added" as const, path: "checkout/mail/templates/emails/welcome.txt" }; + const banner = { ...invoice, kind: "added" as const, path: "checkout/widgets/templates/banner.txt" }; + const mappedDirectory = "/dev/billing/modules"; + const alpha = "/dev/billing/alpha"; + const beta = "/dev/reports/beta"; + const candidate = (directory: string, path: string) => ({ + directory, + source: `${directory}/${path.split("/").slice(1).join("/")}`, + strip: 1, + applies: true, + }); + const auto = { path: welcome.path, directory: mappedDirectory, strip: 1, file: null }; + const chosen = { path: banner.path, directory: beta, strip: 1, file: null }; + await openPatch(page, "file", [welcome, banner], "/dev", { + automaticMappings: [auto], + directoryMatches: [ + { path: welcome.path, candidates: [candidate(mappedDirectory, welcome.path)] }, + { path: banner.path, candidates: [candidate(alpha, banner.path), candidate(beta, banner.path)] }, + ], + }); + const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true }); + const tree = dialog.getByRole("tree", { name: "Patch files", exact: true }); + const added = tree.getByRole("treeitem").filter({ hasText: "welcome.txt" }); + await expect(added.getByText("billing/modules/mail/templates/emails", { exact: true })).toBeVisible(); + const review = tree.getByRole("treeitem").filter({ hasText: "banner.txt" }); + await expect(review.getByRole("checkbox")).toBeChecked(); + await expect(review.getByText("checkout/widgets/templates", { exact: true })).toBeVisible(); + await review.click({ button: "right" }); + await page.getByRole("menuitem", { name: "Map Directory…", exact: true }).click(); + await page.getByRole("menuitemcheckbox", { name: "reports/beta/widgets/templates/banner.txt", exact: true }).click(); + await expect(review.getByText("reports/beta/widgets/templates", { exact: true })).toBeVisible(); + await expect(review.getByRole("checkbox")).toBeChecked(); + await expect(added.getByRole("checkbox")).toBeChecked(); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_apply_mapped_patch")) + .toEqual([{ repo, base: "/dev", patch, paths: null, mappings: [chosen, auto] }]); +}); + +test("Apply Patch assigns only successful and conflicted files to the chosen changelist", async ({ + workbench: page, +}) => { + await stubDesktop(page); + const saved = { ...invoice, path: "billing/invoice.ts" }; + const added = { ...invoice, kind: "added" as const, path: "legacy/new.ts" }; + const conflict = { ...invoice, path: "reports/conflict.ts", applies: false }; + const failed = { ...invoice, path: "archive/failed.ts" }; + const mapped = { path: added.path, directory: "/dev/reports", strip: 1, file: null }; + await openPatch(page, "file", [saved, added, conflict, failed], "/dev", { + directoryMatches: [], + automaticMappings: [mapped], + }); + await page.evaluate(async () => { + const lists = "/src/features/vcs/changelists.ts"; + const { initialChangelists, useChangelists } = await import(/* @vite-ignore */ lists); + const state = initialChangelists(); + useChangelists.setState({ + state: { ...state, lists: [...state.lists, { id: "review", name: "Review", comment: "" }] }, + }); + const handlers = window.__ipc.handlers; + handlers.vcs_changelists_save = () => null; + const head = { head: "main", headCommit: "01122", operation: null, hasRemotes: false }; + handlers.vcs_roots = () => ["/dev/billing", "/dev/reports", "/dev/archive"].map((root) => ({ root, ...head })); + handlers.vcs_branch_info = () => head; + let intent = false; + handlers.vcs_stage_without_content = () => { + intent = true; + return null; + }; + handlers.vcs_status = () => + [ + ["billing/invoice.ts", "modified"], + ["billing/unrelated.ts", "modified"], + ["reports/new.ts", intent ? "added" : "untracked"], + ["reports/conflict.ts", "conflicted"], + ["archive/failed.ts", "modified"], + ].map(([path, unstaged]) => ({ path: `/dev/${path}`, relPath: path, staged: null, unstaged })); + handlers.vcs_apply_mapped_patch = () => ({ + outcome: { applied: ["/dev/billing/invoice.ts", "/dev/reports/new.ts"], conflicts: ["/dev/reports/conflict.ts"] }, + conflictedRepositories: ["/dev/reports"], + failures: [{ root: "/dev/archive", error: { kind: "invalid", message: "File did not match", detail: null } }], + }); + const actions = "/src/platform/actions.ts"; + const { registerActions } = await import(/* @vite-ignore */ actions); + registerActions([{ id: "vcs.resolveConflicts", title: "Resolve Conflicts…", run: () => {} }]); + }); + const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true }); + const target = dialog.getByRole("textbox", { name: "Target changelist", exact: true }); + await expect(target).toHaveValue("Changes"); + await dialog.getByRole("button", { name: "Choose changelist", exact: true }).click(); + await page.getByRole("option", { name: "Review", exact: true }).click(); + await expect(target).toHaveValue("Review"); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect + .poll(async () => { + const saved = (await ipcCalls(page, "vcs_changelists_save")).at(-1)?.changelists as ChangelistState | undefined; + return saved?.files; + }) + .toEqual({ + "billing/invoice.ts": "review", + "billing/unrelated.ts": "default", + "reports/new.ts": "review", + "reports/conflict.ts": "review", + "archive/failed.ts": "default", + }); + expect(await ipcCalls(page, "vcs_stage_without_content")).toEqual([{ paths: ["/dev/reports/new.ts"] }]); + expect(await ipcCalls(page, "vcs_stage")).toEqual([]); +}); + +test("Apply Patch creates a typed changelist when repository-relative changes are applied", async ({ + workbench: page, +}) => { + await stubDesktop(page); + await openPatch(page, "file", [invoice]); + await page.evaluate( + ({ repo, path }) => { + const h = window.__ipc.handlers; + const head = { head: "main", headCommit: "001122", operation: null, hasRemotes: false }; + h.vcs_roots = () => [{ root: repo, ...head }]; + h.vcs_branch_info = () => head; + h.vcs_changelists_save = () => null; + h.vcs_status = () => [{ path: `${repo}/${path}`, relPath: path, staged: null, unstaged: "modified" }]; + }, + { repo, path: invoice.path }, + ); + const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true }); + const target = dialog.getByRole("textbox", { name: "Target changelist", exact: true }); + await target.fill("Abandoned"); + await expect(dialog.getByText("New", { exact: true })).toBeVisible(); + await dialog.getByRole("button", { name: "Cancel", exact: true }).click(); + expect(await ipcCalls(page, "vcs_changelists_save")).toEqual([]); + await openPatch(page, "file", [invoice]); + await target.fill(" "); + const apply = dialog.getByRole("button", { name: "Apply", exact: true }); + await expect(apply).toBeDisabled(); + await target.fill("Release review"); + await apply.click(); + await expect + .poll(async () => { + const saved = (await ipcCalls(page, "vcs_changelists_save")).at(-1)?.changelists as ChangelistState | undefined; + const listId = saved?.files?.[invoice.path]; + return saved?.lists.find((list) => list.id === listId)?.name; + }) + .toBe("Release review"); + expect(await ipcCalls(page, "vcs_stage_without_content")).toEqual([]); +}); + +test("Apply Patch uses the working tree directly in staging mode", async ({ workbench: page }) => { + await stubDesktop(page); + await page.evaluate(async () => { + const project = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ project); + useProject.setState((s: { settings: Record }) => ({ + settings: { ...s.settings, vcs: { git: { stagingArea: true }, commit: { nonModal: true } } }, + })); + }); + await openPatch(page, "file", [invoice]); + const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true }); + await expect(dialog.getByRole("textbox", { name: "Target changelist", exact: true })).toHaveCount(0); + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect.poll(() => ipcCalls(page, "vcs_apply_patch")).toEqual([{ repo, patch, paths: null }]); + expect(await ipcCalls(page, "vcs_changelists_save")).toEqual([]); + expect(await ipcCalls(page, "vcs_stage_without_content")).toEqual([]); }); diff --git a/e2e/branchCompareLayout.spec.ts b/e2e/branchCompareLayout.spec.ts index 9137af23b..d1a34fc79 100644 --- a/e2e/branchCompareLayout.spec.ts +++ b/e2e/branchCompareLayout.spec.ts @@ -1,6 +1,8 @@ import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; -test("Branch comparison keeps both commit ranges and the diff action visible", async ({ workbench: page }) => { +test("Branch comparison reuses one editor tab and keeps both commit ranges independent", async ({ + workbench: page, +}) => { const branch = "feature/settlement-reconciliation-and-international-ledger-reporting"; const current = "feature/review-quarterly-settlement-audit"; const incomingSubject = "Keep regional settlement references stable during the report export"; @@ -33,26 +35,55 @@ test("Branch comparison keeps both commit ranges and the diff action visible", a h.vcs_roots = () => [{ root, ...branchInfo }]; h.vcs_branch_info = () => branchInfo; h.vcs_status = () => []; - h.vcs_log = ({ query }) => - (query as { range: string }).range === `HEAD..${branch}` - ? [entry("c", incomingSubject)] - : [entry("b", outgoingSubject)]; + h.vcs_branches = () => []; + h.vcs_log_refs = () => ({}); + h.vcs_config_get = () => null; + h.vcs_commit_files = () => []; + h.vcs_log_details_batch = ({ revisions }) => + (revisions as string[]).map(() => ({ message: "", containingBranches: [], signature: "N" })); + h.vcs_log = ({ query }) => { + const { ranges, skip, text } = query as { ranges: string[]; skip: number; text: string | null }; + if (skip) return []; + const range = ranges?.[0]; + const rows = + range === `refs/heads/${current}..refs/heads/${branch}` + ? [entry("c", incomingSubject)] + : range === `refs/heads/${branch}..refs/heads/${current}` + ? [entry("b", outgoingSubject)] + : []; + return text ? rows.filter((commit) => commit.summary.includes(text)) : rows; + }; h.window_open_comparison = () => null; const store = "/src/features/vcs/store.ts"; const { useVcs } = await import(/* @vite-ignore */ store); useVcs.setState({ available: true, root, repo: root, roots: [root], branch: branchInfo }); - const path = "/src/features/vcs/CompareBranches.tsx"; - (await import(/* @vite-ignore */ path)).showCompareBranches(branch); + const path = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ path); + const target = { name: branch, rev: `refs/heads/${branch}` }; + await executeAction("vcs.log.compareBranches", target); + await executeAction("vcs.log.compareBranches", target); }, { branch, current, incomingSubject, outgoingSubject }, ); - const dialog = page.getByRole("dialog", { name: new RegExp(`Compare ${current}`) }); - await expect(dialog.getByRole("listbox")).toHaveCount(2); - const incoming = dialog.getByRole("listbox", { name: `In ${branch}, not in ${current}` }); - const outgoing = dialog.getByRole("listbox", { name: `In ${current}, not in ${branch}` }); + await expect(page.getByRole("tab", { name: new RegExp(`Compare ${current}`) })).toHaveCount(1); + const incomingPane = page.getByRole("region", { name: `In ${branch}, not in ${current}` }); + const outgoingPane = page.getByRole("region", { name: `In ${current}, not in ${branch}` }); + const incoming = incomingPane.getByRole("listbox", { name: "Commits" }); + const outgoing = outgoingPane.getByRole("listbox", { name: "Commits" }); await expect(incoming.getByText(incomingSubject, { exact: true })).toBeVisible(); await expect(outgoing.getByText(outgoingSubject, { exact: true })).toBeVisible(); - const divider = dialog.getByRole("separator", { name: "Resize branch comparison panes" }); + await incoming.getByText(incomingSubject, { exact: true }).click(); + await outgoing.getByText(outgoingSubject, { exact: true }).click(); + await expect(incoming.getByRole("option", { selected: true })).toHaveCount(1); + await expect(outgoing.getByRole("option", { selected: true })).toHaveCount(1); + const search = incomingPane.getByRole("textbox", { name: "Filter by message" }); + await search.click(); + await search.fill("does not match"); + await expect(incoming.getByRole("option")).toHaveCount(0); + await expect(outgoing.getByText(outgoingSubject, { exact: true })).toBeVisible(); + await search.fill(""); + await expect(incoming.getByText(incomingSubject, { exact: true })).toBeVisible(); + const divider = page.getByRole("separator", { name: "Resize branch comparison panes" }); await expect(divider).toHaveAttribute("aria-orientation", "horizontal"); const start = (await divider.boundingBox())!.y; await divider.focus(); @@ -60,12 +91,29 @@ test("Branch comparison keeps both commit ranges and the diff action visible", a await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(start + 1); await page.setViewportSize({ width: 440, height: 660 }); - const heading = dialog.getByRole("heading", { name: new RegExp(`In ${branch}`) }); + const heading = incomingPane.getByRole("heading", { name: new RegExp(`In ${branch}`) }); await expect.poll(() => heading.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); await expect(incoming.getByRole("option")).toBeVisible(); await expect(outgoing.getByRole("option")).toBeVisible(); - await dialog.getByRole("button", { name: "Show Diff", exact: true }).click(); + await page.getByRole("button", { name: "Show Branch Diff", exact: true }).click(); await expect .poll(() => ipcCalls(page, "window_open_comparison")) - .toMatchObject([{ comparison: { from: { rev: branch }, to: { rev: "HEAD" }, repo: "/dev/acme-api" } }]); + .toMatchObject([ + { + comparison: { + from: { rev: `refs/heads/${branch}` }, + to: { rev: `refs/heads/${current}` }, + repo: "/dev/acme-api", + }, + }, + ]); + await page.getByRole("tablist", { name: "Editor tabs" }).getByRole("button", { name: "Close Tab" }).click(); + await expect(incomingPane).toHaveCount(0); + await expect(outgoingPane).toHaveCount(0); + const openScopes = await page.evaluate(async () => { + const path = "/src/features/vcs/logStore.ts"; + const { useGitLog } = await import(/* @vite-ignore */ path); + return useGitLog.getState().logTabs.filter((tab: { comparison?: unknown }) => tab.comparison).length; + }); + expect(openScopes).toBe(0); }); diff --git a/e2e/branchesPopupExpansion.spec.ts b/e2e/branchesPopupExpansion.spec.ts index be5db05fb..ba5af5f21 100644 --- a/e2e/branchesPopupExpansion.spec.ts +++ b/e2e/branchesPopupExpansion.spec.ts @@ -3,50 +3,53 @@ * Git is stubbed at the IPC layer; reloading the page stands in for restarting the IDE. */ import type { Page } from "@playwright/test"; -import { expect, stubDesktop, test } from "./fixtures"; +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; const ROOT = "/dev/acme-api"; -async function openBranches(page: Page) { +async function openBranches(page: Page, tags: string[] = [], hasRemotes = true) { await stubDesktop(page); - await page.evaluate(async (root) => { - const h = window.__ipc.handlers; - const branch = (name: string, remote: boolean, current = false) => ({ - name, - current, - remote, - upstream: null, - ahead: 0, - behind: 0, - lastCommitMs: null, - commit: "1111111", - }); - h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }]; - h.vcs_branch_info = () => ({ - head: "main", - headCommit: "1111111", - upstream: null, - ahead: 0, - behind: 0, - operation: null, - }); - h.vcs_status = () => []; - h.vcs_tags = () => []; - h.vcs_branches = () => [ - branch("main", false, true), - branch("develop", false), - branch("origin/main", true), - branch("origin/release", true), - ]; - const vcsModule = "/src/features/vcs/store.ts"; - const { useVcs, refreshNow, loadBranches } = await import(/* @vite-ignore */ vcsModule); - useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); - await refreshNow(); - await loadBranches(); - const actionsModule = "/src/platform/actions.ts"; - const { executeAction } = await import(/* @vite-ignore */ actionsModule); - await executeAction("vcs.branches"); - }, ROOT); + await page.evaluate( + async ({ root, tags, hasRemotes }) => { + const h = window.__ipc.handlers; + const branch = (name: string, remote: boolean, current = false) => ({ + name, + current, + remote, + upstream: null, + ahead: 0, + behind: 0, + lastCommitMs: null, + commit: "1111111", + }); + h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111", hasRemotes }]; + h.vcs_branch_info = () => ({ + head: "main", + headCommit: "1111111", + upstream: null, + ahead: 0, + behind: 0, + operation: null, + }); + h.vcs_status = () => []; + h.vcs_tags = () => tags; + h.vcs_branches = () => [ + branch("main", false, true), + branch("develop", false), + branch("origin/main", true), + branch("origin/release", true), + ]; + const vcsModule = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow, loadBranches } = await import(/* @vite-ignore */ vcsModule); + useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); + await refreshNow(); + await loadBranches(); + const actionsModule = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actionsModule); + await executeAction("vcs.branches"); + }, + { root: ROOT, tags, hasRemotes }, + ); const popup = page.getByRole("dialog", { name: "Git Branches" }); await expect(popup.getByRole("listbox", { name: "Branches" })).toBeVisible(); return popup; @@ -75,3 +78,71 @@ test("Git Branches reopens with the groups expanded as the user left them, also await expect(popup.getByText("release", { exact: true })).toBeVisible(); await expect(popup.getByText("develop", { exact: true })).toBeHidden(); }); + +test("Tag menus use the current remote configuration even before fetching any branches", async ({ + workbench: page, +}) => { + const popup = await openBranches(page, ["v1"]); + await page.evaluate(() => { + window.__ipc.handlers.vcs_remotes = () => [{ name: "release/empty", url: "/empty.git" }]; + window.__ipc.handlers.vcs_remote = () => null; + }); + const tags = group(popup, "Tags"); + await expect(tags).toBeVisible(); + if ((await tags.getAttribute("aria-expanded")) !== "true") await tags.click(); + await popup.getByRole("option", { name: "v1", exact: true }).click(); + await expect(page.getByRole("menuitem", { name: "Push to origin", exact: true })).toHaveCount(0); + await page.getByRole("menuitem", { name: "Push to release/empty", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_remote")) + .toMatchObject([{ repo: ROOT, op: { op: "pushTag", tag: "v1", remote: "release/empty" } }]); + + await page.evaluate(async () => { + window.__ipc.handlers.vcs_remotes = () => [{ name: "renamed/remote", url: "/empty.git" }]; + const path = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ path); + await executeAction("vcs.branches"); + }); + await popup.getByRole("option", { name: "v1", exact: true }).click(); + await expect(page.getByRole("menuitem", { name: "Push to renamed/remote", exact: true })).toBeVisible(); + await expect(page.getByRole("menuitem", { name: "Push to release/empty", exact: true })).toHaveCount(0); +}); + +test("Fetch in Git Branches follows configured remotes and stays busy in place", async ({ workbench: page }) => { + const popup = await openBranches(page, [], false); + const idle = popup.getByRole("button", { name: "Fetch", exact: true }); + await expect(idle).toBeDisabled(); + const executeFetch = () => + page.evaluate(async () => { + const path = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ path); + return executeAction("vcs.fetch"); + }); + expect(await executeFetch()).toBe(false); + + await page.evaluate(async (root) => { + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111", hasRemotes: true }]; + h.vcs_remote = () => + new Promise((resolve) => + window.addEventListener("test:finish-fetch", () => resolve({ remotes: [] }), { once: true }), + ); + const path = "/src/features/vcs/store.ts"; + const { refreshNow } = await import(/* @vite-ignore */ path); + await refreshNow(); + }, ROOT); + await expect(idle).toBeEnabled(); + await idle.click(); + const busy = popup.getByRole("button", { name: "Fetching…", exact: true }); + await expect(busy).toHaveAttribute("aria-busy", "true"); + await expect(busy).toBeFocused(); + await busy.dispatchEvent("click"); + await page.keyboard.press("Space"); + expect(await executeFetch()).toBe(false); + expect(await ipcCalls(page, "vcs_remote")).toHaveLength(1); + + await page.evaluate(() => window.dispatchEvent(new Event("test:finish-fetch"))); + await expect(idle).toBeEnabled(); + await expect(popup).toBeVisible(); + await expect(idle).toBeFocused(); +}); diff --git a/e2e/commit.spec.ts b/e2e/commit.spec.ts index 214b93210..ca6c3859b 100644 --- a/e2e/commit.spec.ts +++ b/e2e/commit.spec.ts @@ -3,6 +3,7 @@ * covered by `crates/ide-vcs` against real repositories. */ import type { Page } from "@playwright/test"; +import type { PartialCommitFile } from "../src/bindings"; import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures"; const ROOT = "/dev/acme-api"; @@ -36,6 +37,13 @@ async function stubRepository(page: Page) { h.vcs_stage = () => null; h.vcs_unstage = () => null; h.vcs_config_get = () => "configured"; + h.vcs_commit_selection_changes = () => []; + const readText = h.fs_read_text; + h.fs_read_text = (args) => { + if (args.path === `${root}/build.gradle.kts`) return "plugins {}\n"; + if (args.path === `${root}/notes.txt`) return "New notes\n"; + return readText?.(args); + }; h.vcs_commit = () => { committed = true; return "2222222"; @@ -63,6 +71,7 @@ test("⌘K commits the checked changes with the typed message", async ({ workben // Committing without a message is refused. await commit.click(); await expect(panel.getByRole("alert")).toHaveText("Specify commit message"); + await expect(message).toBeFocused(); expect(await ipcCalls(page, "vcs_commit")).toHaveLength(0); await message.fill("Return order DTOs from create"); @@ -76,6 +85,842 @@ test("⌘K commits the checked changes with the typed message", async ({ workben await expect(changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" })).toBeHidden(); }); +test("the Commit window gives its message preferred focus", async ({ workbench: page }) => { + await stubRepository(page); + const stripe = page.locator('[data-stripe-button="commit"]'); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + if ((await stripe.getAttribute("aria-pressed")) === "true") await stripe.click(); + await expect(panel).toBeHidden(); + await stripe.click(); + + const message = panel.getByRole("textbox", { name: "Commit message" }); + await expect(message).toBeFocused(); + const changes = panel.getByRole("tree", { name: "Changes" }); + await changes.focus(); + await expect(changes).toBeFocused(); + await page.keyboard.press("Meta+k"); + await expect(message).toBeFocused(); +}); + +test("continuing a resolved revert reviews staged changes and keeps the draft for a retry", async ({ + workbench: page, +}) => { + await stubRepository(page); + await page.evaluate(async (root) => { + const handlers = window.__ipc.handlers; + let stopped = true; + let configured = false; + const operation = () => (stopped ? "revert" : null); + handlers.vcs_roots = () => [{ root, operation: operation(), head: "main", headCommit: "1111111" }]; + handlers.vcs_branch_info = () => ({ + head: "main", + headCommit: "1111111", + upstream: null, + ahead: 0, + behind: 0, + operation: operation(), + }); + handlers.vcs_review_apply_commit = () => ({ + kind: "revert", + checkpoint: "reviewed-index", + message: 'Revert "Original work"\n\nThis reverts commit 2222222.', + paths: [`${root}/build.gradle.kts`], + }); + handlers.vcs_config_get = ({ key }) => + !configured && (key === "user.name" || key === "user.email") ? null : "configured"; + handlers.vcs_set_user_identity = () => { + configured = true; + return null; + }; + handlers.vcs_operation = ({ op }) => { + const reviewed = op as { options?: { runHooks?: boolean } }; + if (reviewed.options?.runHooks) { + throw { kind: "invalidInput", message: "A Git hook rejected this commit." }; + } + stopped = false; + return null; + }; + const store = "/src/features/vcs/store.ts"; + const { refreshNow } = await import(/* @vite-ignore */ store); + await refreshNow(); + }, ROOT); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const proceed = panel.getByRole("button", { name: "Continue", exact: true }); + const review = page.getByRole("dialog", { name: "Continue Revert" }); + const message = review.getByRole("textbox", { name: "Commit message" }); + const author = review.getByRole("textbox", { name: "Author", exact: true }); + const date = review.getByLabel("Author date", { exact: true }); + const signOff = review.getByRole("checkbox", { name: "Sign-off commit" }); + const hooks = review.getByRole("checkbox", { name: "Run Git hooks" }); + const confirm = review.getByRole("button", { name: "Commit and Continue", exact: true }); + await proceed.click(); + await expect(review.getByRole("list", { name: "Staged Changes" }).getByRole("button")).toHaveText("build.gradle.kts"); + await expect(message).toHaveValue('Revert "Original work"\n\nThis reverts commit 2222222.'); + await author.fill("Canceled Author "); + await signOff.click(); + await hooks.click(); + await review.getByRole("button", { name: "Cancel", exact: true }).click(); + await expect(review).toBeHidden(); + expect(await ipcCalls(page, "vcs_operation")).toEqual([]); + await proceed.click(); + await expect(author).toHaveValue(""); + await expect(signOff).not.toBeChecked(); + await expect(hooks).toBeChecked(); + await message.fill("Reviewed revert\n\n# Context"); + await author.fill("Review Author "); + await date.fill("2024-06-04T13:20:21"); + await signOff.click(); + await confirm.click(); + const identity = page.getByRole("dialog", { name: "Git User Name Is Not Defined" }); + await identity.getByRole("button", { name: "Cancel", exact: true }).click(); + await expect(identity).toBeHidden(); + expect(await ipcCalls(page, "vcs_operation")).toEqual([]); + + await proceed.click(); + await expect(message).toHaveValue("Reviewed revert\n\n# Context"); + await confirm.click(); + await identity.getByLabel("Name:", { exact: true }).fill("Repo Committer"); + await identity.getByLabel("E-mail:", { exact: true }).fill("committer@example.invalid"); + await identity.getByRole("checkbox", { name: "Set properties globally" }).click(); + await identity.getByRole("button", { name: "Set and Commit" }).click(); + await expect(page.getByText("A Git hook rejected this commit.")).toBeVisible(); + expect(await ipcCalls(page, "vcs_set_user_identity")).toEqual([ + { repo: ROOT, name: "Repo Committer", email: "committer@example.invalid", global: false }, + ]); + + await proceed.click(); + await expect(message).toHaveValue("Reviewed revert\n\n# Context"); + await expect(author).toHaveValue("Review Author "); + await expect(date).toHaveValue("2024-06-04T13:20:21"); + await expect(signOff).toBeChecked(); + await expect(hooks).toBeChecked(); + await hooks.click(); + await confirm.click(); + const expected = (runHooks: boolean) => ({ + repo: ROOT, + op: { + op: "continueReviewedApply", + checkpoint: "reviewed-index", + message: "Reviewed revert\n\n# Context", + options: { + author: "Review Author ", + authorDate: expect.stringMatching(/^2024-06-04T13:20:21[+-]\d{2}:\d{2}$/), + signOff: true, + runHooks, + }, + }, + }); + await expect.poll(() => ipcCalls(page, "vcs_operation")).toMatchObject([expected(true), expected(false)]); + await expect(proceed).toBeHidden(); +}); + +test("Commit reviews a paused cherry-pick without collecting unrelated changes or other repositories", async ({ + workbench: page, +}) => { + await stubRepository(page); + await page.evaluate(async (root) => { + const handlers = window.__ipc.handlers; + const nested = `${root}/nested`; + let stopped = true; + const branch = (repo: string) => ({ + root: repo, + head: "main", + headCommit: repo === root && !stopped ? "3333333" : "1111111", + upstream: null, + ahead: 0, + behind: 0, + operation: repo === root && stopped ? "cherry-pick" : null, + }); + const file = (path: string, relPath: string, staged: string | null, unstaged: string | null) => ({ + path, + relPath, + staged, + unstaged, + renamedFrom: null, + }); + handlers.vcs_roots = () => [branch(root), branch(nested)]; + handlers.vcs_branch_info = ({ repo }) => branch(String(repo ?? root)); + handlers.vcs_status = () => [ + ...(stopped ? [file(`${root}/build.gradle.kts`, "build.gradle.kts", "modified", null)] : []), + file(`${root}/local.txt`, "local.txt", null, "modified"), + file(`${nested}/nested.txt`, "nested.txt", null, "modified"), + ]; + handlers.vcs_review_apply_commit = () => ({ + kind: "cherry-pick", + checkpoint: "paused-pick-index", + message: "Original pick message", + author: "Original Author ", + paths: [`${root}/build.gradle.kts`], + }); + handlers.vcs_commit_crlf_paths = ({ paths }) => paths; + const project = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ project); + const { settings } = useProject.getState(); + useProject.setState({ + settings: { + ...settings, + vcs: { ...settings?.vcs, commit: { ...settings?.vcs?.commit, clearInitialMessage: true } }, + }, + }); + handlers.vcs_operation = () => { + stopped = false; + return null; + }; + const store = "/src/features/vcs/store.ts"; + const { refreshNow } = await import(/* @vite-ignore */ store); + await refreshNow(); + }, ROOT); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const commit = panel.getByRole("button", { name: "Commit", exact: true }); + const draft = panel.getByRole("textbox", { name: "Commit message" }); + const local = panel.getByRole("checkbox", { name: "Include local.txt in commit" }); + const nested = panel.getByRole("checkbox", { name: "Include nested.txt in commit" }); + const review = page.getByRole("dialog", { name: "Continue Cherry-Pick" }); + const message = review.getByRole("textbox", { name: "Commit message" }); + const author = review.getByRole("textbox", { name: "Author", exact: true }); + await expect(nested).toBeChecked(); + await draft.fill("Unrelated and shared draft"); + await commit.click(); + await expect(page.getByText("Review paused Git operations separately")).toBeVisible(); + expect(await ipcCalls(page, "vcs_commit")).toEqual([]); + expect(await ipcCalls(page, "vcs_review_apply_commit")).toEqual([]); + await nested.click(); + await expect(local).toBeChecked(); + await panel.getByRole("button", { name: "Commit Options", exact: true }).click(); + const options = page.getByRole("dialog", { name: "Commit Options", exact: true }); + await options.getByRole("checkbox", { name: "Sign-off commit" }).click(); + await options.getByRole("checkbox", { name: "Run Git hooks" }).click(); + await options.getByRole("textbox", { name: "Author", exact: true }).fill("Panel Author "); + await page.keyboard.press("Escape"); + await commit.click(); + await expect(message).toHaveValue("Original pick message"); + await expect(author).toHaveValue("Original Author "); + await expect(review.getByRole("list", { name: "Staged Changes" }).getByRole("button")).toHaveText("build.gradle.kts"); + await review.getByRole("button", { name: "Cancel", exact: true }).click(); + await expect(draft).toHaveValue("Unrelated and shared draft"); + await local.click(); + await draft.fill("Commit panel draft for the pick"); + await panel.getByRole("button", { name: "Commit Options", exact: true }).click(); + await options.getByRole("textbox", { name: "Author", exact: true }).fill("Panel Author "); + await page.keyboard.press("Escape"); + await commit.click(); + await expect(message).toHaveValue("Commit panel draft for the pick"); + await expect(author).toHaveValue("Panel Author "); + await expect(review.getByRole("checkbox", { name: "Sign-off commit" })).toBeChecked(); + await expect(review.getByRole("checkbox", { name: "Run Git hooks" })).not.toBeChecked(); + await message.fill("Confirmed cherry-pick message"); + await review.getByRole("button", { name: "Commit and Continue", exact: true }).click(); + const checks = page.getByRole("dialog", { name: "Commit Checks", exact: true }); + await expect(checks.getByText(/1 selected file has CRLF \(build\.gradle\.kts\)/)).toBeVisible(); + await expect(checks.getByRole("button", { name: "Cancel", exact: true })).toBeFocused(); + expect(await ipcCalls(page, "vcs_operation")).toEqual([]); + expect(await ipcCalls(page, "vcs_commit_crlf_paths")).toMatchObject([ + { repo: ROOT, paths: [`${ROOT}/build.gradle.kts`] }, + ]); + await checks.getByRole("button", { name: "Commit Anyway", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_operation")) + .toMatchObject([ + { + repo: ROOT, + op: { + op: "continueReviewedApply", + checkpoint: "paused-pick-index", + message: "Confirmed cherry-pick message", + options: { author: "Panel Author ", authorDate: null, signOff: true, runHooks: false }, + }, + }, + ]); + expect(await ipcCalls(page, "vcs_commit")).toEqual([]); + await expect(draft).toHaveValue(""); +}); + +test("continuing a resolved operation applies commit modifications to the reviewed staging snapshot", async ({ + workbench: page, +}) => { + await stubRepository(page); + await page.evaluate(async (root) => { + const handlers = window.__ipc.handlers; + const path = `${root}/build.gradle.kts`; + let stopped = true; + let formatted = false; + let analysisRuns = 0; + const branch = () => ({ + root, + head: "main", + headCommit: stopped ? "1111111" : "2222222", + upstream: null, + ahead: 0, + behind: 0, + operation: stopped ? "revert" : null, + }); + handlers.vcs_roots = () => [branch()]; + handlers.vcs_branch_info = branch; + handlers.vcs_status = () => [ + { + path, + relPath: "build.gradle.kts", + staged: stopped ? "modified" : null, + unstaged: "modified", + renamedFrom: null, + }, + { path: `${root}/notes.txt`, relPath: "notes.txt", staged: null, unstaged: "modified", renamedFrom: null }, + ]; + const review = () => ({ + kind: "revert", + checkpoint: formatted ? "formatted-index" : "original-index", + message: "Revert original change", + paths: [path], + }); + handlers.vcs_review_apply_commit = review; + handlers.vcs_staged_text = () => ({ text: "import unused\nval n=2\n", version: "original-blob" }); + handlers.vcs_file_at = ({ rev }) => (rev === ":0" && formatted ? "val n = 3\n" : "val n = 1\n"); + handlers.vcs_diff_hunks = () => [{ kind: "modified", start: 0, lines: 1, oldStart: 0, oldLines: 1 }]; + handlers.lsp_source_action_text = ({ kind }) => + kind === "source.organizeImports" + ? [{ range: { start: { line: 0, col: 0 }, end: { line: 1, col: 0 } }, new_text: "" }] + : [{ range: { start: { line: 0, col: 6 }, end: { line: 0, col: 7 } }, new_text: "3" }]; + handlers.lsp_format_text = () => [ + { range: { start: { line: 0, col: 0 }, end: { line: 0, col: 7 } }, new_text: "val n = 3" }, + ]; + handlers.lsp_snapshot_diagnostics = () => + analysisRuns++ === 0 + ? [ + { + range: { start: { line: 0, col: 4 }, end: { line: 0, col: 5 } }, + severity: "warning", + message: "Warning in the commit snapshot", + source: "Test analyzer", + }, + ] + : []; + handlers.vcs_format_apply_commit = () => { + formatted = true; + return review(); + }; + handlers.vcs_commit_crlf_paths = ({ paths }) => (formatted ? paths : []); + handlers.vcs_operation = () => { + stopped = false; + return null; + }; + const project = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ project); + const { settings } = useProject.getState(); + useProject.setState({ + settings: { + ...settings, + vcs: { + ...settings?.vcs, + commit: { ...settings?.vcs?.commit, reformat: true, optimizeImports: true, cleanup: true, analyzeCode: true }, + }, + }, + }); + const store = "/src/features/vcs/store.ts"; + const { refreshNow } = await import(/* @vite-ignore */ store); + await refreshNow(); + }, ROOT); + + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const proceed = panel.getByRole("button", { name: "Continue", exact: true }); + await proceed.click(); + const review = page.getByRole("dialog", { name: "Continue Revert" }); + await expect(review).toBeVisible(); + expect(await ipcCalls(page, "vcs_format_apply_commit")).toEqual([]); + await review.getByRole("button", { name: "Commit and Continue", exact: true }).click(); + const checks = page.getByRole("dialog", { name: "Commit Checks", exact: true }); + await expect(checks.getByText(/1 selected file has CRLF \(build\.gradle\.kts\)/)).toBeVisible(); + await expect(checks.getByText(/1 warning found in 1 file/)).toBeVisible(); + const path = `${ROOT}/build.gradle.kts`; + expect(await ipcCalls(page, "lsp_source_action_text")).toMatchObject([ + { path, kind: "source.organizeImports", text: "import unused\nval n=2\n" }, + { path, kind: "source.fixAll", text: "val n=2\n" }, + ]); + expect(await ipcCalls(page, "lsp_format_text")).toMatchObject([{ path, text: "val n=3\n" }]); + expect(await ipcCalls(page, "lsp_snapshot_diagnostics")).toMatchObject([{ path, text: "val n = 3\n" }]); + expect(await ipcCalls(page, "vcs_format_apply_commit")).toMatchObject([ + { + repo: ROOT, + checkpoint: "original-index", + edits: [{ path, version: "original-blob", text: "val n = 3\n" }], + }, + ]); + expect(await ipcCalls(page, "apply_workspace_edit")).toEqual([]); + expect(await ipcCalls(page, "vcs_operation")).toEqual([]); + await checks.getByRole("button", { name: "Review", exact: true }).click(); + await expect(checks).toBeHidden(); + await expect(page.getByText("Warning in the commit snapshot", { exact: true })).toBeVisible(); + await expect(page.getByText("Staged (index)", { exact: true }).first()).toBeVisible(); + expect(await ipcCalls(page, "vcs_operation")).toEqual([]); + await proceed.click(); + await review.getByRole("button", { name: "Commit and Continue", exact: true }).click(); + await checks.getByRole("button", { name: "Commit Anyway", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_operation")) + .toMatchObject([{ repo: ROOT, op: { op: "continueReviewedApply", checkpoint: "formatted-index" } }]); + await expect(proceed).toBeHidden(); +}); + +test("keeps cleanup of selected lines through Commit Anyway and preserves the excluded line", async ({ + workbench: page, +}) => { + await stubRepository(page); + const path = `${ROOT}/build.gradle.kts`; + await page.evaluate( + async ({ path }) => { + const handlers = window.__ipc.handlers; + const head = "top\noriginal left\noriginal right\nend\n"; + const disk = "top\nexcluded edit\nselected edit\nend\n"; + const selected = "top\noriginal left\nselected edit\nend\n"; + const hunk = { + kind: "modified", + start: 1, + lines: 2, + oldStart: 1, + oldLines: 2, + oldText: "original left\noriginal right\n", + }; + handlers.vcs_file_at = ({ rev }) => + rev === "2222222" ? selected.replace("selected edit", "cleaned edit") : head; + handlers.fs_read_text = () => disk; + handlers.vcs_diff_hunks = () => [hunk]; + handlers.vcs_preview_partial_commit = ({ file }) => (file as PartialCommitFile).prepared?.text ?? selected; + handlers.lsp_source_action_text = () => [ + { range: { start: { line: 2, col: 0 }, end: { line: 2, col: 13 } }, new_text: "cleaned edit" }, + ]; + handlers.lsp_snapshot_diagnostics = () => [ + { + range: { start: { line: 2, col: 0 }, end: { line: 2, col: 0 } }, + severity: "warning", + message: "Review the cleaned selection", + }, + ]; + const info = { id: 12, text: disk, version: 2, large: false, readOnly: false, dirty: false }; + handlers.doc_open = () => info; + handlers.doc_snapshot = () => info; + handlers.doc_autosave = () => true; + handlers.doc_close = () => null; + handlers.apply_workspace_edit = () => null; + const projectModule = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectModule); + const { settings } = useProject.getState(); + useProject.setState({ + settings: { + ...settings, + vcs: { + ...settings?.vcs, + commit: { ...settings?.vcs?.commit, cleanup: true, analyzeCode: true, postponeSlowChecks: false }, + }, + }, + }); + const hunksModule = "/src/features/vcs/hunks.ts"; + const [key] = (await import(/* @vite-ignore */ hunksModule)).hunkKeys(disk, [hunk]); + const commitModule = "/src/features/vcs/commitStore.ts"; + const { useCommit } = await import(/* @vite-ignore */ commitModule); + useCommit.setState({ + checks: new Map([ + [path, "hunks"], + [path.replace("build.gradle.kts", "notes.txt"), "none"], + ]), + excludedHunkLines: new Map([[path, new Map([[key, { old: new Set([0]), current: new Set([0]) }]])]]), + }); + }, + { path }, + ); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + await panel.getByRole("textbox", { name: "Commit message" }).fill("Selected lines"); + await panel.getByRole("button", { name: "Commit", exact: true }).click(); + const before = "top\noriginal left\nselected edit\nend\n"; + const cleaned = "top\noriginal left\ncleaned edit\nend\n"; + await expect(panel.getByText(/1 warning found in 1 file/)).toBeVisible(); + expect(await ipcCalls(page, "lsp_snapshot_diagnostics")).toMatchObject([{ path, text: cleaned }]); + expect(await ipcCalls(page, "vcs_commit")).toEqual([]); + expect(await ipcCalls(page, "apply_workspace_edit")).toEqual([]); + await panel.getByRole("button", { name: "Commit Anyway", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_commit")) + .toMatchObject([{ options: { partial: [{ path, prepared: { before, text: cleaned } }] } }]); + await expect + .poll(() => ipcCalls(page, "apply_workspace_edit")) + .toMatchObject([ + { + edit: { + files: [ + { + path, + version: 2, + edits: [{ range: { start: { line: 2, col: 0 }, end: { line: 2, col: 13 } }, new_text: "cleaned edit" }], + }, + ], + }, + }, + ]); + expect(await ipcCalls(page, "lsp_source_action_text")).toHaveLength(1); +}); + +async function stubCommitAnalysis(page: Page) { + await stubRepository(page); + await page.evaluate(async (root) => { + let committed = false; + const path = `${root}/build.gradle.kts`; + const h = window.__ipc.handlers; + const error = { + range: { start: { line: 0, col: 0 }, end: { line: 0, col: 4 } }, + severity: "error", + message: "Unresolved symbol in committed code", + source: "Test analyzer", + }; + h.vcs_status = () => + committed ? [] : [{ path, relPath: "build.gradle.kts", staged: "modified", unstaged: null, renamedFrom: null }]; + h.vcs_branch_info = () => ({ head: "main", headCommit: committed ? "2222222" : "1111111", operation: null }); + h.vcs_commit = () => { + committed = true; + return "2222222"; + }; + h.vcs_commit_selection_changes = () => [ + { path: "build.gradle.kts", kind: "modified", oldPath: null, before: "1111111", after: "2222222" }, + ]; + h.vcs_file_at = ({ rev }) => + rev === "2222222" + ? "Committed code() // TODO in commit\n" + : rev === ":0" + ? "Selected code()\n" + : "Original code()\n"; + h.vcs_diff_hunks = () => [ + { kind: "modified", start: 0, lines: 1, oldStart: 0, oldLines: 1, oldText: "Original code()\n" }, + ]; + h.lsp_snapshot_diagnostics = ({ text }) => + text === "Committed code() // TODO in commit\n" + ? new Promise((resolve) => + window.addEventListener("releaseCommitAnalysis", () => resolve([error]), { once: true }), + ) + : [error]; + const module = "/src/features/vcs/store.ts"; + await (await import(/* @vite-ignore */ module)).refreshNow(); + }, ROOT); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + await panel.getByRole("textbox", { name: "Commit message" }).fill("Check committed code"); + return panel; +} + +test("a local commit finishes before background analysis of the committed revision", async ({ workbench: page }) => { + const panel = await stubCommitAnalysis(page); + await panel.getByRole("button", { name: "Commit Options", exact: true }).click(); + const options = page.getByRole("dialog", { name: "Commit Options", exact: true }); + await expect(options.getByRole("checkbox", { name: "Run advanced checks after commit" })).toBeChecked(); + await page.keyboard.press("Escape"); + await panel.getByRole("button", { name: "Commit", exact: true }).click(); + await expect.poll(() => ipcCalls(page, "vcs_commit")).toHaveLength(1); + await expect(panel.getByText("build.gradle.kts", { exact: true })).toBeHidden(); + await expect + .poll(() => ipcCalls(page, "lsp_snapshot_diagnostics")) + .toMatchObject([{ path: `${ROOT}/build.gradle.kts`, text: "Committed code() // TODO in commit\n" }]); + await page.evaluate(() => window.dispatchEvent(new Event("releaseCommitAnalysis"))); + await expect(page.getByText("Post-commit checks failed", { exact: true })).toBeVisible(); + await expect(page.getByText(/1 TODO item in committed changes/)).toBeVisible(); + await page.getByRole("button", { name: "Review TODOs", exact: true }).click(); + const todo = page.getByRole("region", { name: "TODO", exact: true }); + await expect(todo.getByRole("tab", { name: /Committed TODOs/ })).toHaveAttribute("aria-selected", "true"); + await expect( + todo.getByRole("tree", { name: "TODO items" }).getByText("TODO in commit", { exact: false }), + ).toBeVisible(); + await page.getByRole("button", { name: "Review", exact: true }).click(); + await expect(page.getByText("Unresolved symbol in committed code", { exact: true })).toBeVisible(); + expect(await ipcCalls(page, "vcs_commit_selection_changes")).toMatchObject([{ repo: ROOT, commits: ["2222222"] }]); +}); + +test("Commit and Push runs code analysis before creating a commit even with background checks enabled", async ({ + workbench: page, +}) => { + const panel = await stubCommitAnalysis(page); + await panel.getByRole("button", { name: "Commit and Push…", exact: true }).click(); + await expect(panel.getByText(/1 error found in 1 file/)).toBeVisible(); + expect(await ipcCalls(page, "lsp_snapshot_diagnostics")).toMatchObject([ + { path: `${ROOT}/build.gradle.kts`, text: "Selected code()\n" }, + ]); + expect(await ipcCalls(page, "vcs_commit")).toEqual([]); + expect(await ipcCalls(page, "vcs_commit_selection_changes")).toEqual([]); +}); + +test("Run Commit Checks reports the selected changes when background checks are enabled", async ({ + workbench: page, +}) => { + const panel = await stubCommitAnalysis(page); + await panel.getByRole("button", { name: "Commit Options", exact: true }).click(); + const options = page.getByRole("dialog", { name: "Commit Options", exact: true }); + await options.getByRole("button", { name: "Run Commit Checks", exact: true }).click(); + await expect(panel.getByText(/1 error found in 1 file/)).toBeVisible(); + expect(await ipcCalls(page, "lsp_snapshot_diagnostics")).toMatchObject([ + { path: `${ROOT}/build.gradle.kts`, text: "Selected code()\n" }, + ]); + expect(await ipcCalls(page, "vcs_commit")).toEqual([]); +}); + +test("Commit Options applies a named TODO filter independently of the TODO window", async ({ workbench: page }) => { + await stubRepository(page); + await page.evaluate(() => { + const handlers = window.__ipc.handlers; + handlers.vcs_file_at = () => "Original\n"; + handlers.fs_read_text = () => "// TODO polish later; FIXME block release\n"; + handlers.vcs_diff_hunks = () => [ + { kind: "modified", start: 0, lines: 1, oldStart: 0, oldLines: 1, oldText: "Original\n" }, + ]; + }); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + await panel.getByRole("textbox", { name: "Commit message" }).fill("Check release blockers"); + const openOptions = () => panel.getByRole("button", { name: "Commit Options", exact: true }).click(); + const options = page.getByRole("dialog", { name: "Commit Options", exact: true }); + const configure = options.getByRole("button", { name: "Configure TODO Filter", exact: true }); + await openOptions(); + await configure.click(); + await page.getByRole("menuitem", { name: "Edit Filters…", exact: true }).click(); + const settings = page.getByRole("dialog", { name: "Settings", exact: true }); + await settings.getByRole("button", { name: "Add TODO Filter", exact: true }).click(); + const filter = page.getByRole("dialog", { name: "Add TODO Filter", exact: true }); + const save = filter.getByRole("button", { name: "OK", exact: true }); + await expect(save).toBeDisabled(); + await filter.getByRole("textbox", { name: "Filter name" }).fill("Release blockers"); + await expect(save).toBeDisabled(); + await filter.getByRole("checkbox", { name: "FIXME", exact: true }).check(); + await save.click(); + await settings.getByRole("button", { name: "OK", exact: true }).click(); + await expect(settings).toBeHidden(); + + if (!(await options.isVisible())) await openOptions(); + await configure.click(); + await page.getByRole("menuitemcheckbox", { name: "Release blockers", exact: true }).click(); + await expect(configure).toHaveText("Release blockers"); + await options.getByRole("button", { name: "Run Commit Checks", exact: true }).click(); + await expect(panel.getByText(/1 TODO item found/)).toBeVisible(); + await panel.getByRole("button", { name: "Review TODOs", exact: true }).click(); + const todoItems = page.getByRole("region", { name: "TODO", exact: true }).getByRole("tree", { name: "TODO items" }); + await expect(todoItems.getByText(/FIXME block release/)).toBeVisible(); + await expect(todoItems.getByText(/TODO polish later/)).toBeHidden(); + + const todo = "/src/platform/todoFilterSelection.ts"; + expect( + await page.evaluate(async (module) => { + const { todoFilterSelection } = await import(/* @vite-ignore */ module); + return { commit: todoFilterSelection("commit"), view: todoFilterSelection("view") }; + }, todo), + ).toEqual({ commit: expect.any(String), view: null }); + + await openOptions(); + await configure.click(); + await page.getByRole("menuitemcheckbox", { name: "Show All", exact: true }).click(); + await options.getByRole("button", { name: "Run Commit Checks", exact: true }).click(); + await expect(panel.getByText(/2 TODO items found/)).toBeVisible(); + await panel.getByRole("button", { name: "Review TODOs", exact: true }).click(); + await expect(todoItems.getByText(/TODO polish later/)).toBeVisible(); + expect(await ipcCalls(page, "vcs_commit")).toEqual([]); +}); + +test("the TODO check reports unreadable files and can retry after they become available", async ({ + workbench: page, +}) => { + await stubRepository(page); + await page.evaluate(() => { + const handlers = window.__ipc.handlers; + handlers.vcs_file_at = () => "Original\n"; + handlers.fs_read_text = () => { + throw { kind: "io", message: "Fixture file is locked", data: null }; + }; + handlers.vcs_diff_entries = () => [{ mode: "100644", gitlink: null }]; + handlers.vcs_diff_hunks = () => [ + { kind: "modified", start: 0, lines: 1, oldStart: 0, oldLines: 1, oldText: "Original\n" }, + ]; + }); + await page.keyboard.press("Meta+k"); + const commit = page.getByRole("region", { name: "Commit", exact: true }); + await commit.getByRole("textbox", { name: "Commit message" }).fill("Check without losing the draft"); + await commit.getByRole("button", { name: "Commit Options", exact: true }).click(); + await page + .getByRole("dialog", { name: "Commit Options", exact: true }) + .getByRole("button", { + name: "Run Commit Checks", + exact: true, + }) + .click(); + await expect(commit.getByText(/Could not check 1 file/)).toBeVisible(); + await expect(commit.getByRole("button", { name: "Commit Anyway", exact: true })).toBeVisible(); + await expect(commit.getByText("Commit checks passed")).toBeHidden(); + await commit.getByRole("button", { name: "Review TODOs", exact: true }).click(); + const todo = page.getByRole("region", { name: "TODO", exact: true }); + const skipped = todo.getByRole("region", { name: "Files Not Checked", exact: true }); + await expect(skipped.getByText("build.gradle.kts", { exact: true })).toBeVisible(); + await expect(skipped.getByText("Fixture file is locked", { exact: true })).toBeVisible(); + + await page.evaluate(() => { + window.__ipc.handlers.fs_read_text = () => "// TODO now readable\n"; + }); + await commit.getByRole("button", { name: "Rerun Commit Checks", exact: true }).click(); + await expect(commit.getByText(/1 TODO item found/)).toBeVisible(); + await expect(commit.getByText(/Could not check 1 file/)).toBeHidden(); + expect(await ipcCalls(page, "vcs_commit")).toEqual([]); +}); + +test("pending TODO review includes every match and keeps the checked text", async ({ workbench: page }) => { + await stubRepository(page); + await page.evaluate(() => { + const handlers = window.__ipc.handlers; + handlers.vcs_file_at = () => "Original\n"; + handlers.fs_read_text = () => Array.from({ length: 25 }, (_, i) => `// TODO review task ${i + 1}\n`).join(""); + handlers.vcs_diff_hunks = () => [ + { kind: "modified", start: 0, lines: 25, oldStart: 0, oldLines: 1, oldText: "Original\n" }, + ]; + }); + await page.keyboard.press("Meta+k"); + const commit = page.getByRole("region", { name: "Commit", exact: true }); + await commit.getByRole("textbox", { name: "Commit message" }).fill("Keep the checked snapshot"); + await commit.getByRole("button", { name: "Commit Options", exact: true }).click(); + await page + .getByRole("dialog", { name: "Commit Options", exact: true }) + .getByRole("button", { name: "Run Commit Checks", exact: true }) + .click(); + await expect(commit.getByText(/25 TODO items found/)).toBeVisible(); + await page.evaluate(() => { + window.__ipc.handlers.fs_read_text = () => "Changed after the check\n"; + }); + const reviewButton = commit.getByRole("button", { name: "Review TODOs", exact: true }); + await reviewButton.click(); + const todo = page.getByRole("region", { name: "TODO", exact: true }); + const tab = todo.getByRole("tab", { name: /Commit TODOs.*Keep the checked snapshot/ }); + await expect(tab).toHaveAttribute("aria-selected", "true"); + await reviewButton.click(); + await expect(tab).toHaveCount(1); + const tree = todo.getByRole("tree", { name: "TODO items" }); + await tree.press("End"); + await expect(tree.getByRole("treeitem", { name: /TODO review task 25$/ })).toHaveAttribute("aria-selected", "true"); + const preview = todo.getByRole("region", { name: "Preview", exact: true }); + await expect(preview.getByText(/TODO review task 25/)).toBeVisible(); + await expect(preview.getByText("Changed after the check")).toBeHidden(); + await tab.press("Delete"); + await expect(tab).toBeHidden(); + await expect(todo.getByRole("tab", { name: /Project/ })).toHaveAttribute("aria-selected", "true"); + expect(await ipcCalls(page, "vcs_commit")).toEqual([]); +}); + +test("opening a TODO review from the modal commit leaves the draft available", async ({ workbench: page }) => { + await stubRepository(page); + await page.evaluate(async () => { + const module = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ module); + const { settings } = useProject.getState(); + useProject.setState({ + settings: { ...settings, vcs: { ...settings?.vcs, commit: { ...settings?.vcs?.commit, nonModal: false } } }, + }); + const handlers = window.__ipc.handlers; + handlers.vcs_file_at = () => "Original\n"; + handlers.fs_read_text = () => "// TODO from the commit dialog\n"; + handlers.vcs_diff_hunks = () => [ + { kind: "modified", start: 0, lines: 1, oldStart: 0, oldLines: 1, oldText: "Original\n" }, + ]; + }); + + await page.keyboard.press("Meta+k"); + const dialog = page.getByRole("dialog", { name: "Commit Changes", exact: true }); + await dialog.getByRole("textbox", { name: "Commit message" }).fill("Keep this draft"); + await dialog.getByRole("button", { name: "Run Commit Checks", exact: true }).click(); + await dialog.getByRole("button", { name: "Review TODOs", exact: true }).click(); + await expect(dialog).toBeHidden(); + const todo = page.getByRole("region", { name: "TODO", exact: true }); + await expect(todo.getByRole("tree").getByText("TODO from the commit dialog")).toBeVisible(); + await page.keyboard.press("Meta+k"); + await expect(dialog.getByRole("textbox", { name: "Commit message" })).toHaveValue("Keep this draft"); + expect(await ipcCalls(page, "vcs_commit")).toEqual([]); +}); + +async function configureCommitTests(page: Page) { + await stubRepository(page); + await page.evaluate(async (root) => { + const config = { + id: "npm:test", + name: "Verification suite", + kind: "npm", + command: "npm", + args: ["test"], + cwd: root, + env: {}, + detected: false, + isTest: false, + debugAdapter: null, + }; + const handlers = window.__ipc.handlers; + handlers.run_configs = () => [config]; + handlers.run_apply_settings = ({ configs }) => configs; + handlers.run_start = ({ onOutput }) => { + window.addEventListener( + "finishCommitTests", + () => { + window.__ipc.send(onOutput, { kind: "stderr", text: "Verification suite fixture failed\n" }); + window.__ipc.emit({ type: "runExited", run: 75, code: 7 }); + }, + { once: true }, + ); + return { id: 75, configId: config.id, name: config.name, pid: 4242, running: true, pty: false }; + }; + handlers.run_stop = ({ id }) => { + window.__ipc.emit({ type: "runExited", run: Number(id), code: 143 }); + return null; + }; + const runModule = "/src/features/run/store.ts"; + await (await import(/* @vite-ignore */ runModule)).loadConfigs(); + }, ROOT); + + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + await panel.getByRole("textbox", { name: "Commit message" }).fill("Run verification"); + const openOptions = () => panel.getByRole("button", { name: "Commit Options", exact: true }).click(); + const options = page.getByRole("dialog", { name: "Commit Options", exact: true }); + await openOptions(); + const toggle = options.getByRole("checkbox", { name: "Run Tests", exact: true }); + await expect(toggle).not.toBeChecked(); + await options.getByRole("button", { name: "Test run configuration" }).click(); + await page.getByRole("option", { name: "Verification suite", exact: true }).click(); + await toggle.check(); + await page.keyboard.press("Escape"); + return { panel, options, openOptions }; +} + +for (const action of ["Run Commit Checks", "Commit and Push…", "Commit"] as const) { + test(`${action} runs the selected verification configuration`, async ({ workbench: page }) => { + const { panel, options, openOptions } = await configureCommitTests(page); + if (action === "Run Commit Checks") { + await openOptions(); + await options.getByRole("button", { name: action, exact: true }).click(); + } else { + await panel.getByRole("button", { name: action, exact: true }).click(); + } + + await expect.poll(() => ipcCalls(page, "run_start")).toMatchObject([{ config: { id: "npm:test" } }]); + expect(await ipcCalls(page, "vcs_commit")).toHaveLength(action === "Commit" ? 1 : 0); + const run = page.getByRole("region", { name: "Run", exact: true }); + await expect(run).toBeHidden(); + await page.evaluate(() => window.dispatchEvent(new Event("finishCommitTests"))); + const summary = action === "Commit" ? page : panel; + await expect(summary.getByText(/Verification suite" exited with code 7/)).toBeVisible(); + await summary.getByRole("button", { name: "Review Run Output", exact: true }).click(); + await expect(run.getByText("Verification suite fixture failed")).toBeVisible(); + expect(await ipcCalls(page, "vcs_commit")).toHaveLength(action === "Commit" ? 1 : 0); + }); +} + +test("cancelling commit tests stops the owned run and aborts the commit", async ({ workbench: page }) => { + const { panel } = await configureCommitTests(page); + await panel.getByRole("button", { name: "Commit and Push…", exact: true }).click(); + await expect.poll(() => ipcCalls(page, "run_start")).toHaveLength(1); + await page.getByRole("button", { name: "Background tasks: Running tests for commit" }).click(); + await page.getByRole("button", { name: "Cancel Running tests for commit" }).click(); + await expect.poll(() => ipcCalls(page, "run_stop")).toMatchObject([{ id: 75 }]); + await expect(panel.getByRole("button", { name: "Commit and Push…", exact: true })).toBeEnabled(); + expect(await ipcCalls(page, "vcs_commit")).toEqual([]); +}); + test("turning off default inclusion starts Commit with all files unchecked", async ({ workbench: page }) => { await page.keyboard.press("Meta+,"); const settings = page.getByRole("dialog", { name: "Settings", exact: true }); @@ -104,6 +949,81 @@ test("turning off default inclusion starts Commit with all files unchecked", asy expect(committed!.options).toMatchObject({ stage: [`${ROOT}/build.gradle.kts`] }); }); +test("the Commit tool window restores the draft and author options for the included changelist", async ({ + workbench: page, +}) => { + await stubRepository(page); + await page.evaluate(async (root) => { + const listsPath = "/src/features/vcs/changelists.ts"; + const { initialChangelists, useChangelists } = await import(/* @vite-ignore */ listsPath); + const state = initialChangelists(); + state.lists.push({ id: "feature", name: "Feature", comment: "Message from the changelist" }); + state.files = { "build.gradle.kts": state.active, "notes.txt": "feature" }; + useChangelists.setState({ state, root, loaded: true }); + let files = ["build.gradle.kts", "notes.txt"]; + const handlers = window.__ipc.handlers; + handlers.vcs_status = () => + files.map((relPath) => ({ + relPath, + path: `${root}/${relPath}`, + staged: null, + unstaged: "modified", + renamedFrom: null, + })); + handlers.vcs_commit = () => { + files = ["build.gradle.kts"]; + return "2222222"; + }; + const storePath = "/src/features/vcs/store.ts"; + await (await import(/* @vite-ignore */ storePath)).refreshNow(); + }, ROOT); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const message = panel.getByRole("textbox", { name: "Commit message" }); + const base = panel.getByRole("checkbox", { name: "Include build.gradle.kts in commit" }); + const feature = panel.getByRole("checkbox", { name: "Include notes.txt in commit" }); + const gear = panel.getByRole("button", { name: "Commit Options", exact: true }); + const options = page.getByRole("dialog", { name: "Commit Options", exact: true }); + const author = options.getByRole("textbox", { name: "Author", exact: true }); + const date = options.getByLabel("Author date", { exact: true }); + const baseDate = "2021-05-03T08:30:05"; + const featureDate = "2022-06-04T13:20:21"; + const featureAuthor = "Feature Author "; + await expect(base).toBeChecked(); + await expect(feature).not.toBeChecked(); + await message.fill("Default draft"); + await gear.click(); + await author.fill("Default Author "); + await date.fill(baseDate); + await page.keyboard.press("Escape"); + await base.click(); + await feature.click(); + await expect(message).toHaveValue("Message from the changelist"); + await message.fill("Feature draft"); + await gear.click(); + await expect(author).toHaveValue(""); + await expect(date).toHaveValue(""); + await author.fill(featureAuthor); + await date.fill(featureDate); + await page.keyboard.press("Escape"); + await feature.click(); + await expect(message).toHaveValue("Default draft"); + await gear.click(); + await expect(author).toHaveValue("Default Author "); + await expect(date).toHaveValue(baseDate); + await page.keyboard.press("Escape"); + await feature.click(); + await expect(message).toHaveValue("Feature draft"); + await panel.getByRole("button", { name: "Commit", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_commit")) + .toMatchObject([{ message: "Feature draft", options: { author: featureAuthor, stage: [`${ROOT}/notes.txt`] } }]); + const [committed] = await ipcCalls(page, "vcs_commit"); + const expectedDate = await page.evaluate((local) => new Date(local).toISOString(), featureDate); + expect(new Date((committed!.options as { authorDate: string }).authorDate).toISOString()).toBe(expectedDate); + await expect(message).toHaveValue("Default draft"); +}); + test("commit message history opens above the message without an empty icon column", async ({ workbench: page }) => { await stubRepository(page); await page.keyboard.press("Meta+k"); @@ -127,6 +1047,270 @@ test("commit message history opens above the message without an empty icon colum await expect(row.locator("span")).toHaveCount(1); }); +test("Amend shows the original author and warns when the committer differs", async ({ workbench: page }) => { + await stubRepository(page); + await page.evaluate(() => { + const h = window.__ipc.handlers; + h.vcs_config_get = ({ key }) => + key === "user.name" ? "Default Git User" : key === "user.email" ? "default@example.test" : null; + h.vcs_log = () => [ + { + id: "1111111", + shortId: "1111111", + parents: ["0000000"], + summary: "Original commit", + message: "Original commit", + author: "Original Author", + email: "original@example.test", + committer: "Original Committer", + committerEmail: "committer@example.test", + }, + ]; + h.vcs_commit_files = () => []; + }); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const amend = panel.getByRole("checkbox", { name: "Amend", exact: true }); + const authorLink = panel.getByRole("button", { name: "Edit Commit Author", exact: true }); + const author = page + .getByRole("dialog", { name: "Commit Options", exact: true }) + .getByRole("textbox", { name: "Author", exact: true }); + const warning = panel.getByRole("img", { name: "Committer of the amended commit differs from default", exact: true }); + + await panel.getByRole("button", { name: "Commit Options", exact: true }).click(); + await author.fill("Draft Author "); + await page.keyboard.press("Escape"); + await expect(authorLink).toHaveText("Draft Author"); + await amend.check(); + await expect(authorLink).toHaveText("Original Author"); + await expect(warning).toBeVisible(); + await amend.uncheck(); + await expect(authorLink).toHaveText("Draft Author"); + await expect(warning).toBeHidden(); + + await amend.check(); + await expect(authorLink).toHaveText("Original Author"); + await authorLink.click(); + await expect(author).toBeFocused(); + await expect(author).toHaveValue("Original Author "); + await author.fill("Edited Author "); + await page.keyboard.press("Escape"); + await amend.uncheck(); + await expect(authorLink).toHaveText("Edited Author"); + + await amend.check(); + await expect(authorLink).toHaveText("Original Author"); + await panel.getByRole("button", { name: "Amend Commit", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_commit")) + .toMatchObject([ + { + repo: ROOT, + message: "Original commit", + options: { amend: true, author: "Original Author " }, + }, + ]); + await expect(authorLink).toBeHidden(); +}); + +async function stubEarlierAmend(page: Page) { + await stubRepository(page); + await page.evaluate(() => { + const h = window.__ipc.handlers; + const commit = (id: string, parents: string[], subject: string) => ({ + id, + shortId: id, + parents, + summary: subject, + message: subject, + author: "Test", + email: "test@example.test", + committer: "Test", + committerEmail: "test@example.test", + }); + const tip = commit("1111111", ["aaaaaaa"], "Last local commit"); + h.vcs_log = ({ query }) => + (query as { firstParent?: boolean }).firstParent + ? [ + tip, + commit("aaaaaaa", ["ddddddd"], "Earlier local commit"), + commit("ddddddd", ["bbbbbbb"], "Improve local docs"), + commit("bbbbbbb", ["ccccccc"], "Published commit"), + commit("ccccccc", [], "Before published commit"), + ] + : [tip]; + h.vcs_branches = () => [ + { name: "origin/main", remote: true }, + { name: "origin/feature", remote: true }, + ]; + h.vcs_merge_base = () => "bbbbbbb"; + h.vcs_config_get = ({ key }) => (key === "user.name" ? "Test" : "test@example.test"); + h.vcs_commit_files = ({ commit }) => [ + { + path: commit === "aaaaaaa" ? "earlier.txt" : "latest.txt", + kind: "added", + oldPath: null, + }, + ]; + }); +} + +test("Amend can select an earlier commit before protected history", async ({ workbench: page }) => { + await stubEarlierAmend(page); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const choose = panel.getByRole("button", { name: "Choose Commit to Amend", exact: true }); + const picker = page.getByRole("listbox", { name: "Choose Commit to Amend", exact: true }); + const message = panel.getByRole("textbox", { name: "Commit message" }); + await message.fill("Draft"); + await choose.click(); + const earlier = picker.getByRole("option", { name: "Earlier local commit", exact: true }); + await expect(earlier).toBeVisible(); + await expect(picker.getByText("Published commit", { exact: true })).toHaveCount(0); + await expect(picker.getByText("Before published commit", { exact: true })).toHaveCount(0); + await earlier.click(); + await expect(message).toHaveValue("Earlier local commit"); + await expect(panel.getByRole("treeitem", { name: /Earlier local commit 1 file/ })).toBeVisible(); + await expect(panel.getByRole("treeitem", { name: "earlier.txt", exact: true })).toBeVisible(); + await choose.click(); + await picker.getByRole("option", { name: /^Amend Last Commit/ }).click(); + await expect(message).toHaveValue("Last local commit"); + await panel.getByRole("checkbox", { name: "Amend", exact: true }).uncheck(); + await expect(message).toHaveValue("Draft"); + + await choose.click(); + await earlier.click(); + await message.fill("Revised earlier commit"); + await panel.getByRole("button", { name: "Amend Commit", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_commit")) + .toMatchObject([ + { + repo: ROOT, + message: "Revised earlier commit", + options: { + amend: true, + amendTarget: { + commit: "aaaaaaa", + head: { branch: "main", commit: "1111111" }, + protectedBranches: ["origin/main"], + }, + stage: [ROOT + "/build.gradle.kts"], + }, + }, + ]); + await expect(panel.getByRole("checkbox", { name: "Amend", exact: true })).not.toBeChecked(); +}); + +test("Amend filters commit subjects while loading and supports keyboard selection", async ({ workbench: page }) => { + await stubEarlierAmend(page); + await page.evaluate(() => { + const h = window.__ipc.handlers; + const log = h.vcs_log!; + let resolve!: () => void; + const ready = new Promise((done) => { + resolve = done; + }); + h.test_release_amend_history = () => resolve(); + h.vcs_log = async (args) => { + if ((args.query as { firstParent?: boolean }).firstParent) await ready; + return log(args); + }; + }); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const choose = panel.getByRole("button", { name: "Choose Commit to Amend", exact: true }); + const picker = page.getByRole("listbox", { name: "Choose Commit to Amend", exact: true }); + const search = page.getByRole("textbox", { name: "Search commits", exact: true }); + const message = panel.getByRole("textbox", { name: "Commit message" }); + await message.fill("Draft"); + + await choose.press("d"); + await expect(search).toBeFocused(); + await expect(search).toHaveValue("d"); + await search.pressSequentially("ocs"); + await expect(page.getByText("Loading commits…", { exact: true })).toBeVisible(); + await page.evaluate(() => window.__ipc.handlers.test_release_amend_history?.({})); + await expect(picker.getByRole("option")).toHaveCount(1); + const docs = picker.getByRole("option", { name: "Improve local docs", exact: true }); + await expect(docs.locator("mark")).toHaveText("docs"); + + await search.fill("published"); + await expect(picker.getByText("No matches", { exact: true })).toBeVisible(); + await search.press("Enter"); + await expect(search).toBeFocused(); + await search.press("Escape"); + await expect(picker).toBeHidden(); + await expect(choose).toBeFocused(); + await expect(message).toHaveValue("Draft"); + + await choose.press("ArrowDown"); + await expect(search).toHaveValue(""); + await search.fill("Last local"); + await expect(picker.getByRole("option")).toHaveCount(1); + await expect(picker.getByRole("option", { name: /Amend Last Commit.*Last local commit/ })).toBeVisible(); + await search.fill("local"); + await expect(picker.getByRole("option")).toHaveCount(3); + await search.press("ArrowDown"); + await search.press("ArrowDown"); + await expect(docs).toHaveAttribute("aria-selected", "true"); + await expect(search).toHaveAttribute("aria-activedescendant", (await docs.getAttribute("id"))!); + await search.dispatchEvent("keydown", { key: "Enter", isComposing: true }); + await expect(search).toBeFocused(); + await search.press("Enter"); + await expect(message).toHaveValue("Improve local docs"); + + await choose.press("ArrowDown"); + await expect(docs).toHaveAttribute("aria-selected", "true"); +}); + +for (const editDraft of [false, true]) { + test(`keeping a conflicting Amend ${editDraft ? "preserves a newer draft" : "creates the prepared commit"}`, async ({ + workbench: page, + }) => { + await stubEarlierAmend(page); + await page.evaluate((root) => { + const h = window.__ipc.handlers; + h.vcs_commit = () => { + throw { + kind: "invalidInput", + message: "Amending this commit would cause a conflict.", + data: { type: "amendConflict", commit: "prepared" }, + }; + }; + h.vcs_keep_amend_commit = () => { + const branch = { head: "main", headCommit: "prepared", operation: null, ahead: 0, behind: 0, upstream: null }; + h.vcs_roots = () => [{ root, ...branch }]; + h.vcs_branch_info = () => branch; + h.vcs_status = () => []; + return "prepared"; + }; + }, ROOT); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + await panel.getByRole("button", { name: "Choose Commit to Amend", exact: true }).click(); + await page.getByRole("option", { name: "Earlier local commit", exact: true }).click(); + const message = panel.getByRole("textbox", { name: "Commit message" }); + await expect(message).toHaveValue("Earlier local commit"); + await panel.getByRole("button", { name: "Amend Commit", exact: true }).click(); + + const keep = page.getByRole("button", { name: "Create Amend Commit Anyway", exact: true }); + await expect(keep).toBeVisible(); + expect(await ipcCalls(page, "vcs_keep_amend_commit")).toHaveLength(0); + if (editDraft) await message.fill("New draft after conflict"); + await keep.click(); + await expect.poll(() => ipcCalls(page, "vcs_keep_amend_commit")).toEqual([{ repo: ROOT, commit: "prepared" }]); + await expect(page.getByText("Amend commit created", { exact: true })).toBeVisible(); + expect(await ipcCalls(page, "vcs_commit")).toHaveLength(1); + await expect(message).toHaveValue(editDraft ? "New draft after conflict" : "Earlier local commit"); + await expect(panel.getByRole("checkbox", { name: "Amend", exact: true })).not.toBeChecked(); + if (editDraft) + await expect + .poll(() => page.evaluate((root) => localStorage.getItem(`openidea.vcs.commitDraft:${root}`), ROOT)) + .toBe("New draft after conflict"); + }); +} + test("the Commit changes toolbar fits a narrow side pane", async ({ workbench: page }) => { await stubRepository(page); await page.keyboard.press("Meta+k"); diff --git a/e2e/diff-navigation.spec.ts b/e2e/diff-navigation.spec.ts index 63aa177db..5d723f16d 100644 --- a/e2e/diff-navigation.spec.ts +++ b/e2e/diff-navigation.spec.ts @@ -1,5 +1,6 @@ import type { EditorView } from "@codemirror/view"; import type { Page } from "@playwright/test"; +import type { MemoryBackend } from "../src/editor/core/backend"; import { expect, stubDesktop, test } from "./fixtures"; async function openChain(page: Page) { @@ -19,6 +20,70 @@ async function openChain(page: Page) { return toolbar; } +test("includes and excludes original and working lines in a unified diff selection", async ({ workbench: page }) => { + await stubDesktop(page); + await page.evaluate(async () => { + const path = "/dev/acme-api/lines.txt"; + const before = "start\nold one\nold two\nold three\nend\n"; + const after = "start\nnew one\nnew two\nnew three\nend\n"; + const handlers = window.__ipc.handlers; + handlers.vcs_file_at = () => before; + handlers.vcs_diff_hunks = () => [ + { kind: "modified", start: 1, lines: 3, oldStart: 1, oldLines: 3, oldText: "old one\nold two\nold three\n" }, + ]; + handlers.fs_probe = () => ({ size: after.length, binary: false, tooLarge: false }); + const backendPath = "/src/editor/core/backend.ts"; + const { docBackend } = await import(/* @vite-ignore */ backendPath); + (docBackend() as MemoryBackend).files.set(path, after); + const storePath = "/src/features/vcs/store.ts"; + const { useVcs } = await import(/* @vite-ignore */ storePath); + const status = { path, relPath: "lines.txt", unstaged: "modified", staged: null, renamedFrom: null }; + useVcs.setState({ status: [status], byPath: new Map([[path, status]]) }); + const inputPath = "/src/features/vcs/diffInput.ts"; + const { openDiff } = await import(/* @vite-ignore */ inputPath); + await openDiff({ path, left: { type: "rev", rev: "HEAD" }, right: { type: "worktree" }, mode: "unified" }); + }); + + const marker = page.locator(".cm-include-hunk"); + await expect(marker).toBeChecked(); + const old = page.locator(".cm-deletedLine").filter({ hasText: "old two" }); + await old.click({ button: "right", position: { x: 14, y: 8 } }); + const menu = page.getByRole("menu", { name: "Context menu" }); + await menu.getByRole("menuitem", { name: "Exclude Selected Lines from Commit" }).click(); + await expect(marker).toHaveJSProperty("indeterminate", true); + + const start = (await old.boundingBox())!; + const end = (await page.locator(".cm-line").filter({ hasText: "new one" }).boundingBox())!; + await page.mouse.move(start.x + 1, start.y + start.height / 2); + await page.mouse.down(); + await page.mouse.move(end.x + 48, end.y + end.height / 2, { steps: 12 }); + await page.mouse.up(); + await expect(page.locator(".cm-unified-commit-selected")).toHaveText(["old two", "old three", "new one"]); + const selectionColors = await page + .locator(".cm-unified-commit-selected") + .evaluateAll((rows) => rows.map((row) => getComputedStyle(row).backgroundColor)); + expect(new Set(selectionColors).size).toBe(1); + await old.click({ button: "right", position: { x: 16, y: 8 } }); + await menu.getByRole("menuitem", { name: "Exclude Selected Lines from Commit" }).click(); + + const excluded = await page.evaluate(async () => { + const storePath = "/src/features/vcs/commitStore.ts"; + const { useCommit } = await import(/* @vite-ignore */ storePath); + const byHunk = useCommit.getState().excludedHunkLines.get("/dev/acme-api/lines.txt"); + return [...(byHunk?.values() ?? [])].map((lines) => ({ old: [...lines.old], current: [...lines.current] })); + }); + expect(excluded).toEqual([{ old: [1, 2], current: [0] }]); + await page.mouse.move(end.x + 48, end.y + end.height / 2); + await page.mouse.down(); + await page.mouse.move(start.x + 1, start.y + start.height / 2, { steps: 12 }); + await page.mouse.up(); + await expect(page.locator(".cm-unified-commit-selected")).toHaveText(["old two", "old three", "new one"]); + await old.click({ button: "right", position: { x: 16, y: 8 } }); + await menu.getByRole("menuitem", { name: "Include Selected Lines in Commit" }).click(); + await expect(marker).toBeChecked(); + await expect(marker).toHaveJSProperty("indeterminate", false); +}); + test("a narrow diff keeps navigation, settings and the difference count visible", async ({ workbench: page }) => { const toolbar = await openChain(page); await page.setViewportSize({ width: 400, height: 600 }); diff --git a/e2e/fileHistoryActions.spec.ts b/e2e/fileHistoryActions.spec.ts index 49bc3ba81..e9bc56660 100644 --- a/e2e/fileHistoryActions.spec.ts +++ b/e2e/fileHistoryActions.spec.ts @@ -44,6 +44,7 @@ test("File History opens its revision and compares only that file with the worki h.vcs_log_details_batch = () => []; h.vcs_commit_files = () => []; h.vcs_file_at = ({ path: filePath }) => `historical contents of ${String(filePath)}\n`; + h.vcs_diff_entries = ({ entries }) => (entries as unknown[]).map(() => ({ mode: "100644", gitlink: null })); h.fs_probe = () => ({ size: 32, binary: false, tooLarge: false }); const storeModule = "/src/features/vcs/store.ts"; @@ -79,7 +80,14 @@ test("File History opens its revision and compares only that file with the worki .poll(async () => ipcCalls(page, "vcs_file_at")) .toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION }); // The working copy side is the file itself (an editable document), not the historical path. - await expect.poll(async () => ipcCalls(page, "vcs_file_mode")).toContainEqual({ path: FILE, rev: "WT" }); + await expect + .poll(async () => ipcCalls(page, "vcs_diff_entries")) + .toContainEqual({ + entries: [ + { path: `${ROOT}/src/old-name.ts`, rev: REVISION }, + { path: FILE, rev: "WT" }, + ], + }); await expect(page.getByText(`historical contents of ${ROOT}/src/old-name.ts`).first()).toBeVisible(); await row.click({ button: "right" }); diff --git a/e2e/gitCommitMessageLayout.spec.ts b/e2e/gitCommitMessageLayout.spec.ts index 0847eecc9..b02c0c983 100644 --- a/e2e/gitCommitMessageLayout.spec.ts +++ b/e2e/gitCommitMessageLayout.spec.ts @@ -26,6 +26,7 @@ test("the history message editor shows commit context and grows with the dialog" const handlers = window.__ipc.handlers; handlers.vcs_roots = () => [{ root, ...branch }]; handlers.vcs_branch_info = () => branch; + handlers.vcs_branches = () => []; handlers.vcs_status = () => []; handlers.vcs_log = ({ query }) => (query as { range: string | null }).range?.startsWith("b".repeat(40)) ? commits.slice(0, 1) : commits; @@ -90,7 +91,7 @@ test("the history message editor shows commit context and grows with the dialog" await page.getByRole("menuitem", { name: /Squash Commits/ }).click(); const squash = page.getByRole("dialog", { name: "Squashed Commit Message" }); const combined = squash.getByRole("textbox", { name: "Edit message for squashed commit" }); - await expect(combined).toHaveValue([earlier, detail, latest, detail].join("\n\n")); + await expect(combined).toHaveValue([earlier + "\n\n" + detail, latest + "\n\n" + detail].join("\n\n\n")); await page.setViewportSize({ width: 420, height: 490 }); await expect(combined).toBeInViewport({ ratio: 1 }); await expect(squash.getByRole("button", { name: "OK", exact: true })).toBeInViewport({ ratio: 1 }); diff --git a/e2e/gitLogBranchMenu.spec.ts b/e2e/gitLogBranchMenu.spec.ts index a62e64a3f..2a0265108 100644 --- a/e2e/gitLogBranchMenu.spec.ts +++ b/e2e/gitLogBranchMenu.spec.ts @@ -1,6 +1,7 @@ +import type { Page } from "@playwright/test"; import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; -test("opens a commit's branch menu and acts in its linked repository", async ({ workbench: page }) => { +async function openGitLog(page: Page) { await stubDesktop(page); await page.evaluate(async () => { const primary = "/dev/acme-api"; @@ -20,12 +21,13 @@ test("opens a commit's branch menu and acts in its linked repository", async ({ behind: 0, operation: null, }); + const refs = (repo: unknown) => (repo === linked ? ["origin/dev", "topic", "release"] : ["origin/other"]); h.vcs_branches = ({ repo }) => - [repo === linked ? "origin/dev" : "origin/other"].map((name) => ({ + refs(repo).map((name) => ({ name, commit: tip, - remote: true, - current: false, + remote: name.startsWith("origin/"), + current: name === "release", upstream: null, ahead: 0, behind: 0, @@ -38,7 +40,7 @@ test("opens a commit's branch menu and acts in its linked repository", async ({ id: tip, shortId: tip.slice(0, 8), parents: [], - refs: [repo === linked ? "origin/dev" : "origin/other"], + refs: refs(repo), author: "A", email: "a@example.com", timeMs: 0, @@ -61,7 +63,8 @@ test("opens a commit's branch menu and acts in its linked repository", async ({ h.vcs_config_get = () => null; h.vcs_tags = () => []; h.vcs_status = () => []; - h.vcs_create_branch = () => null; + h.vcs_checkout = () => ({ kind: "done" }); + h.vcs_create_branch = () => ({ checkout: { kind: "done" }, created: { tip: "1111111", previousTip: null } }); const vcsModule = "/src/features/vcs/store.ts"; const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule); useVcs.setState({ available: true, root: primary, repo: primary }); @@ -73,7 +76,10 @@ test("opens a commit's branch menu and acts in its linked repository", async ({ const { executeAction } = await import(/* @vite-ignore */ actionsModule); await executeAction("vcs.showLog"); }); +} +test("opens a commit's branch menu and acts in its linked repository", async ({ workbench: page }) => { + await openGitLog(page); await page.getByRole("option", { name: /Linked repository commit/ }).click({ button: "right" }); const menu = page.getByRole("menu", { name: "Context menu" }); await expect(menu.getByRole("menuitem", { name: "Branch 'origin/other'" })).toHaveCount(0); @@ -86,5 +92,29 @@ test("opens a commit's branch menu and acts in its linked repository", async ({ await dialog.getByRole("button", { name: "Create", exact: true }).click(); await expect .poll(() => ipcCalls(page, "vcs_create_branch")) - .toMatchObject([{ repo: "/dev/acme-web", name: "test-branch", start: "origin/dev", checkout: true }]); + .toMatchObject([{ repo: "/dev/acme-web", name: "test-branch", start: "refs/remotes/origin/dev", checkout: true }]); +}); + +test("checks out either a local branch or the detached revision from a commit", async ({ workbench: page }) => { + await openGitLog(page); + const linked = page.getByRole("option", { name: /Linked repository commit/ }); + await linked.click({ button: "right" }); + await page.getByRole("menuitem", { name: "Checkout", exact: true }).hover(); + const branch = page.getByRole("menuitem", { name: "topic", exact: true }); + await expect(branch).toBeVisible(); + await expect(page.getByRole("menuitem", { name: "release", exact: true })).toHaveCount(0); + await expect(page.getByRole("menuitem", { name: "origin/dev", exact: true })).toHaveCount(0); + await branch.click(); + await linked.click({ button: "right" }); + await page.getByRole("menuitem", { name: "Checkout", exact: true }).hover(); + await page.getByRole("menuitem", { name: "Revision '11111111'", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_checkout")) + .toMatchObject([ + { repo: "/dev/acme-web", branch: "refs/heads/topic" }, + { repo: "/dev/acme-web", branch: `${"1".repeat(40)}^{commit}` }, + ]); + + await page.getByRole("option", { name: /Primary repository commit/ }).click({ button: "right" }); + await expect(page.getByRole("menuitem", { name: "Checkout Revision '11111111'", exact: true })).toBeVisible(); }); diff --git a/e2e/gitLogMultiRepoOperations.spec.ts b/e2e/gitLogMultiRepoOperations.spec.ts new file mode 100644 index 000000000..91a31f02a --- /dev/null +++ b/e2e/gitLogMultiRepoOperations.spec.ts @@ -0,0 +1,253 @@ +import type { Page } from "@playwright/test"; +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +const primary = "/dev/acme-api"; +const worker = "/dev/acme-api/worker"; +const tools = "/dev/acme-api/tools"; +const revision = (n: string) => n.repeat(40); + +async function openMixedSelection( + page: Page, + outcome: "success" | "failure" | "conflict" | "cancel", + { + addCherryPickOrigin, + mixedOrigins = false, + emptyAction, + }: { addCherryPickOrigin?: boolean; mixedOrigins?: boolean; emptyAction?: "skip" | "createEmpty" } = {}, +) { + await stubDesktop(page); + await page.evaluate( + async ({ primary, worker, tools, outcome, addCherryPickOrigin, mixedOrigins, emptyAction }) => { + const h = window.__ipc.handlers; + let conflicted = false; + const branch = (repo: unknown) => ({ + head: "main", + headCommit: "1".repeat(40), + operation: conflicted && repo === worker ? "cherry-pick" : null, + upstream: null, + ahead: 0, + behind: 0, + }); + h.vcs_roots = () => [primary, worker, tools].map((root) => ({ root, ...branch(root) })); + h.vcs_branch_info = ({ repo }) => branch(repo); + h.vcs_status = () => + conflicted + ? [ + { + path: worker + "/work.txt", + relPath: "work.txt", + staged: null, + unstaged: "conflicted", + renamedFrom: null, + }, + ] + : []; + h.vcs_branches = ({ repo }) => [ + { + name: repo === worker || (repo === primary && mixedOrigins) ? "origin/main" : "origin/feature", + remote: true, + current: false, + commit: "2".repeat(40), + upstream: null, + ahead: 0, + behind: 0, + lastCommitMs: 0, + }, + ]; + h.vcs_log = ({ repo }) => { + const rows: Array<[string, string, number]> = + repo === primary + ? [ + ["4", "Newest primary change", 4], + ["1", "Oldest primary change", 1], + ] + : repo === worker + ? [["3", "Worker change", 3]] + : [["2", "Tools change", 2]]; + return rows.map(([n, summary, order]) => ({ + id: n.repeat(40), + shortId: n.repeat(8), + parents: n === "4" ? ["1".repeat(40)] : [], + refs: [], + author: "A", + email: "a@example.com", + timeMs: order * 1000, + summary, + message: summary, + })); + }; + h.vcs_log_refs = () => ({}); + h.vcs_log_users = () => []; + h.vcs_commit_files = () => []; + h.vcs_log_details_batch = ({ repo, revisions }) => + (revisions as string[]).map((rev) => ({ + message: "Fixture", + containingBranches: [ + repo === worker || (repo === primary && mixedOrigins && rev === "1".repeat(40)) + ? "origin/main" + : "origin/feature", + ], + signature: "N", + signer: "", + key: "", + fingerprint: "", + })); + h.vcs_operation = ({ repo, op, onOutput }) => { + window.__ipc.send(onOutput, String(repo)); + if ((op as { op: string }).op === "abort") { + conflicted = false; + return null; + } + if (outcome === "failure" && repo === worker) throw { kind: "invalidInput", message: "Git stopped" }; + if (outcome === "conflict" && repo === worker) { + conflicted = true; + throw { kind: "invalidInput", message: "Git conflict details" }; + } + if (outcome === "cancel" && repo === primary) { + return new Promise((resolve) => { + h.cancel_request = () => { + resolve(null); + return null; + }; + }); + } + if (emptyAction && repo === primary && (op as { op: string }).op === "cherryPick") { + return { emptyCherryPicks: 1, action: emptyAction }; + } + return null; + }; + if (addCherryPickOrigin !== undefined) { + const projectPath = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectPath); + const { settings } = useProject.getState(); + useProject.setState({ + settings: { ...settings, vcs: { ...settings?.vcs, git: { ...settings?.vcs?.git, addCherryPickOrigin } } }, + }); + } + const vcsPath = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsPath); + useVcs.setState({ available: true, root: primary, repo: primary }); + await refreshNow(); + const contextPath = "/src/platform/context.ts"; + (await import(/* @vite-ignore */ contextPath)).setContext("vcsAvailable", true); + const actionsPath = "/src/platform/actions.ts"; + await (await import(/* @vite-ignore */ actionsPath)).executeAction("vcs.showLog"); + }, + { primary, worker, tools, outcome, addCherryPickOrigin, mixedOrigins, emptyAction }, + ); + const log = page.getByRole("listbox", { name: "Commits" }); + const newest = log.getByRole("option", { name: /Newest primary change/ }); + await newest.click(); + await log.getByRole("option", { name: /Oldest primary change/ }).click({ modifiers: ["Meta"] }); + await log.getByRole("option", { name: /Worker change/ }).click({ modifiers: ["Meta"] }); + if (outcome === "failure" || outcome === "conflict") { + await log.getByRole("option", { name: /Tools change/ }).click({ modifiers: ["Meta"] }); + } + await newest.click({ button: "right" }); + return page.getByRole("menu", { name: "Context menu" }); +} + +test("Cherry-Pick groups Git Log selections by repository and applies their commits oldest first", async ({ + workbench: page, +}) => { + const menu = await openMixedSelection(page, "success"); + await menu.getByRole("menuitem", { name: "Cherry-Pick", exact: true }).click(); + await expect(page.getByRole("status").filter({ hasText: "Cherry-picked 3 commits" })).toBeVisible(); + const calls = await ipcCalls(page, "vcs_operation"); + expect(calls).toMatchObject([ + { repo: primary, op: { op: "cherryPick", recordOrigin: false, commits: [revision("1"), revision("4")] } }, + { repo: worker, op: { op: "cherryPick", recordOrigin: true, commits: [revision("3")] } }, + ]); + expect(calls[0]?.onOutput).not.toEqual(calls[1]?.onOutput); +}); + +test("Revert stops after the first failed repository and reports the work already completed", async ({ + workbench: page, +}) => { + const menu = await openMixedSelection(page, "failure"); + await menu.getByRole("menuitem", { name: "Revert Commit", exact: true }).click(); + const failure = page.getByRole("alert").filter({ hasText: "Revert failed" }); + await expect(failure).toContainText("Stopped in worker."); + await expect(failure).toContainText("Completed in acme-api."); + await expect(failure).toContainText("Git stopped"); + expect(await ipcCalls(page, "vcs_operation")).toMatchObject([ + { repo: primary, op: { op: "revert", commits: [revision("4"), revision("1")] } }, + { repo: worker, op: { op: "revert", commits: [revision("3")] } }, + ]); +}); + +test("Cherry-Pick honours the project setting to leave the source line out", async ({ workbench: page }) => { + const menu = await openMixedSelection(page, "success", { addCherryPickOrigin: false, mixedOrigins: true }); + await menu.getByRole("menuitem", { name: "Cherry-Pick", exact: true }).click(); + await expect(page.getByRole("status").filter({ hasText: "Cherry-picked 3 commits" })).toBeVisible(); + const calls = await ipcCalls(page, "vcs_operation"); + expect(calls.map(({ op }) => op)).toEqual([ + { op: "cherryPick", recordOrigin: false, commits: [revision("1"), revision("4")] }, + { op: "cherryPick", recordOrigin: false, commits: [revision("3")] }, + ]); +}); + +test("Cherry-Pick records origins for the protected commits within a mixed repository selection", async ({ + workbench: page, +}) => { + const menu = await openMixedSelection(page, "success", { mixedOrigins: true }); + await menu.getByRole("menuitem", { name: "Cherry-Pick", exact: true }).click(); + await expect(page.getByRole("status").filter({ hasText: "Cherry-picked 3 commits" })).toBeVisible(); + expect(await ipcCalls(page, "vcs_operation")).toMatchObject([ + { + repo: primary, + op: { + op: "cherryPick", + recordOrigin: false, + recordOriginFor: [revision("1")], + commits: [revision("1"), revision("4")], + }, + }, + { repo: worker, op: { op: "cherryPick", recordOrigin: true, commits: [revision("3")] } }, + ]); +}); + +for (const [emptyAction, title, details] of [ + ["skip", "Cherry-picked 2 commits", "Skipped one empty commit"], + ["createEmpty", "Cherry-picked 3 commits", "Created one empty commit"], +] as const) { + test(`Cherry-Pick reports empty commits when the host selects ${emptyAction}`, async ({ workbench: page }) => { + const menu = await openMixedSelection(page, "success", { emptyAction }); + await menu.getByRole("menuitem", { name: "Cherry-Pick", exact: true }).click(); + await expect(page.getByRole("status").filter({ hasText: title })).toContainText(details); + }); +} + +test("Cancelling a mixed Cherry-Pick prevents the next repository from starting", async ({ workbench: page }) => { + const menu = await openMixedSelection(page, "cancel"); + await menu.getByRole("menuitem", { name: "Cherry-Pick", exact: true }).click(); + await expect.poll(() => ipcCalls(page, "vcs_operation")).toHaveLength(1); + const running = page.getByRole("status").filter({ hasText: "Cherry-picking…" }); + await running.getByRole("button", { name: "Cancel", exact: true }).click(); + await expect(page.getByRole("status").filter({ hasText: "Git operation cancelled" })).toContainText( + "Completed in acme-api.", + ); + expect(await ipcCalls(page, "vcs_operation")).toHaveLength(1); +}); + +test("A Cherry-Pick conflict reports partial progress and aborts only the affected repository", async ({ + workbench: page, +}) => { + const menu = await openMixedSelection(page, "conflict"); + await menu.getByRole("menuitem", { name: "Cherry-Pick", exact: true }).click(); + const conflicts = page.getByRole("dialog", { name: "Conflicts" }); + await expect(conflicts).toBeVisible(); + const warning = page.getByRole("status").filter({ hasText: "Cherry-pick has conflicts" }); + await expect(warning).toContainText("Stopped in worker."); + await expect(warning).toContainText("Completed in acme-api."); + await expect(warning).not.toContainText("Git conflict details"); + await conflicts.getByRole("button", { name: "Close", exact: true }).last().click(); + await warning.getByRole("button", { name: "Abort", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_operation")) + .toMatchObject([ + { repo: primary, op: { op: "cherryPick" } }, + { repo: worker, op: { op: "cherryPick" } }, + { repo: worker, op: { op: "abort", expected: "cherry-pick" } }, + ]); +}); diff --git a/e2e/gitLogToolbarMenus.spec.ts b/e2e/gitLogToolbarMenus.spec.ts index f8aee3d0f..fdef93925 100644 --- a/e2e/gitLogToolbarMenus.spec.ts +++ b/e2e/gitLogToolbarMenus.spec.ts @@ -337,6 +337,35 @@ test("Git Log puts affected changes on the changed-files toolbar and groups prev await expect(notes).toBeVisible(); }); +test("Not Cherry-Picked Commits dims other rows while keeping unpicked commits readable", async ({ + workbench: page, +}) => { + await page.evaluate(async () => { + window.__ipc.handlers.vcs_not_cherry_picked = () => ["0".repeat(40)]; + const logModule = "/src/features/vcs/logStore.ts"; + const { setLogBranches } = await import(/* @vite-ignore */ logModule); + setLogBranches(["release"]); + }); + const rows = page.getByRole("listbox", { name: "Commits" }); + const waiting = rows.getByText("Commit 0", { exact: true }); + const picked = rows.getByText("Commit 1", { exact: true }); + const color = await waiting.evaluate((el) => getComputedStyle(el).color); + await expect(picked).toHaveCSS("color", color); + + const view = page.getByRole("button", { name: "View Options", exact: true }); + const highlight = page.getByRole("menuitemcheckbox", { name: "Not Cherry-Picked Commits" }); + await view.click(); + await expect(highlight).toHaveAttribute("aria-checked", "false"); + await highlight.click(); + await expect(picked).not.toHaveCSS("color", color); + await expect(waiting).toHaveCSS("color", color); + + await view.click(); + await expect(highlight).toHaveAttribute("aria-checked", "true"); + await highlight.click(); + await expect(picked).toHaveCSS("color", color); +}); + test("the Paths filter replaces the repository filter and can be cleared from overflow", async ({ workbench: page, }) => { diff --git a/e2e/gitLogUndoCommit.spec.ts b/e2e/gitLogUndoCommit.spec.ts new file mode 100644 index 000000000..07f121f90 --- /dev/null +++ b/e2e/gitLogUndoCommit.spec.ts @@ -0,0 +1,155 @@ +import type { Page } from "@playwright/test"; +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +const primary = "/dev/acme-api"; +const worker = "/dev/acme-api/worker"; +const workerHead = "7".repeat(40); +const message = "Worker change\n\nReapply this change after review."; + +async function showUndoMenu( + page: Page, + { stagingArea = false, published = false, competingOperation = false, initialCommit = false } = {}, +) { + await stubDesktop(page); + await page.evaluate( + async ({ primary, worker, workerHead, message, stagingArea, published, competingOperation, initialCommit }) => { + const h = window.__ipc.handlers; + const parent = "6".repeat(40); + let undone = false; + let primaryMerge = false; + const branch = (repo: unknown) => ({ + head: repo === worker ? "topic" : "main", + headCommit: repo === worker ? (undone ? parent : workerHead) : "1".repeat(40), + operation: repo === primary && primaryMerge ? "merge" : null, + upstream: null, + ahead: 0, + behind: 0, + }); + h.vcs_roots = () => [primary, worker].map((root) => ({ root, ...branch(root) })); + h.vcs_branch_info = ({ repo }) => { + if (repo === worker && competingOperation) primaryMerge = true; + return branch(repo); + }; + h.vcs_status = () => + undone + ? [ + { + path: worker + "/worker.txt", + relPath: "worker.txt", + staged: "modified", + unstaged: null, + renamedFrom: null, + }, + ] + : []; + h.vcs_branches = ({ repo }) => + published && repo === worker + ? [ + { + name: "release/main", + remote: true, + current: false, + commit: workerHead, + upstream: null, + ahead: 0, + behind: 0, + }, + ] + : []; + h.vcs_log = ({ repo }) => { + const { headCommit } = branch(repo); + const summary = repo === worker ? "Worker change" : "Primary change"; + return [ + { + id: headCommit, + shortId: headCommit.slice(0, 8), + parents: repo === worker && !undone && !initialCommit ? [parent] : [], + refs: [], + author: "A", + email: "a@example.com", + timeMs: 1000, + summary, + message, + }, + ]; + }; + h.vcs_log_refs = () => ({}); + h.vcs_log_users = () => []; + h.vcs_commit_files = () => [{ path: "worker.txt", kind: "modified", oldPath: null }]; + const details = (repo: unknown) => ({ + message, + containingBranches: published && repo === worker ? ["release/main"] : [], + signature: "N", + signer: "", + key: "", + fingerprint: "", + }); + h.vcs_log_details = ({ repo }) => details(repo); + h.vcs_log_details_batch = ({ repo, revisions }) => (revisions as string[]).map(() => details(repo)); + h.vcs_undo_commit = () => { + undone = true; + return message; + }; + + const projectPath = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectPath); + const { settings } = useProject.getState(); + useProject.setState({ + settings: { ...settings, vcs: { git: { stagingArea }, commit: { nonModal: true } } }, + }); + const vcsPath = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsPath); + useVcs.setState({ available: true, root: primary, repo: primary }); + await refreshNow(); + const contextPath = "/src/platform/context.ts"; + (await import(/* @vite-ignore */ contextPath)).setContext("vcsAvailable", true); + const actionsPath = "/src/platform/actions.ts"; + await (await import(/* @vite-ignore */ actionsPath)).executeAction("vcs.showLog"); + }, + { primary, worker, workerHead, message, stagingArea, published, competingOperation, initialCommit }, + ); + const row = page.getByRole("listbox", { name: "Commits" }).getByRole("option", { name: /Worker change/ }); + await row.click({ button: "right" }); + await page.getByRole("menuitem", { name: "Undo Commit…" }).click(); +} + +test("Undo Commit uses the selected repository even when another repository needs attention", async ({ + workbench: page, +}) => { + await showUndoMenu(page, { competingOperation: true }); + const lists = page.getByRole("dialog", { name: "Select Target Changelist" }); + await expect(lists).toBeVisible(); + await lists.getByRole("button", { name: "OK" }).click(); + await expect.poll(() => ipcCalls(page, "vcs_undo_commit")).toEqual([{ repo: worker, commit: workerHead }]); +}); + +test("Undo Commit in staging mode restores the message without a changelist prompt", async ({ workbench: page }) => { + await showUndoMenu(page, { stagingArea: true }); + await expect.poll(() => ipcCalls(page, "vcs_undo_commit")).toEqual([{ repo: worker, commit: workerHead }]); + await expect(page.getByRole("dialog", { name: "Select Target Changelist" })).toHaveCount(0); + await expect + .poll(() => + page.evaluate(async () => { + const path = "/src/features/vcs/commitStore.ts"; + return (await import(/* @vite-ignore */ path)).useCommit.getState().message; + }), + ) + .toBe(message); +}); + +test("Undo Commit refuses a commit contained in a protected remote branch without an upstream", async ({ + workbench: page, +}) => { + await showUndoMenu(page, { published: true }); + await expect(page.getByRole("dialog", { name: "Cannot undo commit" })).toContainText("release/main"); + expect(await ipcCalls(page, "vcs_undo_commit")).toHaveLength(0); +}); + +test("Undo Commit confirms before removing the initial commit in staging mode", async ({ workbench: page }) => { + await showUndoMenu(page, { stagingArea: true, initialCommit: true }); + const confirm = page.getByRole("dialog", { name: "Undo Commit" }); + await expect(confirm).toContainText("The initial commit will be undone"); + expect(await ipcCalls(page, "vcs_undo_commit")).toHaveLength(0); + await confirm.getByRole("button", { name: "Undo Commit" }).click(); + await expect.poll(() => ipcCalls(page, "vcs_undo_commit")).toEqual([{ repo: worker, commit: workerHead }]); +}); diff --git a/e2e/gitMergeLayout.spec.ts b/e2e/gitMergeLayout.spec.ts index 0d8caca65..8f21be927 100644 --- a/e2e/gitMergeLayout.spec.ts +++ b/e2e/gitMergeLayout.spec.ts @@ -39,14 +39,22 @@ test("the Git Merge form shows the command and selected options", async ({ workb const merge = dialog.getByRole("button", { name: "Merge", exact: true }); const modifyOptions = dialog.getByRole("button", { name: "Modify options" }); await expect(command).toBeVisible(); - const repoBox = (await repo.boundingBox())!; - const commandBox = (await command.boundingBox())!; - const branchBox = (await branch.boundingBox())!; + const { repoBox, commandBox, branchBox } = await dialog.evaluate((el) => { + const box = (selector: string) => { + const { x, y, width, height } = el.querySelector(selector)!.getBoundingClientRect(); + return { x, y, width, height }; + }; + return { + repoBox: box('button[aria-label="Repository"]'), + commandBox: box("code"), + branchBox: box('button[aria-label="Branch to merge"]'), + }; + }); expect(repoBox.x + repoBox.width).toBeLessThan(commandBox.x); expect(commandBox.x + commandBox.width).toBeLessThan(branchBox.x); - expect(Math.abs(repoBox.y - branchBox.y)).toBeLessThan(1); + expect(Math.abs(repoBox.y + repoBox.height / 2 - (branchBox.y + branchBox.height / 2))).toBeLessThan(1); await expect(repo).toBeFocused(); - await expect(merge).toBeDisabled(); + await expect(branch).toHaveText("feature/api"); await repo.click(); await page.getByRole("option", { name: "service", exact: true }).click(); @@ -78,12 +86,14 @@ test("the Git Merge form shows the command and selected options", async ({ workb .toEqual([ { repo: "/dev/acme-api/service", - branches: ["feature/service"], + branches: ["refs/heads/feature/service"], options: { noFf: true, ffOnly: false, squash: false, noCommit: false, + noVerify: false, + allowUnrelatedHistories: false, message: "Merge service changes\n\nReviewed the service update.", }, }, diff --git a/e2e/gitRebaseLayout.spec.ts b/e2e/gitRebaseLayout.spec.ts index 3f082c659..fa01424cd 100644 --- a/e2e/gitRebaseLayout.spec.ts +++ b/e2e/gitRebaseLayout.spec.ts @@ -30,6 +30,7 @@ test("Rebase shows its command and the two bases for --onto", async ({ workbench })), ]; }; + handlers.vcs_has_commit = () => true; handlers.vcs_rebase_with = () => null; const store = "/src/features/vcs/store.ts"; const { useVcs } = await import(/* @vite-ignore */ store); @@ -88,11 +89,12 @@ test("Rebase shows its command and the two bases for --onto", async ({ workbench await flag("--onto"); const oldBase = dialog.getByRole("button", { name: "Old base", exact: true }); const newBase = dialog.getByRole("button", { name: "New base", exact: true }); - await expect(oldBase).toHaveText("release"); + await expect(newBase).toHaveText("release"); await expect(submit).toBeDisabled(); const oldBox = (await oldBase.boundingBox())!; const newBox = (await newBase.boundingBox())!; expect(oldBox.y).toBeGreaterThan(newBox.y); + await pick(oldBase, "release"); await pick(newBase, "integration"); await flag("--rebase-merges"); await flag("--keep-empty"); @@ -110,8 +112,15 @@ test("Rebase shows its command and the two bases for --onto", async ({ workbench .toEqual([ { repo: "/dev/acme-api/service", - upstream: "release", - options: { onto: "integration", rebaseMerges: true, keepEmpty: true }, + upstream: "refs/heads/release", + options: { + onto: "refs/heads/integration", + branch: null, + rebaseMerges: true, + keepEmpty: true, + updateRefs: false, + autosquash: null, + }, }, ]); }); diff --git a/e2e/gitUnstashLayout.spec.ts b/e2e/gitUnstashLayout.spec.ts index 653427cf8..e5a063a31 100644 --- a/e2e/gitUnstashLayout.spec.ts +++ b/e2e/gitUnstashLayout.spec.ts @@ -26,7 +26,7 @@ test("Unstash aligns its controls and restores the selected repository's stash", base: "a1234567", }), ); - handlers.vcs_stash_apply = () => null; + handlers.vcs_stash_apply = () => ({ index: 1, outcome: { kind: "done" } }); const store = "/src/features/vcs/store.ts"; const { useVcs } = await import(/* @vite-ignore */ store); useVcs.setState({ root, roots: [root, service], repo: root, branch: branchInfo(root), available: true }); @@ -86,5 +86,13 @@ test("Unstash aligns its controls and restores the selected repository's stash", await dialog.getByRole("button", { name: "Pop Stash", exact: true }).click(); await expect .poll(() => ipcCalls(page, "vcs_stash_apply")) - .toEqual([{ repo: "/dev/acme-api/service", index: 1, pop: true, reinstateIndex: true, branch: null }]); + .toEqual([ + { + repo: "/dev/acme-api/service", + stash: { index: 1, message: "Review cache changes", timeMs: null, id: "stash-1", base: "a1234567" }, + pop: true, + reinstateIndex: true, + branch: null, + }, + ]); }); diff --git a/e2e/gitWorktreesLayout.spec.ts b/e2e/gitWorktreesLayout.spec.ts index 47cdad3cf..b68cb0735 100644 --- a/e2e/gitWorktreesLayout.spec.ts +++ b/e2e/gitWorktreesLayout.spec.ts @@ -16,7 +16,10 @@ test("Worktrees places actions beside the tree and shows the folder above its br }); window.__ipc.handlers.vcs_worktrees = ({ repo }) => repo === service - ? [worktree(service, "release", true), worktree("/dev/service-snapshot", null)] + ? [worktree(service, "release", true), worktree("/dev/service-snapshot", null)].map((tree) => ({ + ...tree, + submodule: true, + })) : [worktree(root, "main", true), worktree("/dev/review-worktree", "feature/review", false, true)]; const store = "/src/features/vcs/store.ts"; const { useVcs } = await import(/* @vite-ignore */ store); @@ -29,9 +32,9 @@ test("Worktrees places actions beside the tree and shows the folder above its br await executeAction("vcs.worktrees"); }); - const dialog = page.getByRole("dialog", { name: "Worktrees", exact: true }); - const toolbar = dialog.getByRole("toolbar", { name: "Worktrees", exact: true }); - const tree = dialog.getByRole("tree", { name: "Worktrees", exact: true }); + const panel = page.getByRole("tabpanel", { name: "Worktrees", exact: true }); + const toolbar = panel.getByRole("toolbar", { name: "Worktrees", exact: true }); + const tree = panel.getByRole("tree", { name: "Worktrees", exact: true }); await expect(tree.getByText("feature/review", { exact: true })).toBeVisible(); const barBox = (await toolbar.boundingBox())!; const treeBox = (await tree.boundingBox())!; @@ -44,7 +47,9 @@ test("Worktrees places actions beside the tree and shows the folder above its br expect(nameBox.y + nameBox.height).toBeLessThanOrEqual(branchBox.y); await expect(name).toHaveCSS("font-size", await branch.evaluate((el) => getComputedStyle(el).fontSize)); await expect(row.getByRole("img", { name: "locked", exact: true })).toBeVisible(); - await expect(tree.getByRole("treeitem", { name: /service-snapshot.*a1234567/ })).toBeVisible(); + const submodule = tree.getByRole("treeitem", { name: /service-snapshot.*a1234567/ }); + await expect(submodule.getByText("Submodule", { exact: true })).toBeVisible(); + await expect(row.getByText("Submodule", { exact: true })).toHaveCount(0); await tree.focus(); await tree.press("End"); @@ -54,14 +59,4 @@ test("Worktrees places actions beside the tree and shows the folder above its br await expect(row).toHaveAttribute("aria-selected", "true"); await tree.press("Escape"); await expect(row.getByText("/dev/review-worktree", { exact: true })).toBeVisible(); - await dialog.getByRole("button", { name: "Close", exact: true }).last().click(); - - await page.getByRole("toolbar", { name: "Tool windows" }).getByRole("button", { name: "Git", exact: true }).click(); - await page.getByRole("tab", { name: "Worktrees", exact: true }).click(); - const panel = page.getByRole("tabpanel", { name: "Worktrees", exact: true }); - const dockedTree = panel.getByRole("tree", { name: "Worktrees", exact: true }); - await expect(dockedTree.getByRole("treeitem", { name: /review-worktree.*feature\/review/ })).toBeVisible(); - const dockedBarBox = (await panel.getByRole("toolbar", { name: "Worktrees" }).boundingBox())!; - const dockedTreeBox = (await dockedTree.boundingBox())!; - expect(dockedBarBox.x + dockedBarBox.width).toBeLessThanOrEqual(dockedTreeBox.x); }); diff --git a/e2e/gutterChangeLayout.spec.ts b/e2e/gutterChangeLayout.spec.ts index bddfed451..d9a221982 100644 --- a/e2e/gutterChangeLayout.spec.ts +++ b/e2e/gutterChangeLayout.spec.ts @@ -1,5 +1,5 @@ import type { EditorView } from "@codemirror/view"; -import { expect, stubDesktop, test } from "./fixtures"; +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; test("an inline change keeps its actions and original code readable at the editor zoom", async ({ workbench: page, @@ -73,3 +73,145 @@ test("an inline change keeps its actions and original code readable at the edito await expect(deleted).toBeHidden(); await expect(editor.getByText("// obsolete window", { exact: true })).toBeVisible(); }); + +test("stages and unstages a mixed gutter change and rolls back to the index", async ({ workbench: page }) => { + const root = "/dev/acme-api"; + const path = `${root}/policy.ts`; + const head = "const policy = 'HEAD';"; + const staged = "const policy = 'staged';"; + const working = "const policy = 'working';"; + const before = "// nearby before"; + const after = "// nearby after"; + const surround = (line: string) => `// outside before\n${before}\n${line}\n${after}\n// outside after\n`; + await stubDesktop(page); + await page.evaluate( + async ({ root, path, head, staged, committed, stagedFile }) => { + const h = window.__ipc.handlers; + let index = stagedFile; + let version = 1; + h.fs_probe = () => ({ size: staged.length, binary: false, tooLarge: false }); + h.fs_read_text = () => stagedFile; + h.vcs_file_at = (args) => (args.rev === ":0" ? index : committed); + h.vcs_roots = () => [{ root, head: "main", headCommit: "1111111" }]; + h.vcs_branch_info = () => ({ head: "main", headCommit: "1111111", operation: null }); + h.vcs_status = () => [{ path, relPath: "policy.ts", staged: "modified", unstaged: "modified" }]; + h.vcs_staged_text = () => ({ text: index, version: String(version) }); + h.vcs_save_staged_text = (args) => { + if (args.version !== String(version)) + throw { kind: "outOfSync", message: "The staged version changed on disk" }; + index = String(args.text); + return String(++version); + }; + const project = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ project); + useProject.setState((s: { project: Record; settings: Record }) => ({ + project: { ...s.project, isGit: true }, + settings: { + ...s.settings, + files: { autoSave: false }, + vcs: { git: { stagingArea: true }, commit: { nonModal: true } }, + }, + })); + const service = "/src/workbench/contributions.ts"; + await (await import(/* @vite-ignore */ service)).editorService().openFile(path); + h.vcs_staging_line_hunks = () => { + const view = (document.querySelector(".cm-content") as (HTMLElement & { cmTile: { view: EditorView } }) | null) + ?.cmTile.view; + const indexLine = index.split("\n")[2]!; + const localLine = view?.state.doc.toString().split("\n")[2] ?? staged; + const hasStaged = indexLine !== head; + const hasUnstaged = localLine !== indexLine; + return { + indexVersion: String(version), + hunks: + hasStaged || hasUnstaged + ? [ + { + kind: "modified", + start: 2, + lines: 1, + headStart: 2, + headLines: 1, + headText: head + "\n", + indexStart: 2, + indexLines: 1, + indexText: indexLine + "\n", + staged: hasStaged, + unstaged: hasUnstaged, + }, + ] + : [], + }; + }; + const store = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ store); + useVcs.setState({ available: true, root, repo: root }); + await refreshNow(); + }, + { root, path, head, staged, committed: surround(head), stagedFile: surround(staged) }, + ); + + const editor = page.locator(".cm-editor"); + const content = editor.locator(".cm-content"); + await expect(content).toBeVisible(); + await content.evaluate((el, text) => { + const { view } = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile; + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } }); + }, surround(staged)); + await expect(editor.locator(".cm-openidea-lane").getByTitle("Staged changes", { exact: true })).toBeVisible(); + await content.evaluate((el, text) => { + const { view } = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile; + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } }); + }, surround(working)); + await editor.locator(".cm-openidea-lane").getByTitle("Staged and unstaged changes", { exact: true }).click(); + const mixed = page.getByRole("dialog", { name: "Staged and unstaged changes" }); + await expect(mixed.getByRole("region", { name: "HEAD" })).toHaveText(head); + await expect(mixed.getByRole("region", { name: "Staged (index)" })).toHaveText(staged); + await mixed.getByRole("button", { name: "Show Diff", exact: true }).click(); + const fragment = page.getByRole("dialog", { name: "Show Diff for Lines", exact: true }); + await expect(fragment).toBeVisible(); + const panes = fragment.locator(".cm-content"); + await expect(panes).toHaveCount(3); + for (const [i, line] of [head, staged, working].entries()) { + const pane = panes.nth(i); + await expect(pane).toContainText(line); + await expect(pane).toContainText(before); + await expect(pane).toContainText(after); + await expect(pane).not.toContainText("outside"); + } + const local = fragment.locator('.cm-content[aria-label="Local Version"]'); + await expect(local).toBeEditable(); + await local.press("Meta+a"); + const selection = await local.evaluate((el) => { + const { state } = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view; + return state.sliceDoc(state.selection.main.from, state.selection.main.to); + }); + expect(selection).toBe([before, working, after].join("\n")); + await fragment.getByRole("button", { name: "Revert Change", exact: true }).click(); + await expect(local).toContainText(staged); + await local.press("Meta+z"); + await expect(local).toContainText(working); + await fragment.getByRole("button", { name: "Stage Change (git add hunk)", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_save_staged_text")) + .toEqual([{ path, text: surround(working), version: "1" }]); + await fragment.getByRole("button", { name: "Close", exact: true }).last().click(); + await editor.locator(".cm-openidea-lane").getByTitle("Staged changes", { exact: true }).click(); + const stagedOnly = page.getByRole("dialog", { name: "Staged changes", exact: true }); + await expect(stagedOnly.getByRole("button", { name: "Rollback" })).toBeDisabled(); + await expect(editor.getByText(working, { exact: true })).toBeVisible(); + const unstage = stagedOnly.getByRole("button", { name: "Unstage Change", exact: true }); + await expect(unstage).toBeFocused(); + await unstage.click(); + const unstagedOnly = page.getByRole("dialog", { name: "Unstaged changes", exact: true }); + await expect(unstagedOnly.getByRole("region", { name: "Staged (index)" })).toHaveText(head); + await unstagedOnly.getByRole("button", { name: "Rollback" }).click(); + await expect(editor.getByText(head, { exact: true })).toBeVisible(); + await expect + .poll(() => ipcCalls(page, "vcs_save_staged_text")) + .toEqual([ + { path, text: surround(working), version: "1" }, + { path, text: surround(head), version: "2" }, + ]); + await expect.poll(() => ipcCalls(page, "doc_save")).toEqual([]); +}); diff --git a/e2e/interactiveRebaseLayout.spec.ts b/e2e/interactiveRebaseLayout.spec.ts index 7e2922fcb..4504ad20d 100644 --- a/e2e/interactiveRebaseLayout.spec.ts +++ b/e2e/interactiveRebaseLayout.spec.ts @@ -1,13 +1,13 @@ -import { expect, stubDesktop, test } from "./fixtures"; +import type { Page } from "@playwright/test"; +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; -test("Interactive rebase keeps commit messages and plan controls usable at narrow widths", async ({ - workbench: page, -}) => { +async function showLog(page: Page, scenario: "synthetic" | "updateRefs" | "amend" | "edit") { const first = "Keep regional settlement references stable when reconciling delayed ledger updates"; - const second = "Add settlement summary"; + const amend = scenario === "amend"; + const second = amend ? `amend! ${first}` : "Add settlement summary"; await stubDesktop(page); await page.evaluate( - async ({ first, second }) => { + async ({ first, second, scenario, amend }) => { const root = "/dev/acme-api"; const id = (n: string) => n.repeat(40); const commits = [ @@ -21,22 +21,85 @@ test("Interactive rebase keeps commit messages and plan controls usable at narro message: commit.summary + "\n\nKeep the audit trail linked to the settlement job.", })); const h = window.__ipc.handlers; - h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: id("c") }]; + let rebasing = false; + let continues = 0; + h.vcs_roots = () => [{ root, operation: rebasing ? "rebase" : null, head: "main", headCommit: id("c") }]; h.vcs_branch_info = () => ({ head: "main", headCommit: id("c"), upstream: null, ahead: 0, behind: 0, - operation: null, + operation: rebasing ? "rebase" : null, }); + h.vcs_branches = () => []; h.vcs_status = () => []; h.vcs_log = () => commits; h.vcs_log_refs = () => ({}); h.vcs_log_users = () => ["Sam Rivera "]; h.vcs_config_get = () => null; + h.vcs_config_get_bool = ({ key }) => + key === "rebase.updateRefs" ? scenario === "updateRefs" || scenario === "edit" : null; h.vcs_commit_files = () => []; + h.vcs_commit_selection_changes = ({ commits }) => + (commits as string[]).map((commit) => ({ + path: commit === id("b") ? "refs.txt" : "summary.txt", + kind: "added", + after: commit, + before: null, + oldPath: null, + })); h.vcs_log_details_batch = () => []; + if (scenario !== "synthetic") { + h.vcs_rebase_with_editor = ({ onEdit, operation }) => { + if ((operation as { kind: string }).kind === "continue") { + if (++continues === 1) { + return new Promise((_, reject) => { + h.vcs_rebase_editor_reply = () => { + reject({ kind: "cancelled", message: "cancelled" }); + return null; + }; + window.__ipc.send(onEdit, { + index: 1, + edit: { kind: "message", text: second, plan: null }, + }); + }); + } + if (continues === 3) rebasing = false; + return null; + } + return new Promise((resolve) => { + h.vcs_rebase_editor_reply = ({ reply }) => { + rebasing = scenario === "edit" && !!reply; + resolve(null); + return null; + }; + const [newer, older] = commits; + const reference = "refs/heads/review"; + const row = (commit: (typeof commits)[number], line: number) => ({ + ...commit, + kind: "commit", + action: "pick", + revision: commit.shortId, + line, + }); + window.__ipc.send(onEdit, { + index: 1, + edit: amend + ? { + kind: "plan", + text: `pick ${older!.shortId}\nfixup -C ${newer!.shortId}\n`, + plan: [row(older!, 0), { ...row(newer!, 1), action: "fixup", fixupMessage: "replace" }], + } + : { + kind: "plan", + text: `pick ${older!.shortId}\nupdate-ref ${reference}\npick ${newer!.shortId}\n`, + plan: [row(older!, 0), { kind: "updateRef", line: 1, reference }, row(newer!, 2)], + }, + }); + }); + }; + } const vcsPath = "/src/features/vcs/store.ts"; const { useVcs } = await import(/* @vite-ignore */ vcsPath); useVcs.setState({ available: true, root, roots: [root], repo: root, branchesLoaded: true }); @@ -45,21 +108,185 @@ test("Interactive rebase keeps commit messages and plan controls usable at narro const actionsPath = "/src/platform/actions.ts"; await (await import(/* @vite-ignore */ actionsPath)).executeAction("vcs.showLog"); }, - { first, second }, + { first, second, scenario, amend }, ); + return { first, second }; +} + +async function withCommitMenu(page: Page, summary: string) { const log = page.getByRole("listbox", { name: "Commits" }); - await log.getByRole("option", { name: new RegExp(first) }).click({ button: "right" }); + await log + .getByRole("option", { name: new RegExp(summary) }) + .filter({ hasNotText: `amend! ${summary}` }) + .click({ button: "right" }); +} + +async function openLogRebase(page: Page, scenario: "synthetic" | "updateRefs" | "amend" | "edit") { + const { first, second } = await showLog(page, scenario); + await withCommitMenu(page, first); await page.getByRole("menuitem", { name: /Interactively Rebase from Here/ }).click(); + return { first, second }; +} + +async function publishToProtectedBranch(page: Page, commit: string) { + await page.evaluate((commit) => { + const h = window.__ipc.handlers; + h.vcs_branches = () => [ + { + name: "release/main", + remote: true, + current: false, + commit, + upstream: null, + ahead: 0, + behind: 0, + lastCommitMs: 0, + }, + ]; + h.vcs_log_details = ({ revision }) => ({ + message: "Fixture", + containingBranches: revision === commit ? ["release/main"] : [], + signature: "N", + signer: "", + key: "", + fingerprint: "", + }); + }, commit); +} + +for (const [menu, title] of [ + [/^Edit Commit Message/, "Cannot edit commit message"], + [/^Interactively Rebase from Here/, "Cannot rebase"], + [/^Drop Commits$/, "Cannot drop commit"], +] as const) { + test(`${title} when the oldest affected commit is on a protected remote without an upstream`, async ({ + workbench: page, + }) => { + const { first } = await showLog(page, "synthetic"); + const oldest = "b".repeat(40); + await publishToProtectedBranch(page, oldest); + await withCommitMenu(page, first); + await page.getByRole("menuitem", { name: menu }).click(); + await expect(page.getByRole("dialog", { name: title })).toContainText("release/main"); + expect(await ipcCalls(page, "vcs_log_details")).toContainEqual({ repo: "/dev/acme-api", revision: oldest }); + }); +} + +test("Edit Commit Message permits a newer local commit above the protected tip", async ({ workbench: page }) => { + const { second } = await showLog(page, "synthetic"); + await publishToProtectedBranch(page, "b".repeat(40)); + await withCommitMenu(page, second); + await page.getByRole("menuitem", { name: /^Edit Commit Message/ }).click(); + await expect(page.getByRole("dialog", { name: "Edit Commit Message", exact: true })).toBeVisible(); + expect(await ipcCalls(page, "vcs_log_details")).toContainEqual({ repo: "/dev/acme-api", revision: "c".repeat(40) }); +}); + +test("Edit Commit Message keeps the warning for a published commit on an unprotected upstream", async ({ + workbench: page, +}) => { + const { second } = await showLog(page, "synthetic"); + await page.evaluate(() => { + const h = window.__ipc.handlers; + const branchInfo = h.vcs_branch_info!; + h.vcs_branch_info = async (args) => ({ ...((await branchInfo(args)) as object), upstream: "origin/topic" }); + h.vcs_branches = () => [ + { + name: "origin/topic", + remote: true, + current: false, + commit: "c".repeat(40), + upstream: null, + ahead: 0, + behind: 0, + lastCommitMs: 0, + }, + ]; + }); + await withCommitMenu(page, second); + await page.getByRole("menuitem", { name: /^Edit Commit Message/ }).click(); + const warning = page.getByRole("dialog").filter({ hasText: "already pushed to origin/topic" }); + await expect(warning).toBeVisible(); + await warning.getByRole("button", { name: "Continue" }).click(); + await expect(page.getByRole("dialog", { name: "Edit Commit Message", exact: true })).toBeVisible(); +}); + +test("Edit Commit Message refuses a commit published while the dialog was open", async ({ workbench: page }) => { + const { second } = await showLog(page, "synthetic"); + await withCommitMenu(page, second); + await page.getByRole("menuitem", { name: /^Edit Commit Message/ }).click(); + const editor = page.getByRole("dialog", { name: "Edit Commit Message", exact: true }); + await editor.getByRole("textbox", { name: "Edit message for commit cccccccc by Sam Rivera" }).fill("New message"); + await publishToProtectedBranch(page, "c".repeat(40)); + await editor.getByRole("button", { name: "OK" }).click(); + await expect(page.getByRole("dialog", { name: "Cannot edit commit message" })).toContainText("release/main"); + expect(await ipcCalls(page, "vcs_reword")).toHaveLength(0); +}); + +test("Edit Commit Message refuses a rewrite prepared for another branch", async ({ workbench: page }) => { + const { second } = await showLog(page, "synthetic"); + await withCommitMenu(page, second); + await page.getByRole("menuitem", { name: /^Edit Commit Message/ }).click(); + const editor = page.getByRole("dialog", { name: "Edit Commit Message", exact: true }); + await editor.getByRole("textbox", { name: "Edit message for commit cccccccc by Sam Rivera" }).fill("New message"); + await page.evaluate(() => { + const h = window.__ipc.handlers; + const branchInfo = h.vcs_branch_info!; + h.vcs_branch_info = async (args) => ({ ...((await branchInfo(args)) as object), head: "another-branch" }); + }); + await editor.getByRole("button", { name: "OK" }).click(); + await expect(page.getByRole("dialog", { name: "Cannot edit commit message" })).toContainText("The branch changed"); + expect(await ipcCalls(page, "vcs_reword")).toHaveLength(0); +}); + +test("Undo after reword refuses to move a rewrite that has been published", async ({ workbench: page }) => { + const { second } = await showLog(page, "synthetic"); + const before = "c".repeat(40); + const after = "d".repeat(40); + await page.evaluate( + ({ before, after }) => { + const h = window.__ipc.handlers; + const log = h.vcs_log!; + h.vcs_reword = () => ({ before, after }); + h.vcs_log = (args) => + (args.query as { range?: string }).range === `${before}..${after}` ? [{ id: after }] : log(args); + }, + { before, after }, + ); + await withCommitMenu(page, second); + await page.getByRole("menuitem", { name: /^Edit Commit Message/ }).click(); + const editor = page.getByRole("dialog", { name: "Edit Commit Message", exact: true }); + await editor.getByRole("textbox", { name: "Edit message for commit cccccccc by Sam Rivera" }).fill("New message"); + await editor.getByRole("button", { name: "OK" }).click(); + const edited = page.getByRole("status").filter({ hasText: "Commit message of cccccccc changed" }); + await expect(edited).toBeVisible(); + await publishToProtectedBranch(page, after); + await edited.getByRole("button", { name: "Undo" }).click(); + await expect(page.getByRole("alert").filter({ hasText: "Undo failed" })).toContainText("release/main"); + expect(await ipcCalls(page, "vcs_restore_head")).toHaveLength(0); +}); + +test("Interactive rebase keeps commit messages and plan controls usable at narrow widths", async ({ + workbench: page, +}) => { + const { first, second } = await openLogRebase(page, "synthetic"); const dialog = page.getByRole("dialog", { name: /Rebasing 2 commits/ }); await expect(dialog).toBeVisible(); + const changes = dialog.getByRole("tree", { name: "Changed files" }); + await expect(changes.getByRole("treeitem", { name: "refs.txt" })).toBeVisible(); + await changes.getByRole("treeitem", { name: "refs.txt" }).click(); + await expect(dialog.getByRole("button", { name: "Show Diff", exact: true })).toBeEnabled(); await page.setViewportSize({ width: 440, height: 640 }); - const list = dialog.getByRole("list", { name: "Commits to rebase" }); - const originalRows = list.getByRole("listitem"); + const list = dialog.getByRole("grid", { name: "Commits to rebase" }); + const originalRows = list.getByRole("row"); await dialog.getByRole("button", { name: "Action for bbbbbbbb" }).click(); await page.getByRole("option", { name: "Reword", exact: true }).click(); const reword = dialog.getByRole("textbox", { name: "New message for bbbbbbbb" }); await expect(reword).toHaveValue(first + "\n\nKeep the audit trail linked to the settlement job."); + await dialog.getByRole("button", { name: "Changed files", exact: true }).click(); + const compactChanges = page.getByRole("dialog", { name: "Changed files", exact: true }); + await expect(compactChanges.getByRole("treeitem", { name: "refs.txt" })).toBeVisible(); + await compactChanges.getByRole("button", { name: "Close", exact: true }).click(); const editor = (await reword.boundingBox())!; expect(editor.width).toBeGreaterThan(260); expect(editor.height).toBeGreaterThan(160); @@ -81,10 +308,161 @@ test("Interactive rebase keeps commit messages and plan controls usable at narro .click(); const details = dialog.getByRole("region", { name: "Commit details" }); await expect(details).toContainText("Keep the audit trail linked to the settlement job."); + await expect(changes.getByRole("treeitem", { name: "summary.txt" })).toBeVisible(); + await expect(changes.getByRole("treeitem", { name: "refs.txt" })).toHaveCount(0); await page.setViewportSize({ width: 1120, height: 760 }); await expect(divider).toHaveAttribute("aria-orientation", "vertical"); await expect(details).toContainText(second); + await originalRows + .last() + .getByRole("button", { name: new RegExp(message.split("\n", 1)[0]!) }) + .click({ + modifiers: ["Shift"], + }); + await expect(list.getByRole("row", { selected: true })).toHaveCount(2); + await expect(changes.getByRole("treeitem", { name: "summary.txt" })).toBeVisible(); + await expect(changes.getByRole("treeitem", { name: "refs.txt" })).toBeVisible(); + await dialog.getByRole("button", { name: "Selected Commit Actions" }).click(); + await page.getByRole("option", { name: "Drop", exact: true }).click(); + await expect(list.getByRole("button", { name: /Action for/ }).filter({ hasText: "Drop" })).toHaveCount(2); + await dialog.getByRole("button", { name: "Undo", exact: true }).click(); + await expect(list.getByRole("button", { name: /Action for/ }).filter({ hasText: "Drop" })).toHaveCount(0); await dialog.getByRole("button", { name: "Cancel", exact: true }).click(); + const confirmCancel = page.getByRole("dialog", { name: "Cancel Rebase" }); + await confirmCancel.getByRole("button", { name: "Continue Editing" }).click(); + await expect(dialog).toBeVisible(); + await dialog.getByRole("button", { name: "Cancel", exact: true }).click(); + await confirmCancel.getByRole("button", { name: "Discard Changes" }).click(); await expect(dialog).toBeHidden(); }); + +test("Interactive rebase from Git Log preserves Git's ref updates when configured", async ({ workbench: page }) => { + await openLogRebase(page, "updateRefs"); + const plan = page.getByRole("dialog", { name: "Edit Git Rebase Plan" }); + const update = plan.getByRole("row").filter({ hasText: "refs/heads/review" }); + await expect(update).toBeVisible(); + expect(await ipcCalls(page, "vcs_rebase_with_editor")).toMatchObject([ + { repo: "/dev/acme-api", operation: { kind: "start", upstream: "a".repeat(40) } }, + ]); + await update.getByRole("button").click(); + await plan.getByRole("button", { name: "Move Down" }).click(); + await expect(plan.getByRole("row").last()).toContainText("refs/heads/review"); + await plan.getByRole("button", { name: "Start Rebasing" }).click(); + await expect(plan).toBeHidden(); + expect(await ipcCalls(page, "vcs_rebase_editor_reply")).toMatchObject([ + { reply: { text: "pick bbbbbbbb\npick cccccccc\nupdate-ref refs/heads/review\n" } }, + ]); +}); + +test("Interactive rebase from Git Log displays and edits Git's amend fixup", async ({ workbench: page }) => { + const { second } = await openLogRebase(page, "amend"); + const plan = page.getByRole("dialog", { name: "Edit Git Rebase Plan" }); + const fixup = plan.getByRole("button", { name: "Action for cccccccc" }); + await expect(fixup).toHaveText("Fixup (Replace)"); + await plan.getByRole("button", { name: new RegExp(second) }).click(); + await expect(plan.getByRole("region", { name: "Commit details" })).toContainText( + "Keep the audit trail linked to the settlement job.", + ); + await expect(plan.getByRole("region", { name: "Commit details" })).not.toContainText(second); + await fixup.click(); + await page.getByRole("option", { name: "Fixup (Edit)", exact: true }).click(); + await expect(fixup).toHaveText("Fixup (Edit)"); + await plan.getByRole("button", { name: "Undo", exact: true }).click(); + await expect(fixup).toHaveText("Fixup (Replace)"); + await plan.getByRole("button", { name: "Redo", exact: true }).click(); + await plan.getByRole("button", { name: "Start Rebasing" }).click(); + await expect(plan).toBeHidden(); + expect(await ipcCalls(page, "vcs_rebase_editor_reply")).toMatchObject([ + { reply: { text: "pick bbbbbbbb\nfixup -c cccccccc\n" } }, + ]); +}); + +test("Paused rebase exposes its controls after a second stop and a cancelled message", async ({ workbench: page }) => { + await openLogRebase(page, "edit"); + const plan = page.getByRole("dialog", { name: "Edit Git Rebase Plan" }); + await plan.getByRole("button", { name: "Action for bbbbbbbb" }).click(); + await page.getByRole("option", { name: "Stop to Edit", exact: true }).click(); + await plan.getByRole("button", { name: "Start Rebasing" }).click(); + + const editing = page.getByRole("status").filter({ hasText: "Rebase stopped for editing" }); + await expect(editing.getByRole("button", { name: "Abort", exact: true })).toBeVisible(); + await editing.getByRole("button", { name: "Continue", exact: true }).click(); + const message = page.getByRole("dialog", { name: "Edit Commit Message" }); + await message.getByRole("button", { name: "Cancel", exact: true }).click(); + const paused = page.getByRole("status").filter({ hasText: "Rebase paused" }); + await paused.getByRole("button", { name: "Continue", exact: true }).click(); + await editing.getByRole("button", { name: "Continue", exact: true }).click(); + + await expect(page.getByRole("status").filter({ hasText: "Rebase continued" })).toBeVisible(); + await expect(editing).toBeHidden(); + await expect(paused).toBeHidden(); + const continues = (await ipcCalls(page, "vcs_rebase_with_editor")).slice(1); + expect(continues).toHaveLength(3); + expect(continues.every((call) => call.repo === "/dev/acme-api")).toBe(true); +}); + +test("Abort Rebase confirms the repository and targets the rebase that produced the notice", async ({ + workbench: page, +}) => { + const root = "/dev/acme-api"; + const nested = "/dev/acme-api/worker"; + await stubDesktop(page); + await page.evaluate( + async ({ root, nested }) => { + const h = window.__ipc.handlers; + const rebasing = new Set([root, nested]); + const branch = (repo: string) => ({ + head: "topic", + headCommit: "a".repeat(40), + operation: rebasing.has(repo) ? "rebase" : null, + upstream: null, + ahead: 0, + behind: 0, + }); + h.vcs_roots = () => [ + { root, ...branch(root) }, + { root: nested, ...branch(nested) }, + ]; + h.vcs_branch_info = ({ repo }) => branch((repo as string | null) ?? root); + h.vcs_status = () => [ + { path: root + "/work.txt", relPath: "work.txt", staged: null, unstaged: "conflicted", renamedFrom: null }, + ]; + h.vcs_operation = ({ repo }) => { + rebasing.delete(repo as string); + return null; + }; + const vcsPath = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsPath); + useVcs.setState({ available: true, root, roots: [root, nested], repo: root }); + await refreshNow(); + }, + { root, nested }, + ); + const abort = page + .getByRole("group", { name: "Merge conflicts" }) + .getByRole("button", { name: "Abort Rebase", exact: true }); + const confirmation = page.getByRole("dialog", { name: "Abort Rebase" }); + await abort.click(); + await expect(confirmation.getByText("Abort rebase in acme-api?")).toBeVisible(); + expect(await ipcCalls(page, "vcs_operation")).toEqual([]); + await confirmation.getByRole("button", { name: "Cancel", exact: true }).click(); + await expect(confirmation).toBeHidden(); + expect(await ipcCalls(page, "vcs_operation")).toEqual([]); + + await page.evaluate(async (nested) => { + const vcsPath = "/src/features/vcs/store.ts"; + const { selectRepo, refreshNow } = await import(/* @vite-ignore */ vcsPath); + await selectRepo(nested); + window.__ipc.handlers.vcs_status = () => []; + await refreshNow(); + }, nested); + const resolved = page.getByRole("status").filter({ hasText: "All conflicts resolved" }); + await resolved.getByRole("button", { name: "Abort Rebase", exact: true }).click(); + await expect(confirmation.getByText("Abort rebase in acme-api?")).toBeVisible(); + await confirmation.getByRole("button", { name: "Abort", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_operation")) + .toMatchObject([{ repo: root, op: { op: "abort", expected: "rebase" } }]); + await expect(abort).toBeVisible(); +}); diff --git a/e2e/mergeEditor.spec.ts b/e2e/mergeEditor.spec.ts index c6db0e7f4..296bb1ecb 100644 --- a/e2e/mergeEditor.spec.ts +++ b/e2e/mergeEditor.spec.ts @@ -15,10 +15,11 @@ async function mountMerge( page: Page, versions: [string | null, string | null, string | null] = [BASE, OURS, THEIRS], failure: string | null = null, + binary = false, ) { await page.goto("/"); await page.evaluate( - async ({ versions: [base, ours, theirs], failure }) => { + async ({ versions: [base, ours, theirs], failure, binary }) => { const reactPath = "/node_modules/.vite/deps/react.js"; const domPath = "/node_modules/.vite/deps/react-dom_client.js"; const react = await import(reactPath); @@ -37,6 +38,7 @@ async function mountMerge( : { status: "ok", data: { + binary, base, ours, theirs, @@ -53,9 +55,9 @@ async function mountMerge( createElement(MergeEditor, { input: { key: "merge:demo.ts", data: { path: "/project/demo.ts" } } }), ); }, - { versions, failure }, + { versions, failure, binary }, ); - if (!failure && !versions.some((text) => text?.includes("\0"))) + if (!failure && !binary) await expect(page.getByRole("region", { name: "Result" }).locator(".cm-content")).toBeVisible(); } @@ -110,7 +112,7 @@ async function captureWrites(page: Page) { Object.assign(window, { mergeWrites: calls }); commands.fsReadText = async () => ({ status: "ok", data: "working copy\n" }); commands.docOpen = async () => ({ status: "ok", data: { id: 777, version: 1 } }); - for (const command of ["docEdit", "docSave", "docClose", "fsDelete", "vcsStage"]) + for (const command of ["docEdit", "docSave", "docClose", "vcsAcceptConflictSide", "vcsStage"]) commands[command] = async (...args: unknown[]) => { calls.push({ command, args }); return { status: "ok", data: null }; @@ -177,10 +179,16 @@ test("footer buttons work when a click doesn't focus them, as in WebKit", async await expect(page.getByRole("dialog")).toContainText("Save and mark the file as resolved anyway?"); }); -test("binary and unreadable versions show an error with no Apply controls", async ({ page }) => { - await mountMerge(page, ["\0base", "\0ours", "\0theirs"]); - await expect(page.locator("#merge-host")).toContainText("Binary files cannot be resolved in the merge editor."); - await expect(page.locator("#merge-host").getByRole("button", { name: "Apply", exact: true })).toHaveCount(0); +test("binary conflicts offer whole-file acceptance and unreadable versions can be retried", async ({ page }) => { + await mountMerge(page, [null, null, null], null, true); + const host = page.locator("#merge-host"); + await expect(host).toContainText("Binary file. Choose which version to keep."); + await expect(host.getByRole("button", { name: "Apply", exact: true })).toHaveCount(0); + await captureWrites(page); + await host.getByRole("button", { name: "Accept Yours", exact: true }).click(); + await expect + .poll(() => writes(page)) + .toEqual([{ command: "vcsAcceptConflictSide", args: [["/project/demo.ts"], "ours"] }]); await mountMerge(page, [BASE, OURS, THEIRS], "Cannot read conflict versions"); await expect(page.locator("#merge-host")).toContainText("Cannot read conflict versions"); await expect(page.locator("#merge-host").getByRole("button", { name: "Retry", exact: true })).toBeVisible(); @@ -199,15 +207,13 @@ test("per-change controls also work from the keyboard", async ({ page }) => { await expect(status(page)).toHaveText("2 changes left, 1 conflict"); }); -test("accepting a deleted version removes the file before staging", async ({ page }) => { +test("accepting a deleted version delegates removal and staging to Git", async ({ page }) => { await mountMerge(page, [BASE, OURS, null]); await captureWrites(page); await page.locator("#merge-host").getByRole("button", { name: "Accept Theirs", exact: true }).click(); - await expect.poll(async () => (await writes(page)).some((call) => call.command === "vcsStage")).toBe(true); - expect(await writes(page)).toEqual([ - { command: "fsDelete", args: ["/project/demo.ts"] }, - { command: "vcsStage", args: [["/project/demo.ts"]] }, - ]); + await expect + .poll(() => writes(page)) + .toEqual([{ command: "vcsAcceptConflictSide", args: [["/project/demo.ts"], "theirs"] }]); }); test("a long side shows only the lines it changed against the base", async ({ page }) => { diff --git a/e2e/newBranch.spec.ts b/e2e/newBranch.spec.ts index 483b44afc..6bcfa0ebc 100644 --- a/e2e/newBranch.spec.ts +++ b/e2e/newBranch.spec.ts @@ -7,10 +7,16 @@ import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; const ROOT = "/dev/acme-api"; -async function openNewBranchDialog(page: Page, from?: string, withPrefix = false) { +async function openNewBranchDialog( + page: Page, + from?: string, + mergeBase = "1111111", + blocked = false, + withPrefix = false, +) { await stubDesktop(page); await page.evaluate( - async ({ root, from, withPrefix }) => { + async ({ root, from, mergeBase, blocked, withPrefix }) => { const h = window.__ipc.handlers; h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }]; h.vcs_branch_info = () => ({ @@ -35,7 +41,11 @@ async function openNewBranchDialog(page: Page, from?: string, withPrefix = false }, ...(withPrefix ? [{ name: "feature/weekly-totals", current: false, remote: false }] : []), ]; - h.vcs_create_branch = () => null; + h.vcs_create_branch = ({ options }) => + blocked && (options as { mode?: string } | null)?.mode === "normal" + ? { checkout: { kind: "localChanges", files: ["dirty.txt"] }, created: null } + : { checkout: { kind: "done" }, created: { tip: "2222222", previousTip: null } }; + h.vcs_merge_base = () => mergeBase; const vcsModule = "/src/features/vcs/store.ts"; const { useVcs, refreshNow, loadBranches } = await import(/* @vite-ignore */ vcsModule); useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); @@ -46,7 +56,7 @@ async function openNewBranchDialog(page: Page, from?: string, withPrefix = false if (from) void executeAction("vcs.log.newBranch", { id: from, summary: "Selected commit", repo: root }); else void executeAction("vcs.newBranch"); }, - { root: ROOT, from, withPrefix }, + { root: ROOT, from, mergeBase, blocked, withPrefix }, ); const dialog = page.getByRole("dialog", { name: from ? `Create New Branch from ${from}` : "Create New Branch" }); const input = dialog.getByRole(withPrefix ? "combobox" : "textbox", { name: "New branch name:" }); @@ -86,7 +96,9 @@ test("overwrites a local branch only after explicitly opting in", async ({ workb await create.click(); await expect .poll(() => ipcCalls(page, "vcs_create_branch")) - .toEqual([{ repo: ROOT, name: "main", start: from, checkout: true, overwrite: true }]); + .toMatchObject([ + { repo: ROOT, name: "main", start: from, checkout: true, overwrite: true, expectedTip: "1111111" }, + ]); }); test("a space typed in the middle keeps the caret after it", async ({ workbench: page }) => { @@ -99,6 +111,46 @@ test("a space typed in the middle keeps the caret after it", async ({ workbench: await expect(input).toHaveValue("a-xb"); }); +test("cancelling the drop-local-commits prompt keeps the branch intact", async ({ workbench: page }) => { + const { dialog, input } = await openNewBranchDialog(page, "2".repeat(40), "3333333"); + await input.fill("main"); + await dialog.getByRole("checkbox", { name: "Overwrite existing branch" }).check(); + await dialog.getByRole("button", { name: "Create", exact: true }).click(); + const warning = page.getByRole("dialog", { name: "Overwrite Branch main" }); + await expect(warning.getByRole("button", { name: "Drop Local Commits" })).toBeVisible(); + await warning.getByRole("button", { name: "Cancel", exact: true }).click(); + await expect(warning).toBeHidden(); + expect(await ipcCalls(page, "vcs_create_branch")).toEqual([]); +}); + +for (const [button, mode] of [ + ["Smart Checkout", "smart"], + ["Force Checkout", "force"], + ["Don't Checkout", null], +] as const) { + test(`checkout during branch creation offers ${button}`, async ({ workbench: page }) => { + const from = "2".repeat(40); + const { dialog, input } = await openNewBranchDialog(page, from, "1111111", true); + await input.fill("topic"); + await dialog.getByRole("button", { name: "Create", exact: true }).click(); + const review = page.getByRole("dialog", { name: "Git Checkout Problem" }); + await expect(review.getByRole("treeitem", { name: "dirty.txt" })).toBeVisible(); + await review.getByRole("button", { name: button, exact: true }).click(); + await expect(review).toBeHidden(); + await expect + .poll(() => ipcCalls(page, "vcs_create_branch")) + .toMatchObject( + (mode ? ["normal", "normal", mode] : ["normal"]).map((mode) => ({ + repo: ROOT, + name: "topic", + start: from, + checkout: true, + options: { mode }, + })), + ); + }); +} + test("pasted text has its spaces replaced", async ({ workbench: page }) => { const { dialog, input } = await openNewBranchDialog(page); await input.fill(""); @@ -112,7 +164,7 @@ test("pasted text has its spaces replaced", async ({ workbench: page }) => { test("the branch name and options line up, and prefix completion follows the field", async ({ workbench: page }) => { await page.setViewportSize({ width: 1100, height: 700 }); - const { dialog, input } = await openNewBranchDialog(page, undefined, true); + const { dialog, input } = await openNewBranchDialog(page, undefined, "1111111", false, true); const label = dialog.getByText("New branch name:", { exact: true }); const checkout = dialog.getByRole("checkbox", { name: "Checkout branch" }); const overwrite = dialog.getByRole("checkbox", { name: "Overwrite existing branch" }); @@ -151,5 +203,16 @@ test("the branch name and options line up, and prefix completion follows the fie await create.click(); await expect .poll(() => ipcCalls(page, "vcs_create_branch")) - .toEqual([{ repo: ROOT, name: "feature/review-totals", start: null, checkout: false, overwrite: false }]); + .toEqual([ + { + repo: ROOT, + name: "feature/review-totals", + start: null, + checkout: false, + overwrite: false, + expectedTip: null, + options: null, + shelfBatch: null, + }, + ]); }); diff --git a/e2e/pullDialogLayout.spec.ts b/e2e/pullDialogLayout.spec.ts index 75077e23f..ebdc5f227 100644 --- a/e2e/pullDialogLayout.spec.ts +++ b/e2e/pullDialogLayout.spec.ts @@ -49,8 +49,9 @@ test("Pull fits the remote branch picker and keeps flags accessible in a narrow }); const dialog = page.getByRole("dialog", { name: "Pull to main" }); - const branch = dialog.getByRole("button", { name: "Remote branch" }); + const branch = dialog.getByRole("button", { name: "Remote branch", exact: true }); await expect(branch).toHaveText("main"); + await expect(dialog.getByRole("button", { name: "Fetch remote branches" })).toBeVisible(); const body = dialog.locator("[data-dialog-body]"); await expect.poll(() => branch.evaluate((el) => el.getBoundingClientRect().width)).toBeGreaterThanOrEqual(250); expect(await body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0); @@ -65,7 +66,8 @@ test("Pull fits the remote branch picker and keeps flags accessible in a narrow await expect(dialog.locator("code", { hasText: "--ff-only" })).toBeVisible(); await modify.press("Enter"); await expect(page.getByRole("menuitemcheckbox", { name: "--ff-only" })).toBeChecked(); - await expect(page.getByRole("menuitemcheckbox", { name: "--no-commit" })).toBeDisabled(); + await expect(page.getByRole("menuitemcheckbox", { name: "--no-commit" })).toBeEnabled(); + await expect(page.getByRole("menuitemcheckbox", { name: "--rebase" })).toBeDisabled(); await page.keyboard.press("Escape"); await expect(modify).toBeFocused(); await dialog.getByRole("button", { name: "Pull", exact: true }).click(); @@ -78,7 +80,7 @@ test("Pull fits the remote branch picker and keeps flags accessible in a narrow op: "pullFrom", remote: "origin", branches: ["release/month-end-international-settlement-reconciliation"], - rebase: false, + rebase: null, options: { ffOnly: true }, }, }, diff --git a/e2e/pushTargetBranch.spec.ts b/e2e/pushTargetBranch.spec.ts index d5080f63e..baa171aa5 100644 --- a/e2e/pushTargetBranch.spec.ts +++ b/e2e/pushTargetBranch.spec.ts @@ -46,6 +46,7 @@ async function openPushDialog(page: Page, { outgoing = false, multi = false } = h.vcs_commit_files = () => [{ path: "checkout.ts", oldPath: null, kind: "modified" }]; h.vcs_has_hook = () => false; h.vcs_remotes = () => [{ name: "origin", url: "git@example.com:acme/api.git" }]; + h.vcs_push_target_choices = () => ({ branch: head, destination: null, destinations: [] }); const branch = (name: string, remote: boolean, upstream: string | null = null) => ({ name, remote, @@ -76,7 +77,7 @@ async function openPushDialog(page: Page, { outgoing = false, multi = false } = ); const dialog = page.getByRole("dialog", { name: /Push/ }); const input = multi - ? dialog.getByRole("textbox", { name: "Target branch of acme-api" }) + ? dialog.getByRole("combobox", { name: "Target branch of acme-api" }) : dialog.getByRole("combobox", { name: "Target branch" }); await expect(input).toBeVisible(); return { dialog, input }; @@ -210,7 +211,7 @@ test("Push keeps commit subjects and changed files readable in a narrow window", test("Push keeps per-repository targets editable with long source branches", async ({ workbench: page }) => { await page.setViewportSize({ width: 475, height: 620 }); const { dialog, input } = await openPushDialog(page, { outgoing: true, multi: true }); - const other = dialog.getByRole("textbox", { name: "Target branch of billing-and-refunds" }); + const other = dialog.getByRole("combobox", { name: "Target branch of billing-and-refunds" }); for (const field of [input, other]) { await expect .poll(() => @@ -226,4 +227,19 @@ test("Push keeps per-repository targets editable with long source branches", asy await expect(input).toHaveValue("release/checkout"); await expect(other).toHaveValue(/^feature\//); await expect(dialog.getByRole("checkbox", { name: "acme-api" })).toBeChecked(); + await expect(dialog.getByRole("checkbox", { name: "Push tags:" })).toBeInViewport(); +}); + +test("selecting a completion in a repository row keeps the Push dialog open", async ({ workbench: page }) => { + const { dialog, input } = await openPushDialog(page, { multi: true }); + const other = dialog.getByRole("combobox", { name: "Target branch of billing-and-refunds" }); + const otherTarget = await other.inputValue(); + await input.fill("error"); + await expect(page.getByRole("option", { name: "fix/error-auth" })).toBeVisible(); + await input.press("ArrowDown"); + await input.press("Enter"); + await expect(input).toHaveValue("fix/error-auth"); + await expect(other).toHaveValue(otherTarget); + await expect(dialog).toBeVisible(); + await expect(page.getByRole("listbox", { name: "Remote branches" })).toHaveCount(0); }); diff --git a/e2e/rollbackDialogLayout.spec.ts b/e2e/rollbackDialogLayout.spec.ts index 305462653..e9270dc52 100644 --- a/e2e/rollbackDialogLayout.spec.ts +++ b/e2e/rollbackDialogLayout.spec.ts @@ -1,4 +1,5 @@ import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; +import type { DiffEntryRequest, FileStatus } from "../src/bindings"; test("Rollback fits a short window and scopes its options to checked files", async ({ workbench: page }) => { await page.setViewportSize({ width: 410, height: 330 }); @@ -72,3 +73,50 @@ test("Rollback fits a short window and scopes its options to checked files", asy await expect.poll(() => ipcCalls(page, "vcs_discard")).toEqual([{ paths: [modified[0]] }]); expect(await ipcCalls(page, "vcs_unstage")).toEqual([]); }); + +test("a selected submodule can restore the parent index and checkout separately", async ({ workbench: page }) => { + await stubDesktop(page); + const root = "/dev/parent"; + const path = root + "/libs/module"; + await page.evaluate( + async ({ root, path }) => { + const branch = { head: "main", headCommit: "a", upstream: null, ahead: 0, behind: 0, operation: null }; + const status: FileStatus[] = [ + { path, relPath: "libs/module", staged: "modified", unstaged: "modified", renamedFrom: null }, + { path: path + "/child.txt", relPath: "child.txt", staged: null, unstaged: "modified", renamedFrom: null }, + ]; + const h = window.__ipc.handlers; + h.vcs_branch_info = () => branch; + h.vcs_roots = () => [root, path].map((root) => ({ root, ...branch })); + h.vcs_status = () => status; + h.vcs_diff_entries = ({ entries }) => + (entries as DiffEntryRequest[]).map((entry) => + entry.path === path + ? { mode: "160000", gitlink: entry.rev === "HEAD" ? "a" : entry.rev === ":0" ? "b" : "c" } + : null, + ); + h.vcs_rollback_submodules = () => null; + const storeModule = "/src/features/vcs/store.ts"; + const contextModule = "/src/platform/context.ts"; + const actionsModule = "/src/platform/actions.ts"; + const { useVcs } = await import(/* @vite-ignore */ storeModule); + const { setContext } = await import(/* @vite-ignore */ contextModule); + const { executeAction } = await import(/* @vite-ignore */ actionsModule); + useVcs.setState({ available: true, root, repo: root, roots: [root, path], branch, status }); + setContext("vcsAvailable", true); + await executeAction("vcs.rollback", [path]); + }, + { root, path }, + ); + const dialog = page.getByRole("dialog", { name: "Rollback Changes", exact: true }); + const checkout = dialog.getByRole("checkbox", { name: "Restore selected submodule checkouts" }); + await expect(checkout).toBeChecked(); + await expect(dialog.getByText("child.txt", { exact: true })).toHaveCount(0); + await checkout.uncheck(); + await dialog.getByRole("button", { name: "Rollback", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_rollback_submodules")) + .toEqual([{ paths: [path], source: "head", restoreCheckout: false }]); + expect(await ipcCalls(page, "vcs_unstage")).toEqual([]); + expect(await ipcCalls(page, "vcs_discard")).toEqual([]); +}); diff --git a/e2e/settingsFormLayout.spec.ts b/e2e/settingsFormLayout.spec.ts index e9840adcb..8bc46f2ca 100644 --- a/e2e/settingsFormLayout.spec.ts +++ b/e2e/settingsFormLayout.spec.ts @@ -8,6 +8,29 @@ async function selectPage(page: Page, id: string) { }, id); } +test("Git settings expose fetch tag modes and the check-only mode", async ({ workbench: page }) => { + await page.keyboard.press("Meta+,"); + const dialog = page.getByRole("dialog", { name: "Settings", exact: true }); + await expect(dialog).toBeVisible(); + await selectPage(page, "vcs.git"); + const mode = dialog.getByRole("button", { name: "Fetch tags", exact: true }); + await expect(mode).toHaveText("Auto"); + await mode.click(); + const choices = page.getByRole("listbox"); + for (const label of ["Auto", "Sync", "Always", "Never"]) { + await expect(choices.getByRole("option", { name: new RegExp(`^${label}`) })).toBeVisible(); + } + const sync = choices.getByRole("option", { name: /^Sync/ }); + await expect(sync).toContainText("Delete local tags missing on remote"); + await sync.click(); + await expect(mode).toHaveText("Sync"); + const incoming = dialog.getByRole("button", { name: "Explicitly check for incoming commits on remotes" }); + await incoming.click(); + await choices.getByRole("option", { name: "Check without fetching", exact: true }).click(); + await expect(incoming).toHaveText("Check without fetching"); + await expect(dialog.getByRole("button", { name: "Apply", exact: true })).toBeEnabled(); +}); + test("settings forms share control columns and keep font metrics on one row", async ({ workbench: page }) => { await page.keyboard.press("Meta+,"); const dialog = page.getByRole("dialog", { name: "Settings", exact: true }); diff --git a/e2e/stagedEditor.spec.ts b/e2e/stagedEditor.spec.ts new file mode 100644 index 000000000..ff8a1691c --- /dev/null +++ b/e2e/stagedEditor.spec.ts @@ -0,0 +1,929 @@ +import type { Page } from "@playwright/test"; +import type { EditorView } from "@codemirror/view"; +import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures"; + +test("edits the staged version and keeps an unsaved draft when the index changes", async ({ workbench: page }) => { + const root = "/dev/acme-api"; + const path = `${root}/build.gradle.kts`; + await openFromTree(page, "build.gradle.kts"); + await stubDesktop(page); + await page.evaluate( + async ({ root, path }) => { + let text = "val staged = 1\n"; + let version = "one"; + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, head: "main", headCommit: "1111111" }]; + h.vcs_branch_info = () => ({ head: "main", headCommit: "1111111", operation: null }); + h.vcs_status = () => [{ path, relPath: "build.gradle.kts", staged: "modified", unstaged: "modified" }]; + h.vcs_staged_text = () => ({ text, version }); + h.vcs_file_at = (args) => (args.rev === ":0" ? text : "val committed = 0\n"); + h.fs_read_text = () => "val working = 4\n"; + h.vcs_diff_hunks = () => []; + h.vcs_save_staged_text = (args) => { + if (args.path !== path || args.version !== version) { + throw { kind: "outOfSync", message: "The staged version changed on disk" }; + } + text = String(args.text); + version = "saved"; + return version; + }; + h.test_restage = () => { + text = "val external = 3\n"; + version = "external"; + }; + const project = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ project); + useProject.setState((s: { settings: Record }) => ({ + settings: { + ...s.settings, + vcs: { git: { stagingArea: true }, commit: { nonModal: true }, diffAsEditorTab: true }, + }, + })); + const store = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ store); + useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); + await refreshNow(); + }, + { root, path }, + ); + + await page.keyboard.press("Meta+k"); + const changes = page.getByRole("tree", { name: "Changes", exact: true }); + const staged = changes.getByRole("treeitem", { name: "Staged Changes", exact: false }).first(); + await expect(staged).toBeVisible(); + await changes.getByText("build.gradle.kts", { exact: true }).first().click({ button: "right" }); + await page.getByRole("menuitem", { name: /^Jump to Source/ }).click(); + const editor = page.getByRole("textbox", { name: "Staged version editor" }); + const tab = page.getByRole("tab", { name: /Staged: build\.gradle\.kts/ }); + await expect(tab).toHaveAttribute("aria-selected", "true"); + await expect(editor).toContainText("val staged = 1"); + await editor.fill("val staged = 2\n"); + await editor.press("Meta+s"); + await expect + .poll(() => ipcCalls(page, "vcs_save_staged_text")) + .toEqual([{ path, text: "val staged = 2\n", version: "one" }]); + await expect.poll(() => ipcCalls(page, "doc_save")).toEqual([]); + + await editor.fill("val draft = 4\n"); + await page.evaluate(() => window.__ipc.handlers.test_restage?.({})); + await editor.press("Meta+s"); + await expect(page.getByText("The staged version changed on disk", { exact: true }).first()).toBeVisible(); + await expect(editor).toContainText("val draft = 4"); + await page.getByRole("button", { name: "Reload Staged Version", exact: true }).click(); + await page.getByRole("dialog", { name: "Reload Staged Version" }).getByRole("button", { name: "Reload" }).click(); + await expect(editor).toContainText("val external = 3"); + + await page.getByRole("button", { name: "Compare", exact: true }).click(); + await page.getByRole("menuitem", { name: "Compare with HEAD", exact: true }).click(); + await expect(page.getByRole("tab", { name: /HEAD ↔ Staged \(index\)/ })).toHaveAttribute("aria-selected", "true"); + await expect(page.locator(".cm-editor:visible .cm-content").filter({ hasText: "val committed = 0" })).toBeVisible(); + await expect(page.locator(".cm-editor:visible .cm-content").filter({ hasText: "val external = 3" })).toBeVisible(); + + await tab.click(); + await page.getByRole("button", { name: "Compare", exact: true }).click(); + await page.getByRole("menuitem", { name: "Compare with Local Version", exact: true }).click(); + const workingDiff = page.getByRole("tab", { name: /Staged \(index\) ↔ Local Version/ }); + await expect(workingDiff).toHaveAttribute("aria-selected", "true"); + await tab.click(); + + await page.getByRole("button", { name: "Show Local Version" }).click(); + const localTab = page.getByRole("tab", { name: "build.gradle.kts", exact: true }); + await expect(localTab).toHaveAttribute("aria-selected", "true"); + await localTab.click({ button: "right" }); + await page.getByRole("menuitem", { name: "Compare with Staged Version", exact: true }).click(); + await expect(workingDiff).toHaveAttribute("aria-selected", "true"); + + await tab.click(); + await page.getByRole("button", { name: "Compare", exact: true }).click(); + await page.getByRole("menuitem", { name: "Compare Three Versions", exact: true }).click(); + const headPane = page.locator('.cm-content[aria-label="HEAD"]:visible'); + const indexPane = page.locator('.cm-content[aria-label="Staged (index)"]:visible'); + const localPane = page.locator('.cm-content[aria-label="Local Version"]:visible'); + await expect(headPane).toContainText("val committed = 0"); + await expect(indexPane).toContainText("val external = 3"); + await expect(localPane).not.toBeEmpty(); + const working = await localPane.textContent(); + + await page.getByRole("button", { name: "Unstage Change", exact: true }).click(); + await expect(indexPane).toContainText("val committed = 0"); + await expect + .poll(() => ipcCalls(page, "vcs_save_staged_text")) + .toEqual([ + { path, text: "val staged = 2\n", version: "one" }, + { path, text: "val draft = 4\n", version: "saved" }, + { path, text: "val committed = 0\n", version: "external" }, + ]); + + await page.getByRole("button", { name: "Stage Change (git add hunk)", exact: true }).click(); + await expect.poll(async () => (await ipcCalls(page, "vcs_save_staged_text")).length).toBe(4); + await expect(indexPane).toHaveText(working ?? ""); + await expect(localPane).toHaveText(working ?? ""); + await expect.poll(() => ipcCalls(page, "doc_save")).toEqual([]); +}); + +for (const comparison of ["three-way", "two-way", "local"] as const) { + test(`shares index drafts with the ${comparison} diff and keeps them on a failed close`, async ({ + workbench: page, + }) => { + await checkSharedIndexDraft(page, comparison); + }); +} + +async function checkSharedIndexDraft(page: Page, comparison: "three-way" | "two-way" | "local") { + const root = "/dev/acme-api"; + const path = `${root}/build.gradle.kts`; + await openFromTree(page, "build.gradle.kts"); + await stubDesktop(page); + await page.evaluate( + async ({ root, path }) => { + let text = "val staged = 1\n"; + let version = "one"; + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, head: "main", headCommit: "1111111" }]; + h.vcs_branch_info = () => ({ head: "main", headCommit: "1111111", operation: null }); + h.vcs_status = () => [{ path, relPath: "build.gradle.kts", staged: "modified", unstaged: "modified" }]; + h.vcs_file_at = (args) => (args.rev === ":0" ? text : "val head = 0\n"); + h.vcs_staged_text = () => ({ text, version }); + h.vcs_save_staged_text = (args) => { + if (args.path !== path || args.version !== version) + throw { kind: "outOfSync", message: "The staged version changed on disk" }; + text = String(args.text); + version = "saved"; + return version; + }; + h.test_restage = () => { + text = "val external = 4\n"; + version = "external"; + }; + const project = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ project); + useProject.setState((s: { project: Record; settings: Record }) => ({ + project: { ...s.project, isGit: true }, + settings: { ...s.settings, files: { autoSave: false }, vcs: { git: { stagingArea: true } } }, + })); + const store = "/src/features/vcs/store.ts"; + await (await import(/* @vite-ignore */ store)).refreshNow(); + const actions = "/src/platform/actions.ts"; + await (await import(/* @vite-ignore */ actions)).executeAction("vcs.showStagedVersion", path); + }, + { root, path }, + ); + const staged = page.locator('.cm-content[aria-label="Staged version editor"]'); + await expect(staged).toContainText("val staged = 1"); + const compare = () => + page.evaluate( + async ({ path, comparison }) => { + const input = "/src/features/vcs/diffInput.ts"; + const dialog = "/src/features/vcs/diffDialog.tsx"; + const { stagingGutterDiffData, workingDiffData } = await import(/* @vite-ignore */ input); + const data = + comparison === "three-way" + ? stagingGutterDiffData(path) + : { ...workingDiffData(path, 0, comparison === "local" ? "unstaged" : "staged"), mode: "split" }; + (await import(/* @vite-ignore */ dialog)).openDiffDialog(data); + }, + { path, comparison }, + ); + await compare(); + const modal = page.getByRole("dialog", { name: /build\.gradle\.kts.*Staged/ }); + const index = modal.locator('.cm-content[aria-label="Staged (index)"]'); + await expect(index).toBeEditable(); + await index.fill("val draft = 2\n"); + await expect(staged).toContainText("val draft = 2"); + if (comparison === "two-way") { + await modal.getByRole("button", { name: "Unified Viewer", exact: true }).click(); + await expect(modal.locator(".cm-content")).toHaveCount(1); + await expect(index).toBeEditable(); + await expect(index).toContainText("val draft = 2"); + } + await index.press("Meta+z"); + await expect(staged).toContainText("val staged = 1"); + await index.press("Meta+Shift+z"); + await expect(staged).toContainText("val draft = 2"); + await expect.poll(() => ipcCalls(page, "vcs_save_staged_text")).toEqual([]); + const close = modal.getByRole("button", { name: "Close", exact: true }).last(); + await close.click(); + await expect(modal).toBeHidden(); + await expect + .poll(() => ipcCalls(page, "vcs_save_staged_text")) + .toEqual([{ path, text: "val draft = 2\n", version: "one" }]); + + await compare(); + await expect(index).toBeEditable(); + await index.fill("val unsaved = 3\n"); + await page.evaluate(() => window.__ipc.handlers.test_restage?.({})); + await close.click(); + const error = modal.getByRole("alert").filter({ hasText: "The staged version changed on disk" }); + await expect(error).toBeVisible(); + await expect(index).toContainText("val unsaved = 3"); + await expect(staged).toContainText("val unsaved = 3"); + await error.getByRole("button", { name: "Reload Staged Version" }).click(); + await page.getByRole("dialog", { name: "Reload Staged Version" }).getByRole("button", { name: "Reload" }).click(); + await expect(index).toContainText("val external = 4"); + await expect(staged).toContainText("val external = 4"); + await close.click(); + await expect(modal).toBeHidden(); + await expect.poll(() => ipcCalls(page, "vcs_save_staged_text")).toHaveLength(2); + await expect.poll(() => ipcCalls(page, "doc_save")).toEqual([]); +} + +test("applies individual changes in staging comparisons and rejects a stale index", async ({ workbench: page }) => { + const path = "/dev/acme-api/build.gradle.kts"; + const body = (a: string, b: string, c: string) => + `val alpha = "${a}"\nval gap1 = true\nval beta = "${b}"\nval gap2 = true\nval gamma = "${c}"\n`; + const head = body("HEAD", "HEAD", "HEAD"); + const index = body("index", "HEAD", "index"); + const external = body("external", "HEAD", "index"); + const local = body("index", "draft", "local"); + await openFromTree(page, "build.gradle.kts"); + await stubDesktop(page); + await page.evaluate( + async ({ path, head, index, external }) => { + let text = index; + let version = 1; + const h = window.__ipc.handlers; + const root = "/dev/acme-api"; + h.vcs_roots = () => [{ root, head: "main", headCommit: "1111111" }]; + h.vcs_branch_info = () => ({ head: "main", headCommit: "1111111", operation: null }); + h.vcs_status = () => [{ path, relPath: "build.gradle.kts", staged: "modified", unstaged: "modified" }]; + h.vcs_file_at = (args) => (args.rev === ":0" ? text.replaceAll("\n", "\r\n") : head); + h.vcs_staged_text = () => ({ text, version: String(version) }); + h.fs_probe = () => ({ size: head.length, binary: false, tooLarge: false }); + h.vcs_save_staged_text = (args) => { + if (args.path !== path || args.version !== String(version)) { + throw { kind: "outOfSync", message: "The staged version changed on disk" }; + } + text = String(args.text); + return String(++version); + }; + h.test_restage = () => { + text = external; + version++; + }; + const project = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ project); + useProject.setState((s: { project: Record; settings: Record }) => ({ + project: { ...s.project, isGit: true }, + settings: { + ...s.settings, + files: { autoSave: false }, + vcs: { git: { stagingArea: true }, commit: { nonModal: true } }, + }, + })); + const store = "/src/features/vcs/store.ts"; + const { refreshNow } = await import(/* @vite-ignore */ store); + await refreshNow(); + }, + { path, head, index, external }, + ); + await page.locator(".cm-content:visible").evaluate((el, local) => { + const { view } = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile; + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: local } }); + }, local); + const compare = (side: "staged" | "unstaged") => + page.evaluate( + async ({ path, side }) => { + const input = "/src/features/vcs/diffInput.ts"; + const { openDiff, workingDiffData } = await import(/* @vite-ignore */ input); + await openDiff({ ...workingDiffData(path, 0, side), mode: "split" }); + }, + { path, side }, + ); + await compare("staged"); + const unstage = page.locator(".cm-gutter:visible").getByRole("button", { name: "Unstage Change", exact: true }); + await expect(unstage).toHaveCount(2); + await expect(page.getByText("CRLF", { exact: true })).toBeVisible(); + await page.evaluate(() => window.__ipc.handlers.test_restage?.({})); + await unstage.first().click(); + await expect(page.getByText("The staged version changed on disk", { exact: true }).first()).toBeVisible(); + await expect(page.locator(".cm-content:visible").filter({ hasText: 'val alpha = "external"' })).toHaveCount(1); + await unstage.first().click(); + await expect + .poll(() => ipcCalls(page, "vcs_save_staged_text")) + .toEqual([ + { path, text: body("HEAD", "HEAD", "index"), version: "1" }, + { path, text: body("HEAD", "HEAD", "index"), version: "2" }, + ]); + + await compare("unstaged"); + await page.getByRole("button", { name: "Unified Viewer", exact: true }).click(); + const stage = page.locator(".cm-gutter:visible").getByRole("button", { name: "Stage Change (git add hunk)" }); + await expect(stage).toHaveCount(3); + await stage.nth(1).click(); + await expect(stage).toHaveCount(2); + await expect.poll(() => ipcCalls(page, "vcs_save_staged_text")).toHaveLength(3); + expect((await ipcCalls(page, "vcs_save_staged_text"))[2]).toEqual({ + path, + text: body("HEAD", "draft", "index"), + version: "3", + }); + const reverts = page.locator(".cm-editor:visible").getByTitle("Revert this change", { exact: true }); + await expect(reverts).toHaveCount(2); + await reverts.nth(1).click(); + await expect(stage).toHaveCount(1); + const working = page.getByRole("tab", { name: "build.gradle.kts", exact: true }); + await working.click(); + const editor = page.locator(".cm-editor:visible .cm-content"); + await expect(editor).toContainText('val gamma = "index"'); + await expect(editor).toContainText('val alpha = "index"'); + await expect(editor).toContainText('val beta = "draft"'); + await expect.poll(() => ipcCalls(page, "doc_save")).toEqual([]); + await expect.poll(() => ipcCalls(page, "vcs_stage_hunks")).toEqual([]); +}); + +test("edits and stages from the index in unified diffs of read-only files", async ({ workbench: page }) => { + const root = "/dev/acme-api"; + const path = `${root}/build.gradle.kts`; + const body = (a: string, b: string) => `val alpha = "${a}"\nval gap = true\nval beta = "${b}"\n`; + const staged = body("index", "index"); + await openFromTree(page, "build.gradle.kts"); + await stubDesktop(page); + await page.locator(".cm-content:visible").evaluate( + (el, working) => { + const { view } = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile; + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: working } }); + }, + body("local", "local"), + ); + await page.evaluate( + async ({ path, root, staged }) => { + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, head: "main", headCommit: "1111111" }]; + h.vcs_branch_info = () => ({ head: "main", headCommit: "1111111", operation: null }); + h.vcs_status = () => [{ path, relPath: "build.gradle.kts", staged: "modified", unstaged: "modified" }]; + h.vcs_file_at = () => staged; + h.vcs_staged_text = () => ({ text: staged, version: "original" }); + h.vcs_save_staged_text = () => "saved"; + const project = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ project); + useProject.setState((s: { project: Record; settings: Record }) => ({ + project: { ...s.project, isGit: true }, + settings: { ...s.settings, files: { autoSave: false }, vcs: { git: { stagingArea: true } } }, + })); + const controller = "/src/editor/core/controller.ts"; + const { editorController } = await import(/* @vite-ignore */ controller); + const model = editorController().manager.get(path); + if (!model) throw new Error("Missing working document"); + h.test_set_readonly = ({ readOnly }) => model.setMeta({ readOnly }); + model.setMeta({ readOnly: true }); + const store = "/src/features/vcs/store.ts"; + await (await import(/* @vite-ignore */ store)).refreshNow(); + const input = "/src/features/vcs/diffInput.ts"; + const dialog = "/src/features/vcs/diffDialog.tsx"; + const { workingDiffData } = await import(/* @vite-ignore */ input); + (await import(/* @vite-ignore */ dialog)).openDiffDialog({ + ...workingDiffData(path, 2, "unstaged"), + mode: "unified", + }); + }, + { path, root, staged }, + ); + const modal = page.getByRole("dialog", { name: /build\.gradle\.kts.*Staged/ }); + const index = modal.locator('.cm-content[aria-label="Staged (index)"]'); + await expect(index).toBeEditable(); + await expect(index).toHaveText(/val alpha = "index"\s+val alpha = "local"/, { useInnerText: true }); + const setReadOnly = (readOnly: boolean) => + page.evaluate((readOnly) => window.__ipc.handlers.test_set_readonly?.({ readOnly }), readOnly); + await setReadOnly(false); + await expect(modal.locator(".cm-content")).toBeEditable(); + await expect(index).toHaveCount(0); + await setReadOnly(true); + await expect(index).toBeEditable(); + await expect(modal.getByTitle("Revert this change", { exact: true })).toHaveCount(0); + await index.evaluate((el) => { + const { view } = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile; + const line = view.state.doc.line(1); + view.dispatch({ + changes: { from: line.from, to: line.to, insert: 'val alpha = "draft"' }, + userEvent: "input.type", + }); + }); + await expect(index).toContainText('val alpha = "draft"'); + const stage = modal.locator(".cm-gutter").getByRole("button", { name: "Stage Change (git add hunk)" }); + await expect(stage).toHaveCount(2); + await stage.last().click(); + await expect(stage).toHaveCount(1); + await expect.poll(() => ipcCalls(page, "vcs_save_staged_text")).toEqual([]); + await modal.getByRole("button", { name: "Close", exact: true }).last().click(); + await expect(modal).toBeHidden(); + await expect + .poll(() => ipcCalls(page, "vcs_save_staged_text")) + .toEqual([{ path, text: body("draft", "local"), version: "original" }]); + await expect.poll(() => ipcCalls(page, "doc_save")).toEqual([]); +}); + +test("edits and reverts the local pane of a three-version diff without saving the file", async ({ + workbench: page, +}) => { + const root = "/dev/acme-api"; + const path = `${root}/build.gradle.kts`; + const body = (a: string, b: string, c: string) => + `val alpha = "${a}"\nval gap1 = true\nval beta = "${b}"\nval gap2 = true\nval gamma = "${c}"\n`; + const head = body("HEAD", "HEAD", "HEAD"); + const index = body("index", "HEAD", "index"); + await stubDesktop(page); + await page.evaluate( + async ({ root, path, head, index }) => { + const h = window.__ipc.handlers; + let text = index; + let version = 1; + let saves = 0; + h.test_saves = () => saves; + h.vcs_roots = () => [{ root, head: "main", headCommit: "1111111" }]; + h.vcs_branch_info = () => ({ head: "main", headCommit: "1111111", operation: null }); + h.vcs_status = () => [{ path, relPath: "build.gradle.kts", staged: "modified", unstaged: "modified" }]; + h.vcs_file_at = (args) => (args.rev === ":0" ? text : head); + h.vcs_staged_text = () => ({ text, version: String(version) }); + h.vcs_save_staged_text = (args) => { + if (args.path !== path || args.version !== String(version)) throw new Error("stale index"); + text = String(args.text); + return String(++version); + }; + h.fs_probe = () => ({ size: head.length, binary: false, tooLarge: false }); + const project = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ project); + useProject.setState((s: { project: Record; settings: Record }) => ({ + project: { ...s.project, isGit: true }, + settings: { + ...s.settings, + files: { autoSave: false }, + vcs: { git: { stagingArea: true }, commit: { nonModal: true } }, + }, + })); + const editor = "/src/editor/api.ts"; + (await import(/* @vite-ignore */ editor)).onEditorEvent((event: { type: string; path: string }) => { + if (event.type === "docSaved" && event.path === path) saves++; + }); + const input = "/src/features/vcs/diffInput.ts"; + const { openDiff, stagingGutterDiffData } = await import(/* @vite-ignore */ input); + await openDiff(stagingGutterDiffData(path, 0)); + }, + { root, path, head, index }, + ); + + const local = page.locator('.cm-content[aria-label="Local Version"]:visible'); + await expect(local).toBeEditable(); + await local.fill(body("index", "draft", "temporary")); + const revert = page.getByRole("button", { name: "Revert Change", exact: true }); + await expect(revert).toHaveCount(2); + await revert.nth(1).click(); + await expect(local).toContainText('val gamma = "index"'); + await expect(local).toContainText('val beta = "draft"'); + await expect(revert).toHaveCount(1); + await local.press("Meta+z"); + await expect(local).toContainText('val gamma = "temporary"'); + await local.press("Meta+Shift+z"); + await expect(local).toContainText('val gamma = "index"'); + const stage = page.getByRole("button", { name: "Stage Change (git add hunk)", exact: true }); + await expect(stage).toHaveCount(1); + await stage.click(); + await expect + .poll(() => ipcCalls(page, "vcs_save_staged_text")) + .toEqual([{ path, text: body("index", "draft", "index"), version: "1" }]); + expect(await page.evaluate(() => window.__ipc.handlers.test_saves?.({}))).toBe(0); + + await page.getByRole("button", { name: "Jump to Source", exact: true }).click(); + const source = page.locator(".cm-content:visible"); + await expect(source).toContainText('val beta = "draft"'); + await expect(source).toContainText('val gamma = "index"'); + await source.press("Meta+s"); + await expect.poll(() => page.evaluate(() => window.__ipc.handlers.test_saves?.({}))).toBe(1); +}); + +test("exports the selected side of the index from the staging tree", async ({ workbench: page }) => { + const root = "/dev/acme-api"; + const path = `${root}/build.gradle.kts`; + const patch = "diff --git a/build.gradle.kts b/build.gradle.kts\n"; + await stubDesktop(page); + await page.evaluate( + async ({ root, path, patch }) => { + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, head: "main", headCommit: "1111111" }]; + h.vcs_branch_info = () => ({ head: "main", headCommit: "1111111", operation: null }); + h.vcs_status = () => [{ path, relPath: "build.gradle.kts", staged: "modified", unstaged: "modified" }]; + h.vcs_create_patch = () => patch; + h.clipboard_write_text = () => null; + h.vcs_write_patch = () => null; + const project = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ project); + useProject.setState((s: { settings: Record }) => ({ + settings: { + ...s.settings, + vcs: { git: { stagingArea: true }, commit: { nonModal: true }, confirmation: { onPatchCreated: "no" } }, + }, + })); + const store = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ store); + useVcs.setState({ available: true, root, repo: root }); + await refreshNow(); + }, + { root, path, patch }, + ); + + await page.keyboard.press("Meta+k"); + const changes = page.getByRole("tree", { name: "Changes", exact: true }); + const rows = changes.getByText("build.gradle.kts", { exact: true }); + await expect(rows).toHaveCount(2); + await rows.first().click({ button: "right" }); + await page.getByRole("menuitem", { name: "Create Patch…", exact: true }).click(); + const dialog = page.getByRole("dialog", { name: "Create Patch", exact: true }); + await expect(dialog).toContainText("build.gradle.kts"); + await expect(dialog.getByRole("textbox", { name: "Base directory" })).toHaveValue(root); + await dialog.getByRole("textbox", { name: "Base directory" }).fill("/dev"); + await dialog.getByRole("button", { name: "Patch encoding" }).click(); + await page.getByRole("option", { name: "UTF-16LE" }).click(); + const destination = await dialog.getByRole("textbox", { name: "Patch file" }).inputValue(); + await dialog.getByRole("button", { name: "Create", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "vcs_write_patch")) + .toEqual([{ path: destination, patch, encoding: "utf-16le" }]); + + await rows.last().click({ button: "right" }); + await page.getByRole("menuitem", { name: "Copy as Patch to Clipboard", exact: true }).click(); + await expect.poll(() => ipcCalls(page, "clipboard_write_text")).toEqual([{ text: patch }]); + + await rows.first().click(); + await rows.last().click({ modifiers: ["Meta"] }); + await page.evaluate(async () => { + const actions = "/src/platform/actions.ts"; + await (await import(/* @vite-ignore */ actions)).executeAction("vcs.copyPatch"); + }); + await expect + .poll(() => ipcCalls(page, "vcs_create_patch")) + .toEqual( + ["staged", "unstaged", "both"].map((side) => ({ + repo: null, + base: side === "staged" ? "/dev" : null, + source: { from: "staging", entries: [{ path, side, renamedFrom: null }], reverse: false }, + })), + ); +}); + +test("rolls back selected unstaged rows and can stage a path without its contents", async ({ workbench: page }) => { + const root = "/dev/acme-api"; + const tracked = `${root}/build.gradle.kts`; + const untracked = `${root}/fresh.txt`; + await stubDesktop(page); + await page.evaluate( + async ({ root, tracked, untracked }) => { + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, head: "main", headCommit: "1111111" }]; + h.vcs_branch_info = () => ({ head: "main", headCommit: "1111111", operation: null }); + h.vcs_status = () => [ + { path: tracked, relPath: "build.gradle.kts", staged: "modified", unstaged: "modified" }, + { path: untracked, relPath: "fresh.txt", staged: null, unstaged: "untracked" }, + ]; + h.vcs_restore_unstaged = () => null; + h.vcs_stage_without_content = () => null; + const project = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ project); + useProject.setState((s: { settings: Record }) => ({ + settings: { ...s.settings, vcs: { git: { stagingArea: true }, commit: { nonModal: true } } }, + })); + const store = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ store); + useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); + await refreshNow(); + }, + { root, tracked, untracked }, + ); + + await page.keyboard.press("Meta+k"); + const changes = page.getByRole("tree", { name: "Changes", exact: true }); + const trackedRows = changes.getByText("build.gradle.kts", { exact: true }); + await expect(trackedRows).toHaveCount(2); + await trackedRows.first().click({ button: "right" }); + await expect(page.getByRole("menuitem", { name: "Unstage", exact: true })).toBeVisible(); + await expect(page.getByRole("menuitem", { name: /^Rollback/ })).toHaveCount(0); + await page.keyboard.press("Escape"); + await trackedRows.last().click(); + await page.keyboard.press("Meta+Alt+z"); + const dialog = page.getByRole("dialog", { name: "Rollback Unstaged Changes" }); + await expect(dialog).toContainText("build.gradle.kts"); + await dialog.getByRole("button", { name: "Rollback", exact: true }).click(); + await expect.poll(() => ipcCalls(page, "vcs_restore_unstaged")).toEqual([{ paths: [tracked] }]); + await expect.poll(() => ipcCalls(page, "vcs_unstage")).toEqual([]); + await expect.poll(() => ipcCalls(page, "vcs_discard")).toEqual([]); + + await changes.getByRole("treeitem", { name: /^Unversioned Files/ }).click(); + await page.keyboard.press("ArrowRight"); + await changes.getByText("fresh.txt", { exact: true }).click({ button: "right" }); + await page.getByRole("menuitem", { name: "Stage Without Content", exact: true }).click(); + await expect.poll(() => ipcCalls(page, "vcs_stage_without_content")).toEqual([{ paths: [untracked] }]); + await expect.poll(() => ipcCalls(page, "vcs_stage")).toEqual([]); +}); + +test("staging shortcuts allow requiring index changes and staging tracked files in bulk", async ({ + workbench: page, +}) => { + const root = "/dev/acme-api"; + const tracked = root + "/build.gradle.kts"; + const untracked = root + "/notes.txt"; + await stubDesktop(page); + await page.evaluate( + async ({ root, tracked, untracked }) => { + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, head: "main", headCommit: "1111111", operation: null }]; + h.vcs_branch_info = () => ({ head: "main", headCommit: "1111111", operation: null }); + const stage = new Set(); + h.vcs_status = () => + [tracked, untracked].map((path) => ({ + path, + relPath: path.slice(root.length + 1), + renamedFrom: null, + staged: stage.has(path) ? (path === tracked ? "modified" : "added") : null, + unstaged: stage.has(path) ? null : path === tracked ? "modified" : "untracked", + })); + h.vcs_stage = ({ paths }) => { + for (const path of paths as string[]) stage.add(path); + return null; + }; + const settings = { + vcs: { git: { stagingArea: true }, commit: { nonModal: true, commitAllWhenNothingStaged: true } }, + }; + h.settings_get = () => structuredClone(settings); + h.settings_set = ({ key, value }) => { + if (key === "vcs.commit.commitAllWhenNothingStaged") { + settings.vcs.commit.commitAllWhenNothingStaged = JSON.parse(String(value)); + } + return structuredClone(settings); + }; + const projectModule = "/src/platform/project.ts"; + const { loadSettings } = await import(/* @vite-ignore */ projectModule); + await loadSettings(); + const vcsModule = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule); + useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); + await refreshNow(); + }, + { root, tracked, untracked }, + ); + + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + await panel.getByRole("textbox", { name: "Commit message" }).fill("Update staging"); + await expect(panel.getByRole("button", { name: "Commit All", exact: true })).toBeEnabled(); + const options = panel.getByRole("button", { name: "Commit Options" }); + await options.click(); + const commitAll = page.getByRole("checkbox", { name: "Commit All when Nothing Is Staged" }); + await expect(commitAll).toBeChecked(); + await commitAll.click(); + await expect(commitAll).not.toBeChecked(); + const commit = panel.getByRole("button", { name: "Commit", exact: true }); + await expect(commit).toBeDisabled(); + expect(await ipcCalls(page, "settings_set")).toContainEqual({ + scope: "global", + key: "vcs.commit.commitAllWhenNothingStaged", + value: "false", + }); + await page.keyboard.press("Escape"); + + const stageTracked = panel.getByRole("button", { name: "Stage All Tracked", exact: true }); + await stageTracked.click(); + await expect.poll(() => ipcCalls(page, "vcs_stage")).toEqual([{ paths: [tracked] }]); + await expect(commit).toBeEnabled(); + await expect(stageTracked).toBeDisabled(); + await expect(panel.getByRole("treeitem", { name: /Unversioned Files/ })).toBeVisible(); + + await page.evaluate(async () => { + const actionsModule = "/src/platform/actions.ts"; + const { executeActionOrThrow } = await import(/* @vite-ignore */ actionsModule); + await executeActionOrThrow("vcs.stageAll"); + }); + await expect.poll(() => ipcCalls(page, "vcs_stage")).toEqual([{ paths: [tracked] }, { paths: [untracked] }]); + await expect(panel.getByRole("treeitem", { name: /Unversioned Files/ })).toBeHidden(); +}); + +test("shows ignored paths on demand without including them in the staging workflow", async ({ workbench: page }) => { + await stubDesktop(page); + const root = "/dev/acme-api"; + const tracked = root + "/build.gradle.kts"; + await page.evaluate( + async ({ root, tracked }) => { + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, head: "main", headCommit: "1111111", operation: null }]; + h.vcs_branch_info = () => ({ head: "main", headCommit: "1111111", operation: null }); + h.vcs_status = () => [ + { path: tracked, relPath: "build.gradle.kts", staged: null, unstaged: "modified", renamedFrom: null }, + ]; + h.vcs_ignored_files = () => + ["cache/", "local.log"].map((relPath) => ({ + path: root + "/" + relPath.replace(/\/$/, ""), + relPath, + staged: null, + unstaged: "ignored", + renamedFrom: null, + })); + h.vcs_stage = () => null; + const projectModule = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectModule); + useProject.setState((s: { settings: Record }) => ({ + settings: { ...s.settings, vcs: { git: { stagingArea: true }, commit: { nonModal: true } } }, + })); + const vcsModule = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule); + useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); + await refreshNow(); + }, + { root, tracked }, + ); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const tree = panel.getByRole("tree", { name: "Changes" }); + const ignored = tree.getByRole("treeitem", { name: /^Ignored Files/ }); + const view = panel.getByRole("button", { name: "View Options", exact: true }); + expect(await ipcCalls(page, "vcs_ignored_files")).toEqual([]); + await expect(ignored).toBeHidden(); + await view.click(); + const showIgnored = page.getByRole("menuitemcheckbox", { name: "Show Ignored Files", exact: true }); + await showIgnored.click(); + await expect(ignored).toContainText("1 file · 1 folder"); + await ignored.click(); + await page.keyboard.press("ArrowRight"); + const log = tree.getByRole("treeitem", { name: "local.log", exact: true }); + await log.click({ button: "right" }); + const menu = page.getByRole("menu"); + await expect(menu.getByRole("menuitem", { name: "Jump to Source" })).toBeVisible(); + await expect(menu.getByRole("menuitem", { name: /Show Diff|^Stage|^Rollback/ })).toHaveCount(0); + await page.keyboard.press("Escape"); + + await page.evaluate(async (root) => { + window.__ipc.handlers.vcs_ignored_files = () => [ + { path: root + "/new.log", relPath: "new.log", staged: null, unstaged: "ignored", renamedFrom: null }, + ]; + const ipcModule = "/src/platform/ipc.ts"; + const { emitLocalIdeEvent } = await import(/* @vite-ignore */ ipcModule); + emitLocalIdeEvent({ type: "excludedDirsChanged", dirs: [root] }); + const actionsModule = "/src/platform/actions.ts"; + const { executeActionOrThrow } = await import(/* @vite-ignore */ actionsModule); + await executeActionOrThrow("vcs.stageAll"); + }, root); + await expect(tree.getByRole("treeitem", { name: "new.log", exact: true })).toBeVisible(); + await expect(log).toBeHidden(); + await expect.poll(() => ipcCalls(page, "vcs_stage")).toEqual([{ paths: [tracked] }]); + await view.click(); + await expect(showIgnored).toHaveAttribute("aria-checked", "true"); + await showIgnored.click(); + await expect(ignored).toBeHidden(); +}); + +test("Commit and Push uses the checked staging repositories", async ({ workbench: page }) => { + await stubDesktop(page); + const root = "/dev/acme-api"; + const included = root + "/application"; + const excluded = root + "/library"; + await page.evaluate( + async ({ root, included, excluded }) => { + const h = window.__ipc.handlers; + const branch = { + head: "main", + headCommit: "1111111", + upstream: null, + operation: null, + ahead: 0, + behind: 0, + }; + const committed = new Set(); + h.vcs_roots = () => [included, excluded].map((root) => ({ root, ...branch })); + h.vcs_branch_info = () => branch; + h.vcs_status = () => + [included, excluded].map((repo) => ({ + path: repo + "/changes.txt", + relPath: "changes.txt", + renamedFrom: null, + staged: committed.has(repo) ? null : "modified", + unstaged: "modified", + })); + h.vcs_config_get = () => "configured"; + h.vcs_commit = ({ repo }) => { + committed.add(String(repo)); + return "2222222"; + }; + // The commit checks read the staged and HEAD versions. + h.vcs_file_at = () => "changes\n"; + h.vcs_remotes = () => []; + h.vcs_branches = () => []; + h.vcs_log = () => []; + const projectModule = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectModule); + useProject.setState((s: { settings: Record }) => ({ + settings: { ...s.settings, vcs: { git: { stagingArea: true, showPushDialog: true } } }, + })); + const vcsModule = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule); + useVcs.setState({ available: true, root, repo: excluded, branchesLoaded: false, stashesLoaded: false }); + await refreshNow(); + }, + { root, included, excluded }, + ); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const tree = panel.getByRole("tree", { name: "Changes", exact: true }); + const application = tree.getByRole("checkbox", { name: "Include application in commit" }); + const library = tree.getByRole("checkbox", { name: "Include library in commit" }); + await expect(application).toBeChecked(); + await expect(library).toBeChecked(); + await expect(tree.getByRole("checkbox")).toHaveCount(2); + + const libraryRow = tree.getByRole("treeitem").filter({ + has: page.getByRole("checkbox", { name: "Include library in commit" }), + }); + await libraryRow.getByText("library", { exact: true }).click(); + await page.keyboard.press("Space"); + await expect(library).not.toBeChecked(); + await application.uncheck(); + await expect(panel.getByRole("button", { name: "Commit", exact: true })).toBeDisabled(); + const push = panel.getByRole("button", { name: "Commit and Push…" }); + await expect(push).toBeDisabled(); + await application.check(); + + const view = panel.getByRole("button", { name: "View Options", exact: true }); + const groupByRepo = page.getByRole("menuitemcheckbox", { name: "Repository", exact: true }); + await view.click(); + await groupByRepo.click(); + await expect(tree.getByRole("checkbox")).toHaveCount(0); + await view.click(); + await groupByRepo.click(); + await expect(application).toBeChecked(); + await expect(library).not.toBeChecked(); + + await panel.getByRole("textbox", { name: "Commit message", exact: true }).fill("Commit application only"); + await push.click(); + await expect + .poll(() => ipcCalls(page, "vcs_commit")) + .toMatchObject([{ repo: included, message: "Commit application only", options: { stage: [], exclude: [] } }]); + await expect(tree.getByRole("checkbox")).toHaveCount(0); + await expect(tree.getByRole("treeitem", { name: /Staged Changes 1 file/ })).toBeVisible(); + const dialog = page.getByRole("dialog", { name: "Push Commits", exact: true }); + await expect(dialog.getByRole("checkbox", { name: "application", exact: true })).toBeChecked(); + await expect(dialog.getByRole("checkbox", { name: "library", exact: true })).not.toBeChecked(); +}); + +test("Amend previews the original commit independently of the staged changes", async ({ workbench: page }) => { + await stubDesktop(page); + const root = "/dev/acme-api"; + const file = `${root}/changes.txt`; + await page.evaluate( + async ({ root, file }) => { + const h = window.__ipc.handlers; + const branch = { head: "main", headCommit: "11111111", operation: null, upstream: null, ahead: 0, behind: 0 }; + h.vcs_roots = () => [{ root, ...branch }]; + h.vcs_branch_info = () => branch; + h.vcs_status = () => [{ path: file, relPath: "changes.txt", staged: "modified", unstaged: null }]; + h.vcs_log = () => [ + { + id: "11111111", + shortId: "11111111", + parents: ["00000000"], + summary: "Original commit", + message: "Original commit\n\nDescription", + }, + ]; + h.vcs_commit_files = () => [{ kind: "renamed", path: "changes.txt", oldPath: "old-name.txt" }]; + h.vcs_file_at = ({ rev }) => (rev === "11111111" ? "committed contents\n" : "parent contents\n"); + h.vcs_diff_hunks = () => []; + const projectModule = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectModule); + useProject.setState((s: { settings: Record }) => ({ + settings: { ...s.settings, vcs: { git: { stagingArea: true }, diffAsEditorTab: true } }, + })); + const vcsModule = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule); + useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); + await refreshNow(); + }, + { root, file }, + ); + + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const message = panel.getByRole("textbox", { name: "Commit message" }); + const amend = panel.getByRole("checkbox", { name: "Amend", exact: true }); + const changes = panel.getByRole("tree", { name: "Changes", exact: true }); + await message.fill("Unsent draft"); + await amend.check(); + await expect(message).toHaveValue("Original commit\n\nDescription"); + await expect(changes.getByRole("treeitem", { name: /Original commit 1 file/ })).toHaveAttribute( + "aria-expanded", + "true", + ); + await expect(changes.getByRole("treeitem", { name: /Staged Changes 1 file/ })).toBeVisible(); + const original = changes.getByRole("treeitem", { name: /changes.txt.*old-name.txt/ }); + await expect(original.getByRole("checkbox")).toHaveCount(0); + await original.getByText("changes.txt", { exact: true }).click(); + await page.keyboard.press("Meta+d"); + await expect(page.getByRole("tab", { name: /00000000 ↔ 11111111/ })).toHaveAttribute("aria-selected", "true"); + await expect + .poll(() => ipcCalls(page, "vcs_file_at")) + .toEqual( + expect.arrayContaining([ + { path: `${root}/old-name.txt`, rev: "00000000" }, + { path: file, rev: "11111111" }, + ]), + ); + await expect(page.locator(".cm-content:visible").getByText("committed contents")).toBeVisible(); + await expect(await ipcCalls(page, "vcs_commit")).toHaveLength(0); + await amend.uncheck(); + await expect(changes.getByText("Original commit", { exact: true })).toHaveCount(0); + await expect(message).toHaveValue("Unsent draft"); +}); diff --git a/e2e/updateProject.spec.ts b/e2e/updateProject.spec.ts index 55648b05c..0b6516d1e 100644 --- a/e2e/updateProject.spec.ts +++ b/e2e/updateProject.spec.ts @@ -64,12 +64,11 @@ test("shows Update failures from the branch menu even when VCS notifications are const branches = page.getByRole("tree", { name: "Branches" }); await branches.getByRole("treeitem", { name: /main current/ }).click({ button: "right" }); await page.getByRole("menuitem", { name: "Update", exact: true }).click(); - const dialog = page.getByRole("dialog", { name: "Update Project", exact: true }); - await expect(dialog).toBeVisible(); - await dialog.getByRole("button", { name: "OK", exact: true }).click(); await expect(page.getByText("Update failed", { exact: true })).toBeVisible(); await expect(page.getByText(/untracked working tree files would be overwritten by merge/)).toBeVisible(); - expect(await ipcCalls(page, "vcs_remote")).toHaveLength(1); + expect(await ipcCalls(page, "vcs_remote")).toEqual([ + expect.objectContaining({ op: { op: "pull", expectedBranch: "main", rebase: false } }), + ]); }); test("Update Project wraps long tracking branches and keeps its options reachable", async ({ workbench: page }) => { @@ -82,6 +81,7 @@ test("Update Project wraps long tracking branches and keeps its options reachabl const h = window.__ipc.handlers; h.vcs_branch_info = () => branch; h.vcs_roots = () => [{ root, head, headCommit: "c1", operation: null }]; + h.vcs_project_update_plan = () => [{ root, parent: null, detachedSubmodule: false }]; h.settings_set = () => null; h.vcs_remote = () => new Promise(() => {}); const storeModule = "/src/features/vcs/store.ts"; @@ -117,7 +117,8 @@ test("Update Project wraps long tracking branches and keeps its options reachabl await dialog.getByRole("button", { name: "OK", exact: true }).click(); await expect .poll(() => ipcCalls(page, "vcs_remote")) - .toEqual([expect.objectContaining({ op: { op: "pull", rebase: true } })]); + .toEqual([expect.objectContaining({ op: { op: "updateProjectBranch", rebase: true } })]); + expect(await ipcCalls(page, "vcs_project_update_plan")).toEqual([{ roots: [] }]); expect(await ipcCalls(page, "settings_set")).toEqual( expect.arrayContaining([ expect.objectContaining({ key: "vcs.git.updateMethod", value: '"rebase"' }), diff --git a/languages/ignore.toml b/languages/ignore.toml index 2b7e3527a..d75d4b189 100644 --- a/languages/ignore.toml +++ b/languages/ignore.toml @@ -1,6 +1,6 @@ id = "ignore" name = "Ignore File" extensions = ["gitignore", "dockerignore"] -filenames = [".gitignore", ".gitignore_global", ".dockerignore", ".npmignore", ".prettierignore", ".eslintignore", ".stylelintignore", ".hgignore", ".ignore", ".rgignore", ".fdignore", ".helmignore", ".vscodeignore", ".gcloudignore", ".slugignore", ".cfignore", ".bzrignore", ".containerignore"] +filenames = [".gitignore", ".gitignore_global", ".worktreeinclude", ".dockerignore", ".npmignore", ".prettierignore", ".eslintignore", ".stylelintignore", ".hgignore", ".ignore", ".rgignore", ".fdignore", ".helmignore", ".vscodeignore", ".gcloudignore", ".slugignore", ".cfignore", ".bzrignore", ".containerignore"] line-comment = "#" indent = { tab-size = 2, insert-spaces = true } diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 4d0f93b57..8d53daf5d 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -678,6 +678,7 @@ pub fn spec(os: Os) -> Vec { act("vcs.update", "Update Project…"), act("vcs.pull", "Pull…"), act("vcs.fetch", "Fetch"), + act("vcs.unshallow", "Fetch Full History"), SEP, // Operation items (Abort Merge, Continue Rebase…) are enabled only while it is in progress. act("vcs.merge", "Merge…"), @@ -713,6 +714,7 @@ pub fn spec(os: Os) -> Vec { act("vcs.shelve", "Shelve Changes…"), act("vcs.showShelf", "Show Shelf"), act("vcs.stash", "Stash Changes…"), + act("vcs.showStashes", "Show Stash"), act("vcs.unstash", "Unstash Changes…"), act("vcs.rollback", "Rollback…"), ], @@ -2451,6 +2453,7 @@ mod tests { "vcs.update", "vcs.pull", "vcs.fetch", + "vcs.unshallow", "|", "vcs.merge", "vcs.merge.abort", diff --git a/src-tauri/src/remote_dev.rs b/src-tauri/src/remote_dev.rs index 1351a2adb..105a84e5d 100644 --- a/src-tauri/src/remote_dev.rs +++ b/src-tauri/src/remote_dev.rs @@ -1117,14 +1117,16 @@ pub async fn remote_invoke( .get(&label) .ok_or_else(|| IdeError::unavailable("this window is not connected to a remote host"))?; let batch_execution = cmd == "db_execute_stream"; - let mut batch_channel = None; + let mut finite_channel = None; if let Value::Object(map) = &mut args { for (name, v) in map { if let Some(id) = v.get("$channel").and_then(Value::as_u64) { let own = c.next_channel.fetch_add(1, std::sync::atomic::Ordering::Relaxed); c.channels.lock().insert(own, (on_channel.clone(), id)); - if batch_execution && name == "onProgress" { - batch_channel = Some(own); + if (batch_execution && name == "onProgress") + || (cmd == "vcs_watch_commit_messages" && name == "onMessages") + { + finite_channel = Some(own); } *v = serde_json::json!({ "$channel": own }); } @@ -1150,8 +1152,8 @@ pub async fn remote_invoke( let web_url = cmd == "web_url"; let call = Invoke { window: label, cmd, args }; let reply = invoke_reply(&c.peer, call, std::time::Duration::from_secs(30)).await; - // The batch's notifications precede its reply. Other commands can keep streaming later. - if let Some(id) = batch_channel { + // These commands finish streaming before their reply. Other commands may retain their channels. + if let Some(id) = finite_channel { c.channels.lock().remove(&id); } let mut result = reply.map_err(|e| { diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rs index 26ddafd3d..5630fb682 100644 --- a/src-tauri/src/windows.rs +++ b/src-tauri/src/windows.rs @@ -178,10 +178,26 @@ pub struct DiffLaunch { /// Absolute path of the file (the right side's path). pub path: String, pub left: DiffSide, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub middle: Option, pub right: DiffSide, - /// 0-based line of the right side to reveal. + /// 0-based line to reveal. #[serde(default, skip_serializing_if = "Option::is_none")] pub line: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub line_side: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub col: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub chain: Option>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum DiffLineSide { + Left, + Middle, + Right, } /// The two files of a command-line diff (`openidea diff a.txt b.txt`), both sides editable. @@ -1820,7 +1836,7 @@ pub fn open_comparison_window( fn diff_window_id(diff: &DiffLaunch) -> u64 { use std::hash::{DefaultHasher, Hash, Hasher}; let mut hasher = DefaultHasher::new(); - (&diff.path, &diff.left, &diff.right).hash(&mut hasher); + (&diff.path, &diff.left, &diff.middle, &diff.right).hash(&mut hasher); hasher.finish() } @@ -2222,12 +2238,19 @@ mod tests { let mut diff = DiffLaunch { path: "/p/a.txt".into(), left: DiffSide::Rev { rev: "HEAD".into(), path: None, label: None }, + middle: None, right: DiffSide::Worktree { label: None, label_detail: None }, line: None, + line_side: None, + col: None, + chain: None, }; let id = diff_window_id(&diff); diff.line = Some(12); assert_eq!(diff_window_id(&diff), id); + diff.middle = Some(DiffSide::Rev { rev: ":0".into(), path: None, label: None }); + assert_ne!(diff_window_id(&diff), id); + diff.middle = None; diff.right = DiffSide::Rev { rev: ":0".into(), path: None, label: None }; assert_ne!(diff_window_id(&diff), id); diff.path = "/p/b.txt".into(); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index c2927ab50..93829ce06 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -355,6 +355,7 @@ lsp_execute_command trusted project_host bin lsp_extract_interface trusted project_host bindings async lsp_extract_interface_info trusted project_host bindings async lsp_format trusted project_host bindings async +lsp_format_text trusted project_host bindings async lsp_goto trusted project_host bindings async lsp_goto_implementation trusted project_host bindings async lsp_hierarchy_members trusted project_host bindings async @@ -384,6 +385,8 @@ lsp_semantic_tokens trusted project_host bin lsp_servers always project_host bindings sync lsp_signature_help trusted project_host bindings async lsp_signature_info trusted project_host bindings async +lsp_snapshot_diagnostics trusted project_host bindings async +lsp_source_action_text trusted project_host bindings async lsp_type_hierarchy trusted project_host bindings async lsp_virtual_document trusted project_host bindings async lsp_workspace_symbols trusted project_host bindings async @@ -649,31 +652,45 @@ tools_uninstall outside_restricted project_host bin tools_updates outside_restricted project_host bindings async undo_workspace_edit always project_host bindings async user_font_data always desktop - async +vcs_accept_conflict_side trusted project_host bindings async vcs_add_to_ignore trusted project_host bindings async vcs_add_worktree trusted project_host bindings async +vcs_apply_mapped_patch trusted project_host bindings async vcs_apply_patch trusted project_host bindings async +vcs_apply_project_patch trusted project_host bindings async vcs_blame always project_host bindings async vcs_block_history always project_host bindings async vcs_branch_info always project_host bindings async vcs_branches always project_host bindings async vcs_changelists_load always project_host bindings async vcs_changelists_save trusted project_host bindings sync +vcs_check_incoming trusted project_host bindings async vcs_checkout trusted project_host bindings async +vcs_checkout_affected_files trusted project_host bindings async vcs_clone always project_host bindings async vcs_commit trusted project_host bindings async +vcs_commit_crlf_paths trusted project_host bindings async vcs_commit_files always project_host bindings async +vcs_commit_large_files trusted project_host bindings async +vcs_commit_push_target always project_host bindings async +vcs_commit_selection_changes always project_host bindings async vcs_commits_changes always project_host bindings async vcs_compare_paths always project_host bindings async vcs_compare_scope always project_host bindings async vcs_config_get always project_host bindings async +vcs_config_get_bool always project_host bindings async vcs_conflict_versions always project_host bindings async vcs_create_branch trusted project_host bindings async vcs_create_patch trusted project_host bindings async vcs_create_tag trusted project_host bindings async +vcs_default_push_target always project_host bindings async vcs_delete_branch trusted project_host bindings async +vcs_delete_merged_branch trusted project_host bindings async vcs_delete_tag trusted project_host bindings async +vcs_delete_tracking_branch trusted project_host bindings async vcs_detected_git always project_host bindings sync vcs_detected_roots always project_host bindings async +vcs_diff_entries always project_host bindings async vcs_diff_hunks always project_host bindings async vcs_diff_numstat always project_host bindings async vcs_diff_revisions always project_host bindings async @@ -681,12 +698,22 @@ vcs_diff_text always project_host bin vcs_diff_with_worktree always project_host bindings async vcs_discard trusted project_host bindings async vcs_edit_remote trusted project_host bindings async +vcs_edit_signing trusted project_host bindings async +vcs_extract_commit_changes trusted project_host bindings async vcs_file_at always project_host bindings async vcs_file_mode trusted project_host bindings async +vcs_finish_shelf_batch trusted project_host bindings async +vcs_format_apply_commit trusted project_host bindings async vcs_git_version trusted project_host bindings async +vcs_gpg_signing_keys trusted project_host bindings async +vcs_has_commit always project_host bindings async vcs_has_hook always project_host bindings async vcs_ignore_blame_revision trusted project_host bindings async +vcs_ignored_files always project_host bindings async vcs_init always project_host bindings async +vcs_inspect_push trusted project_host bindings async +vcs_invalidate_log_signatures always project_host bindings async +vcs_keep_amend_commit trusted project_host bindings async vcs_line_hunks always project_host bindings async vcs_log always project_host bindings async vcs_log_details always project_host bindings async @@ -694,15 +721,25 @@ vcs_log_details_batch always project_host bin vcs_log_refs always project_host bindings async vcs_log_users always project_host bindings async vcs_merge trusted project_host bindings async +vcs_merge_affected_files trusted project_host bindings async vcs_merge_base always project_host bindings async vcs_merge_with trusted project_host bindings async vcs_move_worktree trusted project_host bindings async +vcs_not_cherry_picked always project_host bindings async vcs_open_external_log always project_host bindings async vcs_operation trusted project_host bindings async +vcs_patch_file_diff trusted project_host bindings async vcs_patch_preview trusted project_host bindings async vcs_pending_patch trusted project_host bindings async +vcs_preview_partial_commit trusted project_host bindings async +vcs_project_update_plan always project_host bindings async +vcs_prune_worktrees trusted project_host bindings async +vcs_push_target_choices always project_host bindings async +vcs_read_patch always project_host bindings async vcs_rebase trusted project_host bindings async +vcs_rebase_editor_reply trusted project_host bindings sync vcs_rebase_with trusted project_host bindings async +vcs_rebase_with_editor trusted project_host bindings async vcs_remote trusted project_host bindings async vcs_remotes always project_host bindings async vcs_remove_worktree trusted project_host bindings async @@ -710,11 +747,17 @@ vcs_rename_branch trusted project_host bin vcs_restore_branch trusted project_host bindings async vcs_restore_head trusted project_host bindings async vcs_restore_tag trusted project_host bindings async +vcs_restore_unstaged trusted project_host bindings async +vcs_revert_resolved trusted project_host bindings async +vcs_review_apply_commit always project_host bindings async vcs_revision_children always project_host bindings async vcs_revision_files always project_host bindings async vcs_reword trusted project_host bindings async -vcs_roots always project_host bindings sync +vcs_rollback_submodules trusted project_host bindings async +vcs_roots always project_host bindings async +vcs_save_staged_text trusted project_host bindings async vcs_set_user_identity trusted project_host bindings async +vcs_set_worktree_locked trusted project_host bindings async vcs_shelf_delete trusted project_host bindings async vcs_shelf_diff trusted project_host bindings async vcs_shelf_import trusted project_host bindings async @@ -722,20 +765,29 @@ vcs_shelf_patch always project_host bin vcs_shelf_rename trusted project_host bindings async vcs_shelve trusted project_host bindings async vcs_shelves always project_host bindings async +vcs_signing_config always project_host bindings async vcs_stage trusted project_host bindings async +vcs_stage_formatted_text trusted project_host bindings async vcs_stage_hunks trusted project_host bindings async vcs_stage_patch trusted project_host bindings async +vcs_stage_without_content trusted project_host bindings async +vcs_staged_text trusted project_host bindings async +vcs_staging_line_hunks always project_host bindings async vcs_stash_apply trusted project_host bindings async +vcs_stash_clear trusted project_host bindings async vcs_stash_drop trusted project_host bindings async vcs_stash_push trusted project_host bindings async vcs_stashes always project_host bindings async vcs_status always project_host bindings async vcs_status_paths always project_host bindings async vcs_tags always project_host bindings async +vcs_undo_branch_creation trusted project_host bindings async vcs_undo_commit trusted project_host bindings async vcs_unshelve trusted project_host bindings async vcs_unstage trusted project_host bindings async vcs_update_branches trusted project_host bindings async +vcs_watch_commit_messages always project_host bindings async +vcs_worktree_include always project_host bindings async vcs_worktrees always project_host bindings async vcs_write_patch always project_host bindings async web_browsers always desktop bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 90a612430..4e213b7ff 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -865,6 +865,7 @@ export const commands = { start: Pos, end: Pos, } | null, options: FormatOptions) => typedError(__TAURI_INVOKE("lsp_format", { doc, range, options })), + lspFormatText: (path: string, text: string, options: FormatOptions) => typedError(__TAURI_INVOKE("lsp_format_text", { path, text, options })), lspGoto: (doc: DocId, pos: Pos, kind: GotoKind) => typedError(__TAURI_INVOKE("lsp_goto", { doc, pos, kind })), /** * Go to Implementation of the symbol at `pos`. Implementations found before a @@ -973,6 +974,8 @@ export const commands = { activeParameter: number, } | null, IdeError>(__TAURI_INVOKE("lsp_signature_help", { doc, pos })), lspSignatureInfo: (request: RequestId, doc: DocId, pos: Pos) => typedError(__TAURI_INVOKE("lsp_signature_info", { request, doc, pos })), + lspSnapshotDiagnostics: (path: string, text: string, request: RequestId) => typedError(__TAURI_INVOKE("lsp_snapshot_diagnostics", { path, text, request })), + lspSourceActionText: (path: string, text: string, kind: string, request: RequestId) => typedError(__TAURI_INVOKE("lsp_source_action_text", { path, text, kind, request })), lspTypeHierarchy: (doc: DocId, pos: Pos, direction: HierarchyDirection) => typedError(__TAURI_INVOKE("lsp_type_hierarchy", { doc, pos, direction })), /** * Contents of a read-only language-server document, including JDT library @@ -1116,7 +1119,7 @@ export const commands = { * A window's answer to a plugin's `commitRequested`; false when the call no * longer waits. */ - pluginAnswerCommit: (requestId: string, answer: CommitAnswer) => __TAURI_INVOKE("plugin_answer_commit", { requestId, answer }), + pluginAnswerCommit: (requestId: string, answer: CommitAnswer_Deserialize) => __TAURI_INVOKE("plugin_answer_commit", { requestId, answer }), /** * Reports the user's answer to a plugin's `promptRequested`: the chosen keys * (pick), `[text]` (input), anything (confirm: OK), or `None` when dismissed. @@ -1139,7 +1142,7 @@ export const commands = { * Runs plugins' before-commit checks on what `selection` commits, until * `request` is cancelled. */ - pluginCommitChecks: (selection: CommitSelection, checks: PluginCommitCheckRef[], request: RequestId) => typedError(__TAURI_INVOKE("plugin_commit_checks", { selection, checks, request })), + pluginCommitChecks: (selection: CommitSelection_Deserialize, checks: PluginCommitCheckRef[], request: RequestId) => typedError(__TAURI_INVOKE("plugin_commit_checks", { selection, checks, request })), /** Every plugin's console highlight rules (later changes arrive as `consoleRulesChanged`). */ pluginConsoleRules: () => __TAURI_INVOKE<{ [key in string]: ConsoleRule[] }>("plugin_console_rules"), /** Dispatches a wasm content editor action through the owning plugin's event handler. */ @@ -1816,49 +1819,79 @@ export const commands = { */ toolsUpdates: (request: RequestId) => typedError(__TAURI_INVOKE("tools_updates", { request })), undoWorkspaceEdit: (id: number) => typedError(__TAURI_INVOKE("undo_workspace_edit", { id })), + vcsAcceptConflictSide: (paths: string[], side: ConflictSide) => typedError(__TAURI_INVOKE("vcs_accept_conflict_side", { paths, side })), vcsAddToIgnore: (paths: string[], destination: IgnoreDestination) => typedError(__TAURI_INVOKE("vcs_add_to_ignore", { paths, destination })), - vcsAddWorktree: (repo: string | null, path: string, commitish: string, newBranch: string | null) => typedError(__TAURI_INVOKE("vcs_add_worktree", { repo, path, commitish, newBranch })), - vcsApplyPatch: (repo: string | null, patch: string) => typedError(__TAURI_INVOKE("vcs_apply_patch", { repo, patch })), - vcsBlame: (path: string, text: string | null, revision: string | null) => typedError(__TAURI_INVOKE("vcs_blame", { path, text, revision })), + vcsAddWorktree: (repo: string | null, path: string, commitish: string, newBranch: string | null, copyConfig: boolean | null, setup: { + script: string, + request: RequestId, +} | null) => typedError(__TAURI_INVOKE("vcs_add_worktree", { repo, path, commitish, newBranch, copyConfig, setup })), + vcsApplyMappedPatch: (repo: string | null, base: string | null, patch: string, paths: string[] | null, mappings: PatchPathMapping[]) => typedError(__TAURI_INVOKE("vcs_apply_mapped_patch", { repo, base, patch, paths, mappings })), + vcsApplyPatch: (repo: string | null, patch: string, paths: string[] | null) => typedError(__TAURI_INVOKE("vcs_apply_patch", { repo, patch, paths })), + vcsApplyProjectPatch: (base: string, patch: string, paths: string[] | null) => typedError(__TAURI_INVOKE("vcs_apply_project_patch", { base, patch, paths })), + vcsBlame: (path: string, text: string | null, revision: string | null) => typedError(__TAURI_INVOKE("vcs_blame", { path, text, revision })), /** * History for Selection: commits that changed `lines` (0-based, inclusive) of `path`'s * editor text. Cancellable with `cancel_request(request)`. */ vcsBlockHistory: (request: RequestId, path: string, text: string | null, lines: [number, number]) => typedError(__TAURI_INVOKE("vcs_block_history", { request, path, text, lines })), - vcsBranchInfo: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_branch_info", { repo })), + vcsBranchInfo: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_branch_info", { repo })), vcsBranches: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_branches", { repo })), vcsChangelistsLoad: () => typedError(__TAURI_INVOKE("vcs_changelists_load")), vcsChangelistsSave: (changelists: ChangelistState) => typedError(__TAURI_INVOKE("vcs_changelists_save", { changelists })), + vcsCheckIncoming: (repo: string, request: RequestId) => typedError(__TAURI_INVOKE("vcs_check_incoming", { repo, request })), vcsCheckout: (repo: string | null, branch: string, create: boolean, options: { mode?: CheckoutMode, /** Required when checking out a remote branch whose local namesake is ahead of it. */ diverged?: DivergedLocal | null, /** Check the branch out even though another worktree has it checked out. */ ignoreOtherWorktrees?: boolean, -} | null) => typedError(__TAURI_INVOKE("vcs_checkout", { repo, branch, create, options })), +} | null, shelfBatch: string | null) => typedError(__TAURI_INVOKE("vcs_checkout", { repo, branch, create, options, shelfBatch })), + vcsCheckoutAffectedFiles: (repositories: IpcPath[], branch: string) => typedError<([IpcPath, string[]])[], IdeError>(__TAURI_INVOKE("vcs_checkout_affected_files", { repositories, branch })), /** Clones a repository (Get from VCS). Works without an open project. */ vcsClone: (request: RequestId, url: string, dest: string, depth: number | null, onOutput: Channel) => typedError(__TAURI_INVOKE("vcs_clone", { request, url, dest, depth, onOutput })), - vcsCommit: (repo: string | null, message: string, options: CommitOptions) => typedError(__TAURI_INVOKE("vcs_commit", { repo, message, options })), + vcsCommit: (repo: string | null, message: string, options: CommitOptions_Deserialize) => typedError(__TAURI_INVOKE("vcs_commit", { repo, message, options })), + vcsCommitCrlfPaths: (repo: string, paths: string[], options: CommitOptions_Deserialize, request: RequestId) => typedError(__TAURI_INVOKE("vcs_commit_crlf_paths", { repo, paths, options, request })), vcsCommitFiles: (repo: string | null, commit: string) => typedError(__TAURI_INVOKE("vcs_commit_files", { repo, commit })), + vcsCommitLargeFiles: (repo: string, paths: string[], options: CommitOptions_Deserialize, limit: number, request: RequestId) => typedError(__TAURI_INVOKE("vcs_commit_large_files", { repo, paths, options, limit, request })), + /** Chooses the source branch and configured destination for a single Git Log commit. */ + vcsCommitPushTarget: (repo: string | null, request: RequestId, revision: string) => typedError(__TAURI_INVOKE("vcs_commit_push_target", { repo, request, revision })), + vcsCommitSelectionChanges: (repo: string | null, commits: string[], request: RequestId) => typedError(__TAURI_INVOKE("vcs_commit_selection_changes", { repo, commits, request })), /** Combined changes of several commits, `commits` oldest first. */ vcsCommitsChanges: (repo: string | null, commits: string[]) => typedError(__TAURI_INVOKE("vcs_commits_changes", { repo, commits })), vcsComparePaths: (paths: string[], revision: string, repositories: string[] | null, request: RequestId) => typedError(__TAURI_INVOKE("vcs_compare_paths", { paths, revision, repositories, request })), vcsCompareScope: (paths: string[]) => typedError(__TAURI_INVOKE("vcs_compare_scope", { paths })), /** `git config --get ` in the project repository; `None` when unset. */ vcsConfigGet: (repo: string | null, key: string) => typedError(__TAURI_INVOKE("vcs_config_get", { repo, key })), + vcsConfigGetBool: (repo: string | null, key: string) => typedError(__TAURI_INVOKE("vcs_config_get_bool", { repo, key })), /** The user's side is `ours` (sides swapped during a rebase, as in IDEA). */ vcsConflictVersions: (path: string) => typedError(__TAURI_INVOKE("vcs_conflict_versions", { path })), /** New Branch: creates `name` at `start` (HEAD when absent), optionally checking it out. */ - vcsCreateBranch: (repo: string | null, name: string, start: string | null, checkout: boolean, overwrite: boolean | null) => typedError(__TAURI_INVOKE("vcs_create_branch", { repo, name, start, checkout, overwrite })), - vcsCreatePatch: (repo: string | null, source: PatchSource) => typedError(__TAURI_INVOKE("vcs_create_patch", { repo, source })), + vcsCreateBranch: (repo: string | null, name: string, start: string | null, checkout: boolean, overwrite: boolean | null, expectedTip: string | null, options: { + mode?: CheckoutMode, + /** Required when checking out a remote branch whose local namesake is ahead of it. */ + diverged?: DivergedLocal | null, + /** Check the branch out even though another worktree has it checked out. */ + ignoreOtherWorktrees?: boolean, +} | null, shelfBatch: string | null) => typedError(__TAURI_INVOKE("vcs_create_branch", { repo, name, start, checkout, overwrite, expectedTip, options, shelfBatch })), + vcsCreatePatch: (repo: string | null, source: PatchSource, base: string | null) => typedError(__TAURI_INVOKE("vcs_create_patch", { repo, source, base })), vcsCreateTag: (repo: string | null, name: string, commit: string, message: string | null, force: boolean) => typedError(__TAURI_INVOKE("vcs_create_tag", { repo, name, commit, message, force })), - vcsDeleteBranch: (repo: string | null, branch: string) => typedError(__TAURI_INVOKE("vcs_delete_branch", { repo, branch })), + /** Chooses the destination of a local branch or the current HEAD. */ + vcsDefaultPushTarget: (repo: string | null, branch: string | null) => typedError<{ + selection: PushSelection, + setUpstream: boolean, +} | null, IdeError>(__TAURI_INVOKE("vcs_default_push_target", { repo, branch })), + vcsDeleteBranch: (repo: string | null, branch: string) => typedError(__TAURI_INVOKE("vcs_delete_branch", { repo, branch })), + /** Deletes a branch offered for cleanup by a successful merge. */ + vcsDeleteMergedBranch: (repo: string, branch: string, expectedTip: string) => typedError(__TAURI_INVOKE("vcs_delete_merged_branch", { repo, branch, expectedTip })), /** Tag › Delete: the result is what "Restore" needs. */ vcsDeleteTag: (repo: string | null, name: string) => typedError(__TAURI_INVOKE("vcs_delete_tag", { repo, name })), + /** Deletes a local tracking branch the user selected along with its remote branch. */ + vcsDeleteTrackingBranch: (repo: string | null, branch: string, expectedTip: string, expectedUpstream: string) => typedError(__TAURI_INVOKE("vcs_delete_tracking_branch", { repo, branch, expectedTip, expectedUpstream })), /** The auto-detected git executable (shown as the field's placeholder). */ vcsDetectedGit: () => __TAURI_INVOKE("vcs_detected_git"), /** Directory Mappings: the repository roots detection finds, before any are excluded or added. */ vcsDetectedRoots: () => typedError(__TAURI_INVOKE("vcs_detected_roots")), + vcsDiffEntries: (entries: DiffEntryRequest[]) => typedError<(DiffEntry | null)[], IdeError>(__TAURI_INVOKE("vcs_diff_entries", { entries })), /** Line hunks between two arbitrary texts (diff viewer, commit dialog). */ vcsDiffHunks: (oldText: string, newText: string) => __TAURI_INVOKE("vcs_diff_hunks", { oldText, newText }), /** @@ -1873,25 +1906,42 @@ export const commands = { vcsDiffWithWorktree: (repo: string | null, rev: string) => typedError(__TAURI_INVOKE("vcs_diff_with_worktree", { repo, rev })), vcsDiscard: (paths: string[]) => typedError(__TAURI_INVOKE("vcs_discard", { paths })), vcsEditRemote: (repo: string | null, edit: RemoteEdit) => typedError(__TAURI_INVOKE("vcs_edit_remote", { repo, edit })), + /** Updates the selected repository's Git config. */ + vcsEditSigning: (repo: string, edit: GitSigningEdit) => typedError(__TAURI_INVOKE("vcs_edit_signing", { repo, edit })), + vcsExtractCommitChanges: (repo: string | null, commit: string, expectedHead: HistoryTip, paths: string[], message: string) => typedError(__TAURI_INVOKE("vcs_extract_commit_changes", { repo, commit, expectedHead, paths, message })), vcsFileAt: (path: string, rev: string | null) => typedError(__TAURI_INVOKE("vcs_file_at", { path, rev })), /** * The file's git mode at `rev` (`100644`, `100755`, `120000`…), `"WT"` for the * worktree; `None` when absent there. Lets the diff viewer report a mode-only change. */ vcsFileMode: (path: string, rev: string | null) => typedError(__TAURI_INVOKE("vcs_file_mode", { path, rev })), + /** Restores the batch's ready repositories. A repository with an operation in progress keeps its Shelf. */ + vcsFinishShelfBatch: (batch: string, repositories: (string | null)[]) => typedError(__TAURI_INVOKE("vcs_finish_shelf_batch", { batch, repositories })), + vcsFormatApplyCommit: (repo: string | null, checkpoint: string, edits: StagedTextEdit[], request: RequestId) => typedError(__TAURI_INVOKE("vcs_format_apply_commit", { repo, checkpoint, edits, request })), /** * Settings › Git › Test: runs `git --version` on `path`, or on the auto-detected * executable when `path` is empty. */ vcsGitVersion: (path: string) => typedError(__TAURI_INVOKE("vcs_git_version", { path })), + /** Lists OpenPGP key metadata using the signer Git uses for this repository. */ + vcsGpgSigningKeys: (repo: string, request: RequestId) => typedError(__TAURI_INVOKE("vcs_gpg_signing_keys", { repo, request })), + /** Whether a revision resolves to an existing Git commit. */ + vcsHasCommit: (repo: string | null, revision: string) => typedError(__TAURI_INVOKE("vcs_has_commit", { repo, revision })), /** Whether the repository has the executable Git hook `name` (Push dialog › Run Git hooks). */ vcsHasHook: (repo: string | null, name: string) => typedError(__TAURI_INVOKE("vcs_has_hook", { repo, name })), vcsIgnoreBlameRevision: (path: string, commit: string) => typedError(__TAURI_INVOKE("vcs_ignore_blame_revision", { path, commit })), + vcsIgnoredFiles: () => typedError(__TAURI_INVOKE("vcs_ignored_files")), /** * `git init` in `dir` (VCS › Create Git Repository…): with the git of the window's project when * it is trusted, the default one in a window without a project. */ vcsInit: (dir: string) => typedError(__TAURI_INVOKE("vcs_init", { dir })), + /** Reads the selected push target without prompting for remote credentials. */ + vcsInspectPush: (repo: string | null, request: RequestId, selection: PushSelection, live: boolean) => typedError(__TAURI_INVOKE("vcs_inspect_push", { repo, request, selection, live })), + /** Clears cached verification results before refreshing the Git Log. */ + vcsInvalidateLogSignatures: (repo: string) => typedError(__TAURI_INVOKE("vcs_invalidate_log_signatures", { repo })), + /** Keeps the prepared amend commit after a conflicting history replay. */ + vcsKeepAmendCommit: (repo: string, commit: string) => typedError(__TAURI_INVOKE("vcs_keep_amend_commit", { repo, commit })), /** Gutter change markers for a file, computed against its current (unsaved) text. */ vcsLineHunks: (path: string) => typedError(__TAURI_INVOKE("vcs_line_hunks", { path })), vcsLog: (repo: string | null, query: LogQuery) => typedError(__TAURI_INVOKE("vcs_log", { repo, query })), @@ -1899,34 +1949,68 @@ export const commands = { vcsLogDetailsBatch: (repo: string | null, revisions: string[], request: RequestId) => typedError(__TAURI_INVOKE("vcs_log_details_batch", { repo, revisions, request })), vcsLogRefs: (repo: string | null) => typedError<{ [key in string]: string }, IdeError>(__TAURI_INVOKE("vcs_log_refs", { repo })), vcsLogUsers: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_log_users", { repo })), - vcsMerge: (repo: string | null, branch: string) => typedError(__TAURI_INVOKE("vcs_merge", { repo, branch })), + vcsMerge: (repo: string | null, branch: string, shelfBatch: string | null, smart: boolean) => typedError(__TAURI_INVOKE("vcs_merge", { repo, branch, shelfBatch, smart })), + vcsMergeAffectedFiles: (repositories: IpcPath[], branch: string) => typedError<([IpcPath, string[]])[], IdeError>(__TAURI_INVOKE("vcs_merge_affected_files", { repositories, branch })), /** The best common ancestor of `a` and `b` (`git merge-base`), if any. */ vcsMergeBase: (repo: string | null, a: string, b: string) => typedError(__TAURI_INVOKE("vcs_merge_base", { repo, a, b })), /** Merge dialog: merges `branches` into the current branch. */ - vcsMergeWith: (repo: string | null, branches: string[], options: MergeOptions) => typedError(__TAURI_INVOKE("vcs_merge_with", { repo, branches, options })), + vcsMergeWith: (repo: string | null, branches: string[], options: MergeOptions) => typedError(__TAURI_INVOKE("vcs_merge_with", { repo, branches, options })), vcsMoveWorktree: (repo: string | null, path: string, to: string) => typedError(__TAURI_INVOKE("vcs_move_worktree", { repo, path, to })), + vcsNotCherryPicked: (repo: string | null, source: string, target: string, request: RequestId) => typedError(__TAURI_INVOKE("vcs_not_cherry_picked", { repo, source, target, request })), vcsOpenExternalLog: (path: string) => typedError(__TAURI_INVOKE("vcs_open_external_log", { path })), /** * Local history operation that may take a while (hooks, large checkouts); git's * output streams through `on_output`. Cancellable. */ - vcsOperation: (repo: string | null, request: RequestId, op: GitOperation, onOutput: Channel) => typedError(__TAURI_INVOKE("vcs_operation", { repo, request, op, onOutput })), - vcsPatchPreview: (repo: string | null, patch: string) => typedError(__TAURI_INVOKE("vcs_patch_preview", { repo, patch })), - vcsPendingPatch: (repo: string | null, options: CommitOptions) => typedError(__TAURI_INVOKE("vcs_pending_patch", { repo, options })), - vcsRebase: (repo: string | null, onto: string) => typedError(__TAURI_INVOKE("vcs_rebase", { repo, onto })), - /** Rebase dialog: rebases the current branch onto `upstream` (or `--onto`). */ - vcsRebaseWith: (repo: string | null, upstream: string, options: RebaseOptions) => typedError(__TAURI_INVOKE("vcs_rebase_with", { repo, upstream, options })), + vcsOperation: (repo: string | null, request: RequestId, op: GitOperation_Deserialize, onOutput: Channel) => typedError(__TAURI_INVOKE("vcs_operation", { repo, request, op, onOutput })), + vcsPatchFileDiff: (repo: string | null, base: string | null, patch: string, path: string, mappings: PatchPathMapping[] | null) => typedError(__TAURI_INVOKE("vcs_patch_file_diff", { repo, base, patch, path, mappings })), + vcsPatchPreview: (repo: string | null, patch: string, target: "project" | "repository" | null, mappings: PatchPathMapping[] | null) => typedError(__TAURI_INVOKE("vcs_patch_preview", { repo, patch, target, mappings })), + vcsPendingPatch: (repo: string | null, options: CommitOptions_Deserialize) => typedError(__TAURI_INVOKE("vcs_pending_patch", { repo, options })), + vcsPreviewPartialCommit: (file: PartialCommitFile_Deserialize) => typedError(__TAURI_INVOKE("vcs_preview_partial_commit", { file })), /** Network operation; progress lines stream through `on_output`. Cancellable. */ - vcsRemote: (repo: string | null, request: RequestId, op: RemoteOp, onOutput: Channel) => typedError(__TAURI_INVOKE("vcs_remote", { repo, request, op, onOutput })), + vcsProjectUpdatePlan: (roots: (string | null)[]) => typedError(__TAURI_INVOKE("vcs_project_update_plan", { roots })), + vcsPruneWorktrees: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_prune_worktrees", { repo })), + /** Resolves the push source and the configured destination for each remote. */ + vcsPushTargetChoices: (repo: string | null, request: RequestId, branch: string | null, revision: string | null) => typedError(__TAURI_INVOKE("vcs_push_target_choices", { repo, request, branch, revision })), + /** Reads a patch without normalizing its hunk line endings. */ + vcsReadPatch: (path: string) => typedError(__TAURI_INVOKE("vcs_read_patch", { path })), + vcsRebase: (repo: string | null, onto: string, shelfBatch: string | null) => typedError(__TAURI_INVOKE("vcs_rebase", { repo, onto, shelfBatch })), + vcsRebaseEditorReply: (request: RequestId, index: number, reply: { + text: string, + rewords?: { [key in string]: string }, +} | null) => typedError(__TAURI_INVOKE("vcs_rebase_editor_reply", { request, index, reply })), + /** Rebase dialog: rebases a branch onto an upstream, or replays it from the root. */ + vcsRebaseWith: (repo: string | null, upstream: string | null, options: RebaseOptions) => typedError(__TAURI_INVOKE("vcs_rebase_with", { repo, upstream, options })), + vcsRebaseWithEditor: (repo: string | null, operation: RebaseEditorOperation, request: RequestId, onOutput: Channel, onEdit: Channel, expectedRebase: { + original: HistoryTip, + onto: string, +} | null) => typedError<{ + branch: string | null, + commit: string, +} | null, IdeError>(__TAURI_INVOKE("vcs_rebase_with_editor", { repo, operation, request, onOutput, onEdit, expectedRebase })), + vcsRemote: (repo: string | null, request: RequestId, op: RemoteOp, onOutput: Channel, shelfBatch: string | null) => typedError(__TAURI_INVOKE("vcs_remote", { repo, request, op, onOutput, shelfBatch })), vcsRemotes: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_remotes", { repo })), vcsRemoveWorktree: (repo: string | null, path: string, force: boolean) => typedError(__TAURI_INVOKE("vcs_remove_worktree", { repo, path, force })), vcsRenameBranch: (repo: string | null, from: string, to: string, unsetUpstream: boolean) => typedError(__TAURI_INVOKE("vcs_rename_branch", { repo, from, to, unsetUpstream })), /** "Restore" of the branch-deleted notification. */ - vcsRestoreBranch: (repo: string | null, deleted: DeletedBranch) => typedError(__TAURI_INVOKE("vcs_restore_branch", { repo, deleted })), + vcsRestoreBranch: (repo: string | null, deleted: DeletedBranch_Deserialize) => typedError(__TAURI_INVOKE("vcs_restore_branch", { repo, deleted })), /** Undo of a history rewrite (Edit Commit Message, Drop, Squash). */ - vcsRestoreHead: (repo: string | null, before: string, after: string) => typedError(__TAURI_INVOKE("vcs_restore_head", { repo, before, after })), + vcsRestoreHead: (repo: string | null, before: string, after: string, branch: string | null, checkout: { + branch: string | null, + commit: string, +} | null) => typedError(__TAURI_INVOKE("vcs_restore_head", { repo, before, after, branch, checkout })), /** "Restore" of the tag-deleted notification. */ vcsRestoreTag: (repo: string | null, deleted: DeletedTag) => typedError(__TAURI_INVOKE("vcs_restore_tag", { repo, deleted })), + vcsRestoreUnstaged: (paths: string[]) => typedError(__TAURI_INVOKE("vcs_restore_unstaged", { paths })), + vcsRevertResolved: (paths: string[]) => typedError(__TAURI_INVOKE("vcs_revert_resolved", { paths })), + vcsReviewApplyCommit: (repo: string | null, request: RequestId) => typedError<{ + kind: CommitApplyKind, + checkpoint: string, + message: string, + paths: IpcPath[], + author?: string | null, + authorDate?: string | null, +} | null, IdeError>(__TAURI_INVOKE("vcs_review_apply_commit", { repo, request })), vcsRevisionChildren: (repo: string | null, revision: string, directory: string) => typedError(__TAURI_INVOKE("vcs_revision_children", { repo, revision, directory })), vcsRevisionFiles: (repo: string | null, revision: string) => typedError(__TAURI_INVOKE("vcs_revision_files", { repo, revision })), /** @@ -1934,37 +2018,58 @@ export const commands = { * working tree. */ vcsReword: (repo: string | null, commit: string, message: string) => typedError(__TAURI_INVOKE("vcs_reword", { repo, commit, message })), + vcsRollbackSubmodules: (paths: string[], source: SubmoduleRollbackSource, restoreCheckout: boolean) => typedError(__TAURI_INVOKE("vcs_rollback_submodules", { paths, source, restoreCheckout })), /** The project's repositories, the primary one first. */ vcsRoots: () => typedError(__TAURI_INVOKE("vcs_roots")), + vcsSaveStagedText: (path: string, version: string, text: string) => typedError(__TAURI_INVOKE("vcs_save_staged_text", { path, version, text })), /** * Git User Name Is Not Defined: sets `user.name` / `user.email` for commits in the * repository, or globally. */ vcsSetUserIdentity: (repo: string | null, name: string, email: string, global: boolean) => typedError(__TAURI_INVOKE("vcs_set_user_identity", { repo, name, email, global })), + vcsSetWorktreeLocked: (repo: string | null, path: string, locked: boolean) => typedError(__TAURI_INVOKE("vcs_set_worktree_locked", { repo, path, locked })), vcsShelfDelete: (id: string, path: string | null) => typedError(__TAURI_INVOKE("vcs_shelf_delete", { id, path })), vcsShelfDiff: (id: string) => typedError(__TAURI_INVOKE("vcs_shelf_diff", { id })), vcsShelfImport: (repo: string | null, name: string, patch: string) => typedError(__TAURI_INVOKE("vcs_shelf_import", { repo, name, patch })), - vcsShelfPatch: (id: string, path: string | null) => typedError(__TAURI_INVOKE("vcs_shelf_patch", { id, path })), + vcsShelfPatch: (id: string, path: string | null, base: string | null) => typedError(__TAURI_INVOKE("vcs_shelf_patch", { id, path, base })), vcsShelfRename: (id: string, name: string) => typedError(__TAURI_INVOKE("vcs_shelf_rename", { id, name })), /** Shelve Changes: saves the changes of `paths` as a patch on the shelf and reverts them. */ vcsShelve: (name: string, paths: string[]) => typedError(__TAURI_INVOKE("vcs_shelve", { name, paths })), vcsShelves: () => typedError(__TAURI_INVOKE("vcs_shelves")), + /** The effective signing settings for one registered Git repository. */ + vcsSigningConfig: (repo: string) => typedError(__TAURI_INVOKE("vcs_signing_config", { repo })), vcsStage: (paths: string[]) => typedError(__TAURI_INVOKE("vcs_stage", { paths })), + vcsStageFormattedText: (path: string, before: string, after: string) => typedError(__TAURI_INVOKE("vcs_stage_formatted_text", { path, before, after })), /** * Stages only the selected hunks of a file's working-tree changes. * Indices refer to `vcs_diff_hunks(index_text, worktree_text)`. */ vcsStageHunks: (path: string, hunks: number[]) => typedError(__TAURI_INVOKE("vcs_stage_hunks", { path, hunks })), vcsStagePatch: (patch: string) => typedError(__TAURI_INVOKE("vcs_stage_patch", { patch })), - vcsStashApply: (repo: string | null, index: number, pop: boolean, reinstateIndex: boolean, branch: string | null) => typedError(__TAURI_INVOKE("vcs_stash_apply", { repo, index, pop, reinstateIndex, branch })), - vcsStashDrop: (repo: string | null, index: number) => typedError(__TAURI_INVOKE("vcs_stash_drop", { repo, index })), + vcsStageWithoutContent: (paths: string[]) => typedError(__TAURI_INVOKE("vcs_stage_without_content", { paths })), + vcsStagedText: (path: string) => typedError<{ + text: string, + /** Identifies the index entry, including its mode, when this text was read. */ + version: string, +} | null, IdeError>(__TAURI_INVOKE("vcs_staged_text", { path })), + vcsStagingLineHunks: (path: string, headPath: string | null) => typedError<{ + indexVersion: string, + hunks: StagingLineHunk[], +} | null, IdeError>(__TAURI_INVOKE("vcs_staging_line_hunks", { path, headPath })), + vcsStashApply: (repo: string | null, stash: Stash_Deserialize, pop: boolean, reinstateIndex: boolean, branch: string | null) => typedError(__TAURI_INVOKE("vcs_stash_apply", { repo, stash, pop, reinstateIndex, branch })), + vcsStashClear: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_stash_clear", { repo })), + vcsStashDrop: (repo: string | null, stash: Stash_Deserialize) => typedError(__TAURI_INVOKE("vcs_stash_drop", { repo, stash })), vcsStashPush: (repo: string | null, message: string | null, includeUntracked: boolean, keepIndex: boolean, paths: string[] | null) => typedError(__TAURI_INVOKE("vcs_stash_push", { repo, message, includeUntracked, keepIndex, paths })), - vcsStashes: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_stashes", { repo })), + vcsStashes: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_stashes", { repo })), /** Changes of every repository of the project. */ vcsStatus: () => typedError(__TAURI_INVOKE("vcs_status")), /** Changes of `paths` only: the dirty-scope refresh after a watcher batch. */ vcsStatusPaths: (paths: string[]) => typedError(__TAURI_INVOKE("vcs_status_paths", { paths })), vcsTags: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_tags", { repo })), + vcsUndoBranchCreation: (repo: string | null, name: string, created: BranchCreation, previousHead: { + branch: string | null, + commit: string, +} | null) => typedError(__TAURI_INVOKE("vcs_undo_branch_creation", { repo, name, created, previousHead })), /** * Undo Commit: moves HEAD back to the commit's parent, keeping its changes staged. * Returns the undone commit's message. @@ -1980,10 +2085,13 @@ export const commands = { * Branches › Update Selected: fast-forwards local `branches` to their upstreams, one * fetch per remote; the result says what happened to each. Cancellable. */ - vcsUpdateBranches: (repo: string | null, request: RequestId, branches: string[], onOutput: Channel) => typedError(__TAURI_INVOKE("vcs_update_branches", { repo, request, branches, onOutput })), + vcsUpdateBranches: (repo: string | null, request: RequestId, branches: string[], onOutput: Channel, shelfBatch: string | null) => typedError(__TAURI_INVOKE("vcs_update_branches", { repo, request, branches, onOutput, shelfBatch })), + /** Streams Git's prepared commit message and template for the selected worktree. */ + vcsWatchCommitMessages: (repo: string | null, request: RequestId, onMessages: Channel) => typedError(__TAURI_INVOKE("vcs_watch_commit_messages", { repo, request, onMessages })), + vcsWorktreeInclude: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_worktree_include", { repo })), vcsWorktrees: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_worktrees", { repo })), /** Create Patch › Save to file. */ - vcsWritePatch: (path: string, patch: string) => typedError(__TAURI_INVOKE("vcs_write_patch", { path, patch })), + vcsWritePatch: (path: string, patch: string, encoding: string | null) => typedError(__TAURI_INVOKE("vcs_write_patch", { path, patch, encoding })), /** The browsers installed on this machine. */ webBrowsers: () => typedError(__TAURI_INVOKE("web_browsers")), /** The web reference at `pos` of `doc` and its targets; `None` when there is no reference. */ @@ -3112,6 +3220,13 @@ export type AgentUsage = { cost?: AgentCost | null, }; +export type AmendTarget = { + commit: string, + head: HistoryTip, + /** Remote-tracking branch names protected from history rewrites. */ + protectedBranches?: string[], +}; + /** One entry of `adb devices -l`. */ export type AndroidDevice = { /** `adb -s` value: a USB serial number, `emulator-5554`, or `host:port`. */ @@ -3319,6 +3434,22 @@ export type AppearanceSettings_Serialize = { presentationAssistant: PresentationAssistantSettings, }; +export type ApplyCommitOptions = { + author?: string | null, + authorDate?: string | null, + signOff?: boolean, + runHooks?: boolean, +}; + +export type ApplyCommitReview = { + kind: CommitApplyKind, + checkpoint: string, + message: string, + paths: IpcPath[], + author?: string | null, + authorDate?: string | null, +}; + export type ApplyOutcome = { /** Repository-relative paths changed without conflicts. */ applied: string[], @@ -3421,11 +3552,24 @@ export type BeforeLaunchTask = { target?: string, }; -export type BlameLine = { +export type BlameLine = BlameLine_Serialize | BlameLine_Deserialize; + +export type BlameLine_Deserialize = { commit: string, author: string, timeMs: number | null, summary: string, + /** The file blamed for this line when it had another path in the attributed commit. */ + originPath?: IpcPath | null, +}; + +export type BlameLine_Serialize = { + commit: string, + author: string, + timeMs: number | null, + summary: string, + /** The file blamed for this line when it had another path in the attributed commit. */ + originPath?: IpcPath | null, }; /** History for Selection: the commits that changed a block of lines, newest first. */ @@ -3458,36 +3602,94 @@ export type Branch = { remote: boolean, current: boolean, upstream: string | null, + trackedTip?: TrackedTip | null, ahead: number, behind: number, + outgoing?: OutgoingCommits | null, lastCommitMs: number | null, /** Tip commit id. */ commit?: string, }; -export type BranchInfo = { +/** The branch tip before and after creation, used to roll back a partially successful operation. */ +export type BranchCreation = { + tip: string, + previousTip: string | null, +}; + +export type BranchCreationOutcome = { + checkout: CheckoutOutcome, + /** Present once the branch was created, even if restoring local changes needs attention. */ + created: BranchCreation | null, +}; + +export type BranchInfo = BranchInfo_Serialize | BranchInfo_Deserialize; + +export type BranchInfo_Deserialize = { /** `None` when HEAD is detached. */ head: string | null, headCommit: string | null, upstream: string | null, + /** The upstream as configured on the current branch, even before its tracking ref is fetched. */ + upstreamTracking?: UpstreamTracking | null, + trackedTip?: TrackedTip | null, ahead: number, behind: number, + /** Outgoing commits to the default Push destination, when it has a local tracking ref. */ + outgoing?: OutgoingCommits | null, /** Merge / rebase / cherry-pick in progress. */ operation: string | null, + rebase?: RebaseState | null, }; -export type BranchUpdate = { - branch: string, - status: BranchUpdateStatus, - /** Why it failed. */ - message: string | null, +export type BranchInfo_Serialize = { + /** `None` when HEAD is detached. */ + head: string | null, + headCommit: string | null, + upstream: string | null, + /** The upstream as configured on the current branch, even before its tracking ref is fetched. */ + upstreamTracking?: UpstreamTracking | null, + trackedTip?: TrackedTip | null, + ahead: number, + behind: number, + /** Outgoing commits to the default Push destination, when it has a local tracking ref. */ + outgoing?: OutgoingCommits | null, + /** Merge / rebase / cherry-pick in progress. */ + operation: string | null, + rebase?: RebaseState | null, }; +export type BranchRebasePlan = { + head: HistoryTip, + target: string, + onto: string, +}; + +export type BranchUpdate = BranchUpdate_Serialize | BranchUpdate_Deserialize; + /** What Update Selected did to one local branch. */ export type BranchUpdateStatus = "updated" | "upToDate" | /** Diverged from its upstream: left as it is. */ "notFastForward" | "noUpstream" | "failed"; +export type BranchUpdate_Deserialize = { + branch: string, + status: BranchUpdateStatus, + /** Why it failed. */ + message: string | null, + /** Linked worktree where the update was attempted. */ + worktree?: IpcPath | null, +}; + +export type BranchUpdate_Serialize = { + branch: string, + status: BranchUpdateStatus, + /** Why it failed. */ + message: string | null, + /** Linked worktree where the update was attempted. */ + worktree?: IpcPath | null, +}; + /** Editor › General › Breadcrumbs. */ export type BreadcrumbsSettings = { show?: boolean, @@ -3717,6 +3919,7 @@ export type Changelist = { id: string, name: string, comment?: string, + appliedCommit?: CommitApplySource | null, }; /** User change lists of a project and which list each changed file belongs to. */ @@ -3756,10 +3959,7 @@ export type CheckoutOptions = { ignoreOtherWorktrees?: boolean, }; -/** - * Result of [`Repo::checkout_with`]; the non-`Done` variants other than `Conflicts` - * left the repository untouched. - */ +/** Result of [`Repo::checkout_with`]. */ export type CheckoutOutcome = { kind: "done" } | /** These local changes (repository-relative paths) would be overwritten. */ { kind: "localChanges"; files: string[] } | @@ -3776,12 +3976,28 @@ export type CheckoutOutcome = { kind: "done" } | * on conflicts in these files. */ { kind: "conflicts"; files: string[] } | +/** Switched, but the saved changes could not be restored. */ +{ kind: "restoreFailed"; message: string } | /** * Git refused: `branch` is checked out in the linked worktree at `path`. Nothing * changed; the branch can be worked on there. */ { kind: "checkedOutInWorktree"; branch: string; path: string }; +/** The refs shown before checking out and rebasing a branch onto the current branch. */ +export type CheckoutRebasePlan = { + base: HistoryTip, + branch: string, + branchTip: string | null, + remote: CheckoutRebaseRemote | null, +}; + +export type CheckoutRebaseRemote = { + name: string, + commit: string, + dropLocalCommits: boolean, +}; + export type ChoiceOption = { value: string, label: string, @@ -3968,20 +4184,56 @@ export type CommandForm = { export type Commit = Commit_Serialize | Commit_Deserialize; /** A window's answer to a [`CommitRequest`]. */ -export type CommitAnswer = +export type CommitAnswer = CommitAnswer_Serialize | CommitAnswer_Deserialize; + +/** A window's answer to a [`CommitRequest`]. */ +export type CommitAnswer_Deserialize = /** The window's project has no repository. */ -{ kind: "noRepository" } | { kind: "selection"; selection: CommitSelection } | +({ kind: "noRepository" }) & { selection?: never } | { kind: "selection"; selection: CommitSelection_Deserialize } | /** The message was replaced. */ -{ kind: "done" } | +({ kind: "done" }) & { selection?: never } | /** The draft is no longer at the revision. */ -{ kind: "stale" }; +({ kind: "stale" }) & { selection?: never }; + +/** A window's answer to a [`CommitRequest`]. */ +export type CommitAnswer_Serialize = +/** The window's project has no repository. */ +({ kind: "noRepository" }) & { selection?: never } | { kind: "selection"; selection: CommitSelection_Serialize } | +/** The message was replaced. */ +({ kind: "done" }) & { selection?: never } | +/** The draft is no longer at the revision. */ +({ kind: "stale" }) & { selection?: never }; + +export type CommitApplyKind = "cherry-pick" | "revert"; + +export type CommitApplySource = { + kind?: CommitApplyKind, + repo: IpcPath, + commit: string, + base: string, + author: string | null, + authorDate: string | null, +}; + +export type CommitMessages = { + template: string | null, + prepared: string | null, + pendingApply?: PendingCommitApply | null, +}; /** Commit Options (IDEA's commit options popup). */ -export type CommitOptions = { +export type CommitOptions = CommitOptions_Serialize | CommitOptions_Deserialize; + +/** Commit Options (IDEA's commit options popup). */ +export type CommitOptions_Deserialize = { amend: boolean, + /** Amend this older commit instead of HEAD, with the history snapshot selected in the UI. */ + amendTarget?: AmendTarget | null, signOff: boolean, /** `--author`, e.g. `Name `; `None` or blank uses the configured user. */ author: string | null, + /** Explicit Git author date, e.g. an ISO 8601 timestamp with a time zone. */ + authorDate?: string | null, /** False skips the pre-commit and commit-msg hooks (`--no-verify`). */ runHooks: boolean, /** @@ -3989,13 +4241,37 @@ export type CommitOptions = { * committed through a temporary index, so neither the working tree nor the other * entries of the index change; afterwards their index entries match the new commit. */ - partial?: PartialCommitFile[], + partial?: PartialCommitFile_Deserialize[], /** Files committed with their working-tree content, staged or not. */ stage?: IpcPath[], /** Staged files left out of the commit; they stay staged afterwards. */ exclude?: IpcPath[], }; +/** Commit Options (IDEA's commit options popup). */ +export type CommitOptions_Serialize = { + amend: boolean, + /** Amend this older commit instead of HEAD, with the history snapshot selected in the UI. */ + amendTarget: AmendTarget | null, + signOff: boolean, + /** `--author`, e.g. `Name `; `None` or blank uses the configured user. */ + author: string | null, + /** Explicit Git author date, e.g. an ISO 8601 timestamp with a time zone. */ + authorDate: string | null, + /** False skips the pre-commit and commit-msg hooks (`--no-verify`). */ + runHooks: boolean, + /** + * Files committed with only some of their changes (IDEA's partial commit). They are + * committed through a temporary index, so neither the working tree nor the other + * entries of the index change; afterwards their index entries match the new commit. + */ + partial: PartialCommitFile_Serialize[], + /** Files committed with their working-tree content, staged or not. */ + stage: IpcPath[], + /** Staged files left out of the commit; they stay staged afterwards. */ + exclude: IpcPath[], +}; + /** A problem a plugin's before-commit check reported (WIT `commit-checker.commit-problem`). */ export type CommitProblem = { message: string, @@ -4004,6 +4280,11 @@ export type CommitProblem = { range: Range | null, }; +export type CommitPushTarget = { + branch: string | null, + destination: DefaultPushTarget | null, +}; + /** What a plugin asks of a window's Commit view. */ export type CommitRequest = /** @@ -4018,17 +4299,42 @@ export type CommitRequest = * What a window's Commit view would commit: per repository, the options * `vcs_commit` would get. */ -export type CommitSelection = { +export type CommitSelection = CommitSelection_Serialize | CommitSelection_Deserialize; + +export type CommitSelectionRepo = CommitSelectionRepo_Serialize | CommitSelectionRepo_Deserialize; + +export type CommitSelectionRepo_Deserialize = { + root: IpcPath, + options: CommitOptions_Deserialize, +}; + +export type CommitSelectionRepo_Serialize = { + root: IpcPath, + options: CommitOptions_Serialize, +}; + +/** + * What a window's Commit view would commit: per repository, the options + * `vcs_commit` would get. + */ +export type CommitSelection_Deserialize = { /** Changes whenever the message, the included changes or Amend do. */ revision: number, message: string, amend: boolean, - repositories: CommitSelectionRepo[], + repositories: CommitSelectionRepo_Deserialize[], }; -export type CommitSelectionRepo = { - root: IpcPath, - options: CommitOptions, +/** + * What a window's Commit view would commit: per repository, the options + * `vcs_commit` would get. + */ +export type CommitSelection_Serialize = { + /** Changes whenever the message, the included changes or Amend do. */ + revision: number, + message: string, + amend: boolean, + repositories: CommitSelectionRepo_Serialize[], }; /** Version Control › Commit: commit checks and commit-message inspections. */ @@ -4039,9 +4345,11 @@ export type CommitSettings = { */ nonModal?: boolean, includeChangesByDefault?: boolean, + commitAllWhenNothingStaged?: boolean, /** Start with an empty message instead of the last one / the changelist's. */ clearInitialMessage?: boolean, analyzeCode?: boolean, + postponeSlowChecks?: boolean, checkTodo?: boolean, reformat?: boolean, optimizeImports?: boolean, @@ -4251,6 +4559,9 @@ export type ComposerInstallState = { reason: ComposerInstall, }; +/** Which version the user accepts, relative to the merge editor's labels. */ +export type ConflictSide = "ours" | "theirs"; + /** The user's answer on an install or consent page. */ export type Consent = { /** @@ -5238,14 +5549,41 @@ export type DecorationSet = { file: FileDecoration | null, }; +export type DefaultPushTarget = { + selection: PushSelection, + setUpstream: boolean, +}; + /** A deleted local branch, enough to restore it (IDEA's "Restore" notification action). */ -export type DeletedBranch = { +export type DeletedBranch = DeletedBranch_Serialize | DeletedBranch_Deserialize; + +/** A deleted local branch, enough to restore it (IDEA's "Restore" notification action). */ +export type DeletedBranch_Deserialize = { name: string, /** The commit the branch pointed at. */ tip: string, /** Its upstream (`origin/x`), restored with it. */ upstream: string | null, - /** It was not fully merged: its own commits are now unreachable from any branch. */ + /** Configured remote and source branch, if the upstream is remote. */ + remoteUpstream?: UpstreamTracking | null, + /** Tip that Git compared the deleted branch with when deciding it was unmerged. */ + unmergedBase?: string | null, + /** Git required a force delete because the branch was not fully merged. */ + unmerged: boolean, +}; + +/** A deleted local branch, enough to restore it (IDEA's "Restore" notification action). */ +export type DeletedBranch_Serialize = { + name: string, + /** The commit the branch pointed at. */ + tip: string, + /** Its upstream (`origin/x`), restored with it. */ + upstream: string | null, + /** Configured remote and source branch, if the upstream is remote. */ + remoteUpstream?: UpstreamTracking | null, + /** Tip that Git compared the deleted branch with when deciding it was unmerged. */ + unmergedBase?: string | null, + /** Git required a force delete because the branch was not fully merged. */ unmerged: boolean, }; @@ -5423,6 +5761,17 @@ export type Diagnostic = { server?: string | null, }; +export type DiffEntry = { + mode: string, + /** The recorded commit for a gitlink, independent of the parent's object database. */ + gitlink: string | null, +}; + +export type DiffEntryRequest = { + path: IpcPath, + rev: string, +}; + /** The two files of a command-line diff (`openidea diff a.txt b.txt`), both sides editable. */ export type DiffFilesLaunch = { left: IpcPath, @@ -5437,9 +5786,13 @@ export type DiffLaunch_Deserialize = { /** Absolute path of the file (the right side's path). */ path: string, left: DiffSide_Deserialize, + middle?: DiffSide_Deserialize | null, right: DiffSide_Deserialize, - /** 0-based line of the right side to reveal. */ + /** 0-based line to reveal. */ line?: number | null, + lineSide?: DiffLineSide | null, + col?: number | null, + chain?: DiffLaunch_Deserialize[] | null, }; /** The diff a diff window shows (IDEA's "Show Diff in New Window"), from the UI's `DiffData`. */ @@ -5447,11 +5800,17 @@ export type DiffLaunch_Serialize = { /** Absolute path of the file (the right side's path). */ path: string, left: DiffSide_Serialize, + middle?: DiffSide_Serialize | null, right: DiffSide_Serialize, - /** 0-based line of the right side to reveal. */ + /** 0-based line to reveal. */ line?: number | null, + lineSide?: DiffLineSide | null, + col?: number | null, + chain?: DiffLaunch_Serialize[] | null, }; +export type DiffLineSide = "left" | "middle" | "right"; + /** One side of a diff window's comparison (the UI's `DiffSide`, `diffInput.ts`). */ export type DiffSide = DiffSide_Serialize | DiffSide_Deserialize; @@ -6139,6 +6498,8 @@ export type EditorTabsSettings = { activateOnClose?: string, }; +export type EmptyCherryPickAction = "skip" | "createEmpty"; + /** Editor › File Encodings. */ export type EncodingSettings = { /** Fallback for files outside the project that are not valid UTF-8 (WHATWG label). */ @@ -6165,7 +6526,15 @@ export type EnvReloaded = { shellRead: boolean, }; -export type ErrorData = { type: "tool"; tool: string; missing: boolean }; +export type ErrorData = { type: "tool"; tool: string; missing: boolean } | +/** A non-fast-forward push from the current branch to its configured upstream. */ +{ type: "pushRejected"; source: string; upstream: string; divergence: PushDivergence | null; +/** Other refs may already have been published in the same push. */ +report?: PushReport | null } | +/** Git updated some refs before a later ref or push URL failed. */ +{ type: "pushPartiallyApplied"; report: PushReport } | +/** A conflicted history replay left an amend commit ready to keep separately. */ +{ type: "amendConflict"; commit: string }; export type ErrorKind = "notFound" | "alreadyExists" | "permissionDenied" | "invalidInput" | /** Document version mismatch; the UI must resync the full text. */ @@ -6349,6 +6718,18 @@ export type FacetConfig = { webRoot?: string, }; +export type FetchRemoteResult = { + remote: string, + pruned: string[], + error: IdeError | null, +}; + +export type FetchReport = { + remotes: FetchRemoteResult[], +}; + +export type FetchTagsMode = "auto" | "sync" | "always" | "never"; + export type Field = { id: string, label: string, @@ -6857,6 +7238,13 @@ export type GhRepo = { viewerPermission: string, }; +export type GitAnnotateMovement = "none" | "withinFile" | "acrossFiles"; + +export type GitAnnotateSettings = { + ignoreWhitespace?: boolean, + movement?: GitAnnotateMovement, +}; + export type GitExecutableInfo = { /** `git version …` output. */ version: string, @@ -6864,19 +7252,38 @@ export type GitExecutableInfo = { path: string, }; -export type GitOperation = +export type GitOperation = GitOperation_Serialize | GitOperation_Deserialize; + +export type GitOperationResult = RewrittenCommit | ({ rebased: HistoryTip }) & { action?: never; emptyCherryPicks?: never } | ({ emptyCherryPicks: number; action: EmptyCherryPickAction }) & { rebased?: never }; + +export type GitOperation_Deserialize = /** Continue the merge / rebase / cherry-pick / revert in progress. */ -{ op: "continue" } | +({ op: "continue" }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | ({ op: "continueReviewedApply"; checkpoint: string; message: string; options?: ApplyCommitOptions }) & { base?: never; branch?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; mode?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | ({ op: "finishMerge"; branch: string | null; head: string; target: string }) & { base?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never } | /** Stage and Retry: stage the changes of tracked files, then continue. */ -{ op: "stageAndContinue" } | { op: "abort" } | { op: "skip" } | -/** Commits oldest first; `record_origin` adds "(cherry picked from commit …)". */ -{ op: "cherryPick"; commits: string[]; recordOrigin?: boolean } | +({ op: "stageAndContinue" }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | ({ op: "abort"; expected?: string | null; expectedRebase?: RebaseState | null }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expectedHead?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | ({ op: "skip" }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | +/** Commits oldest first; add the origin for all commits or the specified subset. */ +({ op: "cherryPick"; commits: string[]; recordOrigin?: boolean; recordOriginFor?: string[] }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; shelfBatch?: never; target?: never } | /** Commits newest first. */ -{ op: "revert"; commits: string[] } | { op: "reset"; commit: string; mode: ResetMode } | +({ op: "revert"; commits: string[] }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | ({ op: "reset"; commit: string; mode: ResetMode }) & { base?: never; branch?: never; checkpoint?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | /** Rebases `base..HEAD` (`base: None` = from the root) following `entries`, oldest first. */ -{ op: "interactiveRebase"; base: string | null; entries: RebaseEntry[] }; +({ op: "interactiveRebase"; base: string | null; entries: RebaseEntry[] }) & { branch?: never; checkpoint?: never; commit?: never; commits?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | ({ op: "checkoutRebase"; plan: CheckoutRebasePlan; shelfBatch: string | null }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; recordOrigin?: never; recordOriginFor?: never; target?: never } | ({ op: "rebaseBranch"; plan: BranchRebasePlan; shelfBatch: string | null }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; recordOrigin?: never; recordOriginFor?: never; target?: never } | ({ op: "dropCommitChanges"; commit: string; expectedHead: HistoryTip; paths: string[] }) & { base?: never; branch?: never; checkpoint?: never; commits?: never; entries?: never; expected?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never }; + +export type GitOperation_Serialize = +/** Continue the merge / rebase / cherry-pick / revert in progress. */ +({ op: "continue" }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | ({ op: "continueReviewedApply"; checkpoint: string; message: string; options: ApplyCommitOptions }) & { base?: never; branch?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; mode?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | ({ op: "finishMerge"; branch: string | null; head: string; target: string }) & { base?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never } | +/** Stage and Retry: stage the changes of tracked files, then continue. */ +({ op: "stageAndContinue" }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | ({ op: "abort"; expected: string | null; expectedRebase?: RebaseState | null }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expectedHead?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | ({ op: "skip" }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | +/** Commits oldest first; add the origin for all commits or the specified subset. */ +({ op: "cherryPick"; commits: string[]; recordOrigin: boolean; recordOriginFor: string[] }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; shelfBatch?: never; target?: never } | +/** Commits newest first. */ +({ op: "revert"; commits: string[] }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | ({ op: "reset"; commit: string; mode: ResetMode }) & { base?: never; branch?: never; checkpoint?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | +/** Rebases `base..HEAD` (`base: None` = from the root) following `entries`, oldest first. */ +({ op: "interactiveRebase"; base: string | null; entries: RebaseEntry[] }) & { branch?: never; checkpoint?: never; commit?: never; commits?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never } | ({ op: "checkoutRebase"; plan: CheckoutRebasePlan; shelfBatch: string | null }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; recordOrigin?: never; recordOriginFor?: never; target?: never } | ({ op: "rebaseBranch"; plan: BranchRebasePlan; shelfBatch: string | null }) & { base?: never; branch?: never; checkpoint?: never; commit?: never; commits?: never; entries?: never; expected?: never; expectedHead?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; paths?: never; recordOrigin?: never; recordOriginFor?: never; target?: never } | ({ op: "dropCommitChanges"; commit: string; expectedHead: HistoryTip; paths: string[] }) & { base?: never; branch?: never; checkpoint?: never; commits?: never; entries?: never; expected?: never; expectedRebase?: never; head?: never; message?: never; mode?: never; options?: never; plan?: never; recordOrigin?: never; recordOriginFor?: never; shelfBatch?: never; target?: never }; + +export type GitSaveChangesPolicy = "shelve" | "stash"; export type GitSettings = { + annotate?: GitAnnotateSettings, /** Show blame after the current editor line. */ inlineBlame?: boolean, /** @@ -6889,20 +7296,29 @@ export type GitSettings = { syncBranchOperations?: boolean, /** Path to the git executable; empty = auto-detect. */ executable?: string, + /** Clone all submodules along with the root repository. */ + cloneSubmodules?: boolean, /** Default of Update Project: `merge` | `rebase`. */ updateMethod?: string, + /** Where Git operations keep local changes temporarily. */ + saveChangesPolicy?: GitSaveChangesPolicy, /** Push rejected (non-fast-forward): update the branch and push again. */ autoUpdateOnPushRejected?: boolean, warnCrlf?: boolean, warnDetachedHead?: boolean, - /** Background check for incoming commits: `auto` | `always` | `never`. */ + /** Background check for incoming commits: `auto` | `always` | `check` | `never`. */ incomingCheck?: string, /** Minutes between background checks for incoming commits. */ incomingCheckInterval?: number, + /** How an explicit fetch or project update handles remote tags. */ + fetchTagsMode?: FetchTagsMode, /** Branch name globs, `;`/`,`-separated; force push to them is prohibited. */ protectedBranches?: string, /** Initial state of Commit Options › Sign-off Commit. */ signOff?: boolean, + /** Add Git's origin line when cherry-picking commits from protected remote branches. */ + addCherryPickOrigin?: boolean, + emptyCherryPick?: EmptyCherryPickAction, /** Ask before committing files larger than `large_file_mb`. */ warnLargeFiles?: boolean, largeFileMb?: number, @@ -6914,6 +7330,8 @@ export type GitSettings = { pushDialogOnlyProtected?: boolean, /** Stashes and shelves share one tab. */ combineStashAndShelf?: boolean, + /** What the stash browser compares its saved files against. */ + stashDiffTarget?: StashDiffTarget, /** * The non-modal Commit tool window works on the index: Staged / Unstaged groups, * stage and unstage instead of inclusion checkboxes, and no change lists. @@ -6926,6 +7344,17 @@ export type GitSettings = { cliStatus?: boolean, }; +export type GitSigningConfig = { + format: string, + enabled: boolean, + key: string | null, +}; + +export type GitSigningEdit = { + enabled: boolean | null, + key: string | null, +}; + export type GoBuildTags = { /** Empty values inherit the selected toolchain's defaults. */ os?: string, @@ -6956,6 +7385,11 @@ export type GoSettings = { export type GotoKind = "definition" | "declaration" | "typeDefinition" | "implementation"; +export type GpgSigningKey = { + fingerprint: string, + userId: string | null, +}; + /** One line of the report: an occurrence of a dependency where it is requested. */ export type GradleDependency = { /** `group`, empty for a project dependency. */ @@ -7316,6 +7750,12 @@ export type HistoryKind = */ "label"; +/** Branch and tip confirmed in the UI before editing history. */ +export type HistoryTip = { + branch: string | null, + commit: string, +}; + /** What triggered a hot reload; `flutter debug_adapter` takes it as `reason`. */ export type HotReloadReason = "manual" | "save"; @@ -7570,6 +8010,16 @@ export type ImportedRunConfig_Serialize = { export type ImportsOnPaste = "ask" | "always" | "never"; +export type IncomingRefsReport = { + branches: UnfetchedBranch[], + errors: IncomingRemoteError[], +}; + +export type IncomingRemoteError = { + remote: string, + error: IdeError, +}; + export type IndentConfig = IndentConfig_Serialize | IndentConfig_Deserialize; export type IndentConfig_Deserialize = { @@ -8376,6 +8826,11 @@ export type LanguagesSettings = { zig?: ZigSettings, }; +export type LargeCommitFile = { + path: IpcPath, + size: number, +}; + /** What a freshly opened window should do once its frontend is up. */ export type Launch = Launch_Serialize | Launch_Deserialize; @@ -9263,10 +9718,15 @@ export type MergeOptions = { ffOnly?: boolean, squash?: boolean, noCommit?: boolean, + noVerify?: boolean, + /** Merge histories whose commits have no common ancestor. */ + allowUnrelatedHistories?: boolean, /** `-m`: message of the merge commit (Merge dialog only). */ message?: string | null, }; +export type MergeOutcome = { kind: "done" } | { kind: "localChanges"; files: string[] } | { kind: "conflicts" } | { kind: "alreadyUpToDate" } | { kind: "readyToCommit" } | { kind: "squashed" }; + /** * Who stands on each side of the conflicts of the operation in progress (merge editor * titles, as IDEA labels them). @@ -9293,6 +9753,8 @@ export type MergeSides = { /** The versions of a conflicted file as the merge editor shows them. */ export type MergeVersions = { + /** Binary versions are available for whole-file acceptance, without decoding their data. */ + binary?: boolean, base: string | null, /** The user's side ("Accept Yours"): git's stage 2, or stage 3 when `sides.reversed`. */ ours: string | null, @@ -9560,6 +10022,14 @@ export type OpenProject = { remote: RemoteTarget | null, }; +export type OutgoingCommits = { + remote: string, + branch: string, + /** Full local tracking ref, which may use a custom fetch refspec. */ + reference: string, + count: number, +}; + /** A node of a document outline (Structure tool window, breadcrumbs). */ export type OutlineItem = { name: string, @@ -9585,10 +10055,52 @@ export type PackageFile = { }; /** A file of a partial commit: which of its changes against HEAD to commit. */ -export type PartialCommitFile = { +export type PartialCommitFile = PartialCommitFile_Serialize | PartialCommitFile_Deserialize; + +/** A file of a partial commit: which of its changes against HEAD to commit. */ +export type PartialCommitFile_Deserialize = { path: IpcPath, /** The hunks to commit, as [`diff_hunks`] of the HEAD and on-disk texts reports them. */ hunks: HunkRange[], + /** Hunks whose added and removed lines have individual inclusion. */ + lineHunks?: PartialCommitHunk[], + /** Before-commit edits against the exact text selected by these hunks. */ + prepared?: PreparedPartialCommit | null, +}; + +/** A file of a partial commit: which of its changes against HEAD to commit. */ +export type PartialCommitFile_Serialize = { + path: IpcPath, + /** The hunks to commit, as [`diff_hunks`] of the HEAD and on-disk texts reports them. */ + hunks: HunkRange[], + /** Hunks whose added and removed lines have individual inclusion. */ + lineHunks?: PartialCommitHunk[], + /** Before-commit edits against the exact text selected by these hunks. */ + prepared?: PreparedPartialCommit | null, +}; + +export type PartialCommitHunk = { + range: HunkRange, + /** The normalised texts that the user selected from, used to detect stale selections. */ + oldText: string, + newText: string, + /** Included deletions and additions, 0-based offsets within their respective sides. */ + deletions: number[], + additions: number[], +}; + +export type PatchDiffContent = { kind: "text"; before: string | null; after: string | null } | { kind: "conflict"; local: string | null; base: string | null; patched: string | null } | { kind: "raw"; local: string | null; patch: string; applies: boolean } | { kind: "binary" }; + +export type PatchDirectoryCandidate = { + directory: IpcPath, + source: IpcPath, + strip: number, + applies: boolean | null, +}; + +export type PatchDirectoryMatches = { + path: string, + candidates: PatchDirectoryCandidate[], }; /** One file of a patch (Apply Patch preview). */ @@ -9602,13 +10114,47 @@ export type PatchFile = { binary: boolean, /** Applies cleanly to the working tree (otherwise a 3-way merge is attempted). */ applies: boolean, + missingBase?: boolean, +}; + +export type PatchFileDiff = { + path: IpcPath, + oldPath: IpcPath | null, + content: PatchDiffContent, +}; + +export type PatchPathMapping = { + path: string, + directory: IpcPath | null, + strip: number, + file: IpcPath | null, +}; + +export type PatchPlacement = { + path: string, + target: IpcPath | null, + error: string | null, +}; + +export type PatchPreview = { + files: PatchFile[], + base: IpcPath | null, + placements: PatchPlacement[] | null, + directoryMatches: PatchDirectoryMatches[], + automaticMappings: PatchPathMapping[], }; export type PatchSource = /** Local changes of these files (absolute paths). */ { from: "changes"; paths: IpcPath[]; reverse: boolean } | +/** Changes selected on either side of the index in the staging tree. */ +{ from: "staging"; entries: StagingPatchEntry[]; reverse: boolean } | /** Changes made by these commits (oldest first). */ -{ from: "commits"; commits: string[]; reverse: boolean }; +{ from: "commits"; commits: string[]; reverse: boolean } | +/** Selected files between two revisions, including both paths of a rename. */ +{ from: "revisions"; before: string; after: string; paths: string[] }; + +export type PatchTarget = "project" | "repository"; /** An entry offered when completing a path. */ export type PathCompletion = { @@ -9616,6 +10162,11 @@ export type PathCompletion = { dir: boolean, }; +export type PendingCommitApply = { + source: CommitApplySource, + paths: IpcPath[], +}; + /** A PHP version and where it comes from. */ export type PhpLanguageLevel = { /** `X.Y.Z`. */ @@ -10347,6 +10898,12 @@ export type PrTimelineItem = { url: string | null, }; +export type PreparedPartialCommit = { + /** LF version of the selected text before running the language server. */ + before: string, + text: string, +}; + /** A request ready to send: variables substituted, includes read. */ export type PreparedRequest = { name: string | null, @@ -10527,6 +11084,17 @@ export type ProjectLibrary = { scope?: DependencyScope, }; +export type ProjectPatchFailure = { + root: IpcPath, + error: IdeError, +}; + +export type ProjectPatchOutcome = { + outcome: ApplyOutcome, + conflictedRepositories: IpcPath[], + failures: ProjectPatchFailure[], +}; + export type ProjectRoots = { /** Effective roots, sorted by path. */ roots: SourceFolder[], @@ -10567,6 +11135,12 @@ export type ProjectStructureSettings = { artifacts?: ArtifactConfig[], }; +export type ProjectUpdateTarget = { + root: IpcPath, + parent: IpcPath | null, + detachedSubmodule: boolean, +}; + /** * What a plugin asks the user (`ui.pick`, `ui.pick-many`, `ui.input`, * `ui.input-multiline`, `ui.confirm`). @@ -10649,9 +11223,67 @@ export type PullRequestSummary = { deletions: number, }; +/** + * The two tips shown in the rejected-push dialog. A retry must use this lease + * even if a fetch advances the remote-tracking branch while the dialog is open. + */ +export type PushDivergence = { + source: string, + remote: string, + target: string, + localTip: string, + remoteTip: string, + remoteCommits: number, +}; + +export type PushInspection = { + state: PushTargetState, + localTip: string, + /** An empty value expects the branch to be absent. Null means no tip was available. */ + remoteTip: string | null, + remoteCommits: number, + remoteChecked: boolean, +}; + +export type PushRefResult = { + reference: string, + status: PushRefStatus, + /** The number of commits between the tips Git reports for a fast-forward. */ + commits: number | null, +}; + +export type PushRefStatus = "fastForward" | "forced" | "created" | "upToDate" | "deleted"; + +/** + * Git's reported result for each destination ref. A remote with several push URLs can + * report more than one result for the same ref. + */ +export type PushReport = { + remote: string | null, + refs: PushRefResult[], +}; + +export type PushSelection = { + /** A local branch. A detached source has no branch and requires a commit ID. */ + branch: string | null, + revision: string | null, + remote: string, + target: string, + /** A configured non-branch destination, for example a Gerrit review ref. */ + specialRef?: boolean, +}; + /** Push dialog › Push tags: every tag, or only annotated tags on the pushed commits. */ export type PushTags = "all" | "currentBranch"; +export type PushTargetChoices = { + branch: string | null, + destination: DefaultPushTarget | null, + destinations: DefaultPushTarget[], +}; + +export type PushTargetState = "ready" | "diverged" | "fetchRequired"; + /** A class definition and the methods it declares. */ export type PythonClassFacts = { name: string, @@ -10763,6 +11395,41 @@ export type RebaseAction = "pick" | /** Meld into the previous commit, keeping the previous message. */ "fixup" | "drop"; +export type RebaseEdit = RebaseEdit_Serialize | RebaseEdit_Deserialize; + +export type RebaseEditKind = "plan" | "message"; + +export type RebaseEdit_Deserialize = { + kind: RebaseEditKind, + text: string, + plan: RebaseTodoRow_Deserialize[] | null, +}; + +export type RebaseEdit_Serialize = { + kind: RebaseEditKind, + text: string, + plan: RebaseTodoRow_Serialize[] | null, +}; + +export type RebaseEditorOperation = { kind: "start"; upstream: string | null; options: RebaseOptions } | { kind: "continue"; stage: boolean } | { kind: "skip" }; + +export type RebaseEditorPrompt = RebaseEditorPrompt_Serialize | RebaseEditorPrompt_Deserialize; + +export type RebaseEditorPrompt_Deserialize = { + index: number, + edit: RebaseEdit_Deserialize, +}; + +export type RebaseEditorPrompt_Serialize = { + index: number, + edit: RebaseEdit_Serialize, +}; + +export type RebaseEditorReply = { + text: string, + rewords?: { [key in string]: string }, +}; + /** One line of an interactive rebase plan. */ export type RebaseEntry = { commit: string, @@ -10771,14 +11438,31 @@ export type RebaseEntry = { message?: string | null, }; +export type RebaseFixupMessage = "replace" | "edit"; + /** Rebase dialog options. */ export type RebaseOptions = { - /** `--onto `: replay `upstream..HEAD` onto this revision instead. */ + /** Replay the selected commits onto this revision instead. */ onto?: string | null, + /** Switch to this local branch before rebasing it. */ + branch?: string | null, rebaseMerges?: boolean, keepEmpty?: boolean, + updateRefs?: boolean, + autosquash?: boolean | null, }; +export type RebaseState = { + original: HistoryTip, + onto: string, +}; + +export type RebaseTodoRow = RebaseTodoRow_Serialize | RebaseTodoRow_Deserialize; + +export type RebaseTodoRow_Deserialize = ({ kind: "commit"; line: number; action: RebaseAction; fixupMessage: RebaseFixupMessage | null; id: string; revision: string; author: string; summary: string; message: string }) & { reference?: never } | ({ kind: "updateRef"; line: number; reference: string }) & { action?: never; author?: never; fixupMessage?: never; id?: never; message?: never; revision?: never; summary?: never }; + +export type RebaseTodoRow_Serialize = ({ kind: "commit"; line: number; action: RebaseAction; fixupMessage?: RebaseFixupMessage | null; id: string; revision: string; author: string; summary: string; message: string }) & { reference?: never } | ({ kind: "updateRef"; line: number; reference: string }) & { action?: never; author?: never; fixupMessage?: never; id?: never; message?: never; revision?: never; summary?: never }; + export type RecentProject = { path: IpcPath, name: string, @@ -10918,7 +11602,9 @@ export type RemoteLaunch = { path: string, }; -export type RemoteOp = { op: "fetch" } | { op: "pull"; rebase: boolean } | +export type RemoteOp = { op: "fetch"; +/** The incoming-commit poll keeps Git's tag handling and uses saved credentials only. */ +background?: boolean; report?: boolean; skipRemotes?: string[] } | { op: "fetchRemote"; remote: string; report?: boolean } | { op: "fetchPushTarget"; selection: PushSelection } | { op: "unshallow" } | { op: "pull"; rebase: boolean; expectedBranch?: string | null } | { op: "updateProjectBranch"; rebase: boolean } | { op: "updateSubmodule"; parent: string } | /** Update Project › Reset to the Remote Branch. */ { op: "resetToUpstream" } | { op: "push"; force_with_lease: boolean; set_upstream: boolean; /** Push dialog › Push tags. */ @@ -10926,7 +11612,7 @@ tags?: PushTags | null; /** Plain `--force` (Force push anyway). */ force?: boolean; /** Push dialog › Run Git hooks unchecked (`--no-verify`). */ -no_verify?: boolean } | +no_verify?: boolean } | { op: "pushSelected"; selection: PushSelection; force_with_lease: boolean; set_upstream: boolean; tags: PushTags | null; no_verify: boolean; inspected?: PushInspection | null } | { op: "forcePushRejected"; divergence: PushDivergence; tags: PushTags | null; no_verify: boolean } | /** Deletes a remote branch; `branch` is the remote-tracking name (`origin/feature`). */ { op: "deleteBranch"; branch: string } | /** @@ -10940,9 +11626,13 @@ set_upstream?: boolean; no_verify?: boolean } | /** Push Tag › Push to `remote`. */ { op: "pushTag"; tag: string; remote: string } | /** Deletes tag `tag` on `remote` (Delete on Remote). */ -{ op: "deleteRemoteTag"; tag: string; remote: string } | +{ op: "deleteRemoteTag"; tag: string; remote: string } | { op: "deleteTagOnRemotes"; deleted: DeletedTag } | /** Pull dialog: `branches` of `remote` (none = the configured merge branch). */ -{ op: "pullFrom"; remote: string; branches: string[]; rebase: boolean; options: MergeOptions }; +{ op: "pullFrom"; remote: string; branches: string[]; +/** Explicit rebase or merge. Null uses Git's configured pull behavior. */ +rebase: boolean | null; options: MergeOptions }; + +export type RemoteOpReport = PushReport | FetchReport; export type RemoteProgress = { stage: RemoteStage, @@ -11134,6 +11824,11 @@ export type RevisionChange = { link?: LinkTarget | null, }; +export type RewrittenCommit = { + head: HeadChange, + commit: string, +}; + /** How a grant is presented (plan 4.2). */ export type Risk = /** Listed on the install page, one confirmation. */ @@ -11851,9 +12546,9 @@ export type ShelvedChangeList = { timeMs: number | null, /** Branch checked out when the changes were shelved. */ branch: string | null, - /** Repository owning the patch; absent in legacy shelves. */ + /** Path base of the patch: the owning repository or a common directory for multiple repositories. */ repo?: IpcPath | null, - /** Repository-relative paths. */ + /** Paths relative to the patch base. */ files: ChangedFile[], }; @@ -12058,6 +12753,45 @@ export type StackFrame = { presentationHint: string | null, }; +export type StagedText = { + text: string, + /** Identifies the index entry, including its mode, when this text was read. */ + version: string, +}; + +export type StagedTextEdit = { + path: IpcPath, + version: string, + text: string, +}; + +export type StagingLineHunk = { + kind: HunkKind, + start: number, + lines: number, + headStart: number, + headLines: number, + headText: string, + indexStart: number, + indexLines: number, + indexText: string, + staged: boolean, + unstaged: boolean, +}; + +export type StagingLineHunks = { + indexVersion: string, + hunks: StagingLineHunk[], +}; + +export type StagingPatchEntry = { + path: IpcPath, + renamedFrom: IpcPath | null, + side: StagingPatchSide, +}; + +export type StagingPatchSide = "staged" | "unstaged" | "both"; + export type StartupMetrics = { /** * Process start → `main`: exec, code-signature scan (seconds for a freshly @@ -12072,7 +12806,20 @@ export type StartupMetrics = { firstIpcMs: number | null, }; -export type Stash = { +export type Stash = Stash_Serialize | Stash_Deserialize; + +/** Applying or popping a stash can leave the working tree with conflicts. */ +export type StashApplyOutcome = { kind: "done" } | { kind: "conflicts"; repository: IpcPath }; + +export type StashApplyResult = { + /** The entry's position when the operation started. */ + index: number, + outcome: StashApplyOutcome, +}; + +export type StashDiffTarget = "local" | "parent"; + +export type Stash_Deserialize = { index: number, message: string, timeMs: number | null, @@ -12080,6 +12827,20 @@ export type Stash = { id: string, /** The commit the stash was made on (the stash commit's first parent). */ base: string | null, + /** The stash's third parent, when untracked files were included. */ + untracked?: string | null, +}; + +export type Stash_Serialize = { + index: number, + message: string, + timeMs: number | null, + /** The stash commit; its changes are those against `base`. */ + id: string, + /** The commit the stash was made on (the stash commit's first parent). */ + base: string | null, + /** The stash's third parent, when untracked files were included. */ + untracked?: string | null, }; /** A plugin's status bar item. */ @@ -12260,6 +13021,8 @@ export type StructureSupport = { locals: boolean, }; +export type SubmoduleRollbackSource = "head" | "index"; + export type SymbolFilter = "all" | /** Go to Class (⌘O): classes, interfaces, structs, enums, traits, type aliases. */ "types"; @@ -12746,6 +13509,11 @@ export type TraceUnavailable = /** java-debug has no debug session for the JVM. */ { kind: "noSession" } | { kind: "unsupported"; detail: string }; +export type TrackedTip = { + tracking: UpstreamTracking, + commit: string, +}; + export type TransferError = { path: string, message: string, @@ -12817,6 +13585,12 @@ export type UndoOutcome = { conflicts: IpcPath[], }; +export type UnfetchedBranch = { + branch: string, + trackedTip: TrackedTip, + advertisedCommit: string, +}; + export type UnityProjectInfo = { editorVersion: string | null, /** File names relative to the Unity root, in stable order. */ @@ -12858,6 +13632,11 @@ export type UpdateStatus = { checking: boolean, }; +export type UpstreamTracking = { + remote: string, + branch: string, +}; + export type Variable = Variable_Serialize | Variable_Deserialize; export type Variable_Deserialize = { @@ -12919,16 +13698,25 @@ export type VcsRoot = { branchRoot: IpcPath, /** Merge / rebase / cherry-pick / revert in progress. */ operation: string | null, + /** The current rebase uses Git's interactive mode. */ + interactiveRebase?: boolean, /** Current branch; `None` when HEAD is detached (or unreadable). */ head: string | null, /** HEAD commit; `None` before the first commit. */ headCommit: string | null, + /** The history ends at a shallow boundary rather than at the initial commit. */ + shallow?: boolean, + /** Remote availability is unknown in Restricted Mode or when config cannot be read. */ + hasRemotes?: boolean | null, + /** Conflicts staged during the current operation that can be reopened. */ + resolvedConflicts?: IpcPath[], }; /** Version Control (main page) and its sub-pages. */ export type VcsSettings = { /** Colour folders that contain changed files (project tree, tabs). */ showDirtyDirectories?: boolean, + createChangelistsAutomatically?: boolean, /** Diffs the user opens show in an editor tab; off, in a separate window. */ diffAsEditorTab?: boolean, /** Stop file history (Show History) after `history_limit` commits. */ @@ -13208,6 +13996,23 @@ export type Worktree = { main: boolean, locked: boolean, prunable: boolean, + /** This worktree belongs to a repository checked out as a submodule. */ + submodule?: boolean, +}; + +export type WorktreeCreation = { + copyWarning: string | null, + setupWarning: string | null, +}; + +export type WorktreeInclude = { + path: IpcPath, + exists: boolean, +}; + +export type WorktreeSetup = { + script: string, + request: RequestId, }; export type ZigSettings = { diff --git a/src/editor/api.ts b/src/editor/api.ts index 864487234..b69dbc980 100644 --- a/src/editor/api.ts +++ b/src/editor/api.ts @@ -21,6 +21,7 @@ import { Annotation, Compartment, Facet, + type ChangeSet, type ChangeSpec, StateEffect, type EditorState, @@ -49,7 +50,7 @@ export { type NavigationMatch, } from "@/editor/navigationProviders"; export { registerRelatedProvider, type RelatedContext, type RelatedItem } from "@/editor/relatedProviders"; -export { offsetsToRange, offsetToPos, posToOffset, rangeToOffsets } from "@/editor/lsp/positions"; +export { offsetsToRange, offsetToPos, posToOffset, rangeToOffsets, textEditsToChanges } from "@/editor/lsp/positions"; /** Documents above this size (UTF-16 units) skip per-line decorations. */ export const HEAVY_LIMIT = 8_000_000; @@ -896,6 +897,10 @@ export interface DocumentAttachment { /** The document's context, as editor contributions receive it. */ context(): EditorDocContext; readOnly: boolean; + /** Watch read-only state even when this attachment has no mounted view. */ + subscribeReadOnly(listener: () => void): () => void; + /** Edits from other views or the backend, in the coordinates of the previous text. */ + subscribeExternalChanges(listener: (changes: ChangeSet) => void): () => void; /** Last view state, kept current while unmounted; use it when remounting this attachment. */ editorState(): EditorState | null; /** Dispatch typing through the document history when `sharedHistory` was requested. */ @@ -917,8 +922,8 @@ export interface DocumentAttachment { /** * Applies a change made by this view's owner as one edit of the document's * history (where `undo` works): the text editor tab's when one shows the - * file, so Undo there reverts it too; else this view's. The view receives - * it like any other change of the document, before this returns. + * file, so Undo there reverts it too; else this view's. Before either exists, + * applies the edit directly to the document. */ edit(changes: ChangeSpec, userEvent?: string): void; /** Detach; the document closes when nothing else shows it. */ diff --git a/src/editor/core/cm/baseKeymap.ts b/src/editor/core/cm/baseKeymap.ts index 8e4ef790a..b7f087cf3 100644 --- a/src/editor/core/cm/baseKeymap.ts +++ b/src/editor/core/cm/baseKeymap.ts @@ -46,9 +46,13 @@ const vertical = (b: KeyBinding): KeyBinding => ? { ...b, run: VERTICAL.get(b.run) ?? b.run, shift: VERTICAL.get(b.shift) ?? b.shift } : b; -export const editorBaseKeymap: readonly KeyBinding[] = [ - ...defaultKeymap.filter((b) => !DROPPED.has(b.run)).map(vertical), +export const editorHistoryKeymap: readonly KeyBinding[] = [ ...historyKeymap, // IDEA's Windows Redo is Ctrl+Shift+Z (Ctrl+Y is Delete Line); CodeMirror only binds it on macOS and Linux. { win: "Ctrl-Shift-z", run: redo, preventDefault: true }, ]; + +export const editorBaseKeymap: readonly KeyBinding[] = [ + ...defaultKeymap.filter((b) => !DROPPED.has(b.run)).map(vertical), + ...editorHistoryKeymap, +]; diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index a2543b4b2..a301ffa52 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -34,6 +34,7 @@ import { textEditorWrapperFor, uriOpenerFor, useContributions, + useEditorDocuments, useStandaloneEditor, useTextEditorWrappers, type EditorCloseSession, @@ -375,6 +376,17 @@ export class EditorController implements SlotHost { .find((tab) => kinds.get(tab.input.kind)?.standalone); useStandaloneEditor.setState({ title: standalone ? tabTitle(standalone.input, kinds) : null }); }), + useEditorDocuments.subscribe(() => { + const current = useTabs.getState(); + const kinds = useContributions.getState().editorKinds; + let next = current; + for (const [paneId, pane] of Object.entries(current.panes)) { + for (const tab of pane.tabs) { + if (tab.preview && inputDirty(tab.input, kinds)) next = promoteTab(next, paneId, tab.id); + } + } + if (next !== current) useTabs.setState(next, true); + }), ); tabOptions.activateOnClose = editorPrefs().tabs.activateOnClose as typeof tabOptions.activateOnClose; let prevSettings = useProject.getState().settings; @@ -675,7 +687,10 @@ export class EditorController implements SlotHost { const state = restoreTabsState(session, fileKey); const kinds = useContributions.getState().editorKinds; for (const pane of Object.values(state.panes)) - pane.tabs = pane.tabs.map((tab) => (documentLifecycle(tab.input, kinds) ? { ...tab, preview: false } : tab)); + pane.tabs = pane.tabs.map((tab) => { + const lifecycle = documentLifecycle(tab.input, kinds); + return lifecycle && !lifecycle.allowPreview ? { ...tab, preview: false } : tab; + }); const current = useTabs.getState(); const liveKeys = openKeys(current); this.restoredViews = new Map(Object.entries(session.files).filter(([path]) => !liveKeys.has(fileKey(path)))); @@ -1359,13 +1374,14 @@ export class EditorController implements SlotHost { this.checkOpening(generation); this.navSuppress++; try { - let s = useTabs.getState(); + const before = useTabs.getState(); + let s = before; const activate = this.isCurrentOpening(generation); if (activate) restoreMaximizedToolWindow(); - const preview = - !!o.preview && - editorPrefs().tabs.previewTab && - !documentLifecycle(input, useContributions.getState().editorKinds); + const kinds = useContributions.getState().editorKinds; + const lifecycle = documentLifecycle(input, kinds); + const canPreview = !lifecycle || (lifecycle.allowPreview && !documentDirty({ input, lifecycle })); + const preview = !!o.preview && editorPrefs().tabs.previewTab && canPreview; if (!activate && preview) return; let paneId = s.panes[generation.pane] ? generation.pane : activate ? s.activePane : null; if (!paneId) return; @@ -1387,12 +1403,11 @@ export class EditorController implements SlotHost { if (found && (!(o.side || o.pane) || found.paneId === paneId)) { paneId = found.paneId; if (activate) s = activateTab(setActivePane(s, paneId), paneId, found.tab.id); - if (!o.preview || documentLifecycle(input, useContributions.getState().editorKinds)) - s = promoteTab(s, paneId, found.tab.id); + if (!o.preview || !canPreview) s = promoteTab(s, paneId, found.tab.id); tabId = found.tab.id; if (activate && found.tab.input.data !== input.data && input.data !== undefined) s = openTab(s, paneId, input, { - preview: o.preview && !documentLifecycle(input, useContributions.getState().editorKinds), + preview: o.preview && canPreview, activate, }).state; } else { @@ -1417,6 +1432,8 @@ export class EditorController implements SlotHost { } finally { this.admitting = false; } + const replaced = preview && closedDocuments(before, s, kinds); + if (replaced && replaced.length) await this.releaseDocuments(replaced).catch((e) => this.documentError(e)); const canFocus = () => this.isCurrentOpening(generation) && this.activeTabOf()?.id === tabId; await this.enforcePaneTabLimit(paneId, activate ? tabId : (useTabs.getState().panes[paneId]?.active ?? tabId)); if (!isTextInput(input)) { @@ -2255,7 +2272,7 @@ export class EditorController implements SlotHost { if (!input) return false; const lifecycle = documentLifecycle(input, useContributions.getState().editorKinds); const run = lifecycle?.[command]; - if (!run) return false; + if (!run || lifecycle.handlesHistory?.(input) === false) return false; void run.call(lifecycle, input).catch((e) => this.documentError(e)); return true; } diff --git a/src/editor/core/customDocuments.test.ts b/src/editor/core/customDocuments.test.ts index dd30fee4f..5775acc50 100644 --- a/src/editor/core/customDocuments.test.ts +++ b/src/editor/core/customDocuments.test.ts @@ -9,6 +9,7 @@ import type * as Messages from "@/workbench/messages"; import * as virtualDocs from "@/platform/virtualDocs"; import type { VirtualDocument } from "@/platform/ipc"; import { + notifyEditorDocumentChanged, registerEditorKind, registerFileEditorProvider, type EditorDocumentLifecycle, @@ -76,6 +77,7 @@ const input = (name = "a"): EditorInput => ({ }); let ctrl: EditorController; let documents: Map; +let lifecycle: EditorDocumentLifecycle; let unregister: () => void; beforeEach(() => { @@ -84,7 +86,7 @@ beforeEach(() => { localStorage.clear(); documents = new Map(); const sessions = documents; - const lifecycle: EditorDocumentLifecycle = { + lifecycle = { isDirty: (i) => sessions.get(i.key)!.isDirty(), flush: (i) => sessions.get(i.key)!.flush(), save: (i) => sessions.get(i.key)!.save(), @@ -130,6 +132,32 @@ function deferred() { } describe("custom editor document lifetime", () => { + it("replaces clean document previews and keeps a preview after its first edit", async () => { + lifecycle.allowPreview = true; + const openClean = async (name: string) => { + const current = input(name); + const doc = new TestDocument(); + doc.text = doc.saved; + documents.set(current.key, doc); + await ctrl.openInput(current, { preview: true, focus: false }); + expect(findTab(useTabs.getState(), current.key)?.tab.preview).toBe(true); + return doc; + }; + + const clean = await openClean("clean"); + const draft = await openClean("draft"); + expect(findTab(useTabs.getState(), input("clean").key)).toBeNull(); + expect(clean.releases).toBe(1); + + draft.text = "new draft"; + notifyEditorDocumentChanged(); + expect(findTab(useTabs.getState(), input("draft").key)?.tab.preview).toBe(false); + await openClean("next"); + expect(findTab(useTabs.getState(), input("draft").key)).not.toBeNull(); + expect(draft.releases).toBe(0); + expect(draft.isDirty()).toBe(true); + }); + it("rejects a delayed virtual document from the previous project", async () => { const started = deferred(); const response = deferred(); diff --git a/src/editor/core/embeddedDocuments.ts b/src/editor/core/embeddedDocuments.ts index eaebc4516..ef35f1342 100644 --- a/src/editor/core/embeddedDocuments.ts +++ b/src/editor/core/embeddedDocuments.ts @@ -20,7 +20,7 @@ export function activateEmbeddedDocuments() { notify: (message) => notifications().notify(message), }); manager.start(); - _provideDocumentAttacher((path) => attachDocument(manager, path)); + _provideDocumentAttacher((path, options) => attachDocument(manager, path, options)); _provideCodePreview((path) => previewExtensions(path, useProject.getState().settings?.editor, ipcBackend)); const offColor = installColorScheme(); const offSettings = useProject.subscribe((s, prev) => { diff --git a/src/editor/core/index.ts b/src/editor/core/index.ts index 7291c21f1..e66bccb90 100644 --- a/src/editor/core/index.ts +++ b/src/editor/core/index.ts @@ -15,7 +15,7 @@ import { isUntitledUri } from "@/platform/virtualDocs"; import { formatDocument } from "@/editor/lsp/format"; import { chooserTitle, locationItems, pinToFind } from "@/editor/lsp/navigation"; import { openPopup } from "@/editor/lsp/popupStore"; -import { editorController } from "./controller"; +import { editorController, useTabs } from "./controller"; import { attachDocument } from "./model/attachment"; import { previewExtensions } from "./cm/preview"; import { registerEditorActions } from "./actions"; @@ -55,6 +55,7 @@ export function activate(): void | (() => void) { [...ctrl.manager.byId.values()].filter((m) => isUntitledUri(m.path) && m.getMeta().dirty).map((m) => m.doc), focus: () => ctrl.focus(), openPaths: () => ctrl.openPaths(), + onOpenTabsChange: (fn) => useTabs.subscribe(fn), openTabs: () => ctrl.openTabs(), tabInput: (paneId, tabId) => ctrl.tabInput(paneId, tabId), activeInput: () => ctrl.activeInput(), diff --git a/src/editor/core/model/attachment.test.ts b/src/editor/core/model/attachment.test.ts index 26d5bfe3b..ddedc2186 100644 --- a/src/editor/core/model/attachment.test.ts +++ b/src/editor/core/model/attachment.test.ts @@ -40,6 +40,25 @@ function setup(files: Record, settings: Settings = {}) { afterEach(() => useDocMeta.setState({}, true)); describe("attached document views (editable diff side)", () => { + it("edits and saves through an attachment before it mounts a view", async () => { + const { backend, manager } = setup({ "/p/a.txt": "one\ntwo\n" }); + const att = await attachDocument(manager, "/p/a.txt"); + const observer = await attachDocument(manager, "/p/a.txt"); + const view = new EditorView({ doc: observer.text(), extensions: [observer.extension] }); + try { + att.edit({ from: 4, to: 7, insert: "three" }, "revert"); + expect(att.text()).toBe("one\nthree\n"); + expect(view.state.doc.toString()).toBe("one\nthree\n"); + await att.save({ exact: true }); + expect(backend.docs.get(att.doc)?.saved).toBe("one\nthree\n"); + } finally { + view.destroy(); + observer.release(); + att.release(); + manager.stop(); + } + }); + it.each([ { autoSave: true, tabOpen: false, ensureFinalNewline: false }, { autoSave: false, tabOpen: false, ensureFinalNewline: false }, diff --git a/src/editor/core/model/attachment.ts b/src/editor/core/model/attachment.ts index 375373413..78ac565ff 100644 --- a/src/editor/core/model/attachment.ts +++ b/src/editor/core/model/attachment.ts @@ -5,14 +5,14 @@ */ import { history, historyField, redo, undo } from "@codemirror/commands"; import { + ChangeSet, Compartment, EditorState, Transaction, type Annotation, - type ChangeSet, type StateCommand, } from "@codemirror/state"; -import { EditorView, ViewPlugin } from "@codemirror/view"; +import { EditorView, ViewPlugin, keymap } from "@codemirror/view"; import { _addEditor, _removeEditor, @@ -24,14 +24,16 @@ import { type DocumentAttachmentOptions, type TextEditorHandle, } from "@/editor/api"; -import type { DocAttachmentTarget, DocumentManager } from "./document"; +import { useDocMeta, type DocAttachmentTarget, type DocumentManager } from "./document"; import { saveOnBlur } from "../saveOnBlur"; +import { editorHistoryKeymap } from "../cm/baseKeymap"; class AttachedView implements DocAttachmentTarget { view: EditorView | null = null; forwarding = false; storedState: EditorState | null = null; history = new Compartment(); + readonly listeners = new Set<(changes: ChangeSet) => void>(); historyState?: () => EditorState | null; adoptHistory?: (state: EditorState) => void; @@ -39,6 +41,7 @@ class AttachedView implements DocAttachmentTarget { if (this.forwarding) return; if (this.view) this.view.dispatch({ changes, annotations }); else if (this.storedState) this.storedState = this.storedState.update({ changes, annotations }).state; + for (const listener of this.listeners) listener(changes); } } @@ -128,6 +131,14 @@ export async function attachDocument( get readOnly() { return model.getMeta().readOnly || model.virtual; }, + subscribeReadOnly: (listener) => + useDocMeta.subscribe((state, previous) => { + if (state[model.path]?.readOnly !== previous[model.path]?.readOnly) listener(); + }), + subscribeExternalChanges: (listener) => { + target.listeners.add(listener); + return () => void target.listeners.delete(listener); + }, editorState: () => target.view?.state ?? target.storedState, dispatchTransactions: (transactions, view) => { for (const tr of transactions) { @@ -161,14 +172,23 @@ export async function attachDocument( }), options.sharedHistory ? target.history.of(history()) : [], options.sharedHistory - ? EditorView.domEventHandlers({ - beforeinput: (event) => { - if (event.inputType !== "historyUndo" && event.inputType !== "historyRedo") return false; - event.preventDefault(); - historyCommand(event.inputType === "historyUndo" ? undo : redo); - return true; - }, - }) + ? [ + keymap.of( + editorHistoryKeymap.map((binding) => { + if (binding.run === undo) return { ...binding, run: () => historyCommand(undo) }; + if (binding.run === redo) return { ...binding, run: () => historyCommand(redo) }; + return binding; + }), + ), + EditorView.domEventHandlers({ + beforeinput: (event) => { + if (event.inputType !== "historyUndo" && event.inputType !== "historyRedo") return false; + event.preventDefault(); + historyCommand(event.inputType === "historyUndo" ? undo : redo); + return true; + }, + }), + ] : [], EditorState.changeFilter.of((tr) => isExternalChange(tr) || !model.ctx().readOnly), options.sharedHistory @@ -194,11 +214,17 @@ export async function attachDocument( undo: () => historyCommand(undo), redo: () => historyCommand(redo), edit: (changes, userEvent = "input") => { - if (model.ctx().readOnly) return; + if (released || model.closed || model.ctx().readOnly) return; // Into the document's history, like a typed edit: the text tab's when there is one. const slot = model.primarySlot(); if (slot) slot.dispatchLocal({ changes, userEvent }); - else target.view?.dispatch({ changes, userEvent }); + else if (target.view) target.view.dispatch({ changes, userEvent }); + else { + const edit = ChangeSet.of(changes, model.sync.localText.length); + if (edit.empty) return; + target.applyExternal(edit, [Transaction.userEvent.of(userEvent)]); + model.onLocal(edit, target); + } }, release: () => { if (released) return; @@ -208,6 +234,7 @@ export async function attachDocument( detachHistory = null; target.view = null; target.storedState = null; + target.listeners.clear(); model.detach(target); }, }; diff --git a/src/editor/core/model/customDocuments.ts b/src/editor/core/model/customDocuments.ts index b82b1dd9b..58657a219 100644 --- a/src/editor/core/model/customDocuments.ts +++ b/src/editor/core/model/customDocuments.ts @@ -15,7 +15,8 @@ export interface CustomDocument { type Kinds = ReadonlyMap; export function documentLifecycle(input: EditorInput, kinds: Kinds): EditorDocumentLifecycle | undefined { - return kinds.get(input.kind)?.document; + const document = kinds.get(input.kind)?.document; + return typeof document === "function" ? document(input) : document; } /** Open custom documents by input key, in visual tab order (the first tab's input). */ diff --git a/src/features/github/data/local.ts b/src/features/github/data/local.ts index cb71b955e..46dd80ca1 100644 --- a/src/features/github/data/local.ts +++ b/src/features/github/data/local.ts @@ -196,7 +196,7 @@ export async function openInWorktree(number: number): Promise { failure: tx`Couldn't create the worktree for #${number}`, }; const added = await withBusy(op, async () => { - await call(commands.vcsAddWorktree(revs.root, path, pr.headRefOid, null)); + await call(commands.vcsAddWorktree(revs.root, path, pr.headRefOid, null, null, null)); return true; }); if (added) await executeAction("file.openInNewWindow", path); diff --git a/src/features/github/runtime.ts b/src/features/github/runtime.ts index f25cfc332..1bebfccee 100644 --- a/src/features/github/runtime.ts +++ b/src/features/github/runtime.ts @@ -22,6 +22,7 @@ import { changeRepository, headerMenu } from "./toolwindow/PullRequestsToolWindo import { contextPullRequest, resetTabs } from "./toolwindow/store"; import { activeTimelinePullRequest, openTimeline, timelineIcon, timelineTitle } from "./toolwindow/timelineInput"; import { numberDialog } from "./ui/dialogs"; +import { activateWorktreeReviews } from "./worktreeReviews"; /** The pull request an action applies to: its argument, the timeline editor, the active tab or the list selection. */ function targetPullRequest(arg: unknown): number | null { @@ -118,6 +119,7 @@ export function activate(): () => void { }), activateReviewDiff(), activateReviewMode(), + activateWorktreeReviews(), ]; const stopEditors = maybeEditorService()?.onActiveInputChange?.(() => setContext("githubTimelineActive", activeTimelinePullRequest() !== null), diff --git a/src/features/github/timeline/comments/suggestion.ts b/src/features/github/timeline/comments/suggestion.ts index 1fd3c1174..743f09768 100644 --- a/src/features/github/timeline/comments/suggestion.ts +++ b/src/features/github/timeline/comments/suggestion.ts @@ -39,7 +39,7 @@ export async function applySuggestion( const abs = `${root}/${target.path}`; const text = await call(commands.fsReadText(abs)); const { patch, start, lines } = buildSuggestionPatch(text, target, suggestion); - const outcome = await call(commands.vcsApplyPatch(connectedRoot(), patch)); + const outcome = await call(commands.vcsApplyPatch(connectedRoot(), patch, null)); const files = outcome.conflicts.join(", "); if (files) throw new Error(tx`Conflicts in ${files}`); if (commitMessage) { diff --git a/src/features/github/worktreeReviews.test.ts b/src/features/github/worktreeReviews.test.ts new file mode 100644 index 000000000..c18a82e51 --- /dev/null +++ b/src/features/github/worktreeReviews.test.ts @@ -0,0 +1,86 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { useWorktreeReviewProvider } from "@/workbench/contributions"; +import { useGhRepository, type GHConnection } from "./data/repository"; +import { activateWorktreeReviews } from "./worktreeReviews"; + +const mocks = vi.hoisted(() => ({ + remotes: vi.fn(), + config: vi.fn(), + rest: vi.fn(), + openPullRequest: vi.fn(), +})); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + commands: { + ...real.commands, + vcsRemotes: (root: string) => Promise.resolve({ status: "ok", data: mocks.remotes(root) }), + vcsConfigGet: (root: string, key: string) => Promise.resolve({ status: "ok", data: mocks.config(root, key) }), + }, + }; +}); +vi.mock("./api/client", async (importOriginal) => ({ + ...(await importOriginal()), + rest: mocks.rest, +})); +vi.mock("./toolwindow/open", () => ({ openPullRequest: mocks.openPullRequest })); + +afterEach(() => { + useGhRepository.setState({ connection: null }); + vi.resetAllMocks(); +}); + +it("opens only the review of the tracked branch from the connected worktree group", async () => { + const stop = activateWorktreeReviews(); + try { + expect(useWorktreeReviewProvider.getState().lookup).toBeNull(); + useGhRepository.setState({ + connection: { + root: "C:/repo/review", + coordinates: { owner: "org", name: "base" }, + } as GHConnection, + }); + const lookup = useWorktreeReviewProvider.getState().lookup!; + expect(await lookup({ root: "C:/unrelated", paths: [], branches: ["feature"] })).toEqual(new Map()); + expect(mocks.remotes).not.toHaveBeenCalled(); + + mocks.remotes.mockReturnValue([{ name: "origin", url: "https://github.com/org/base.git" }]); + const config: Record = { + "branch.feature.remote": "origin", + "branch.feature.merge": "refs/heads/remote-feature", + "branch.closed.remote": "origin", + "branch.closed.merge": "refs/pull/5/head", + }; + mocks.config.mockImplementation((_root, key: string) => config[key] ?? null); + mocks.rest + .mockResolvedValueOnce([ + { number: 3, title: "Different fork", state: "open", head: { repo: { full_name: "org/other" } } }, + { number: 7, title: "Matching review", state: "open", head: { repo: { full_name: "org/base" } } }, + ]) + .mockResolvedValueOnce({ number: 5, title: "Closed review", state: "closed" }); + + const reviews = await lookup({ + root: "C:/repo/main", + paths: ["c:\\repo\\review"], + branches: ["feature", "closed", "no-upstream"], + }); + expect(mocks.remotes).toHaveBeenCalledExactlyOnceWith("C:/repo/review"); + expect(mocks.rest).toHaveBeenCalledWith( + "GET", + "repos/org/base/pulls?state=open&head=org%3Aremote-feature&per_page=1", + ); + expect(mocks.rest).toHaveBeenCalledWith("GET", "repos/org/base/pulls/5"); + expect([...reviews.keys()]).toEqual(["feature"]); + expect(reviews.get("feature")?.title).toBe("Matching review"); + await reviews.get("feature")?.open(); + expect(mocks.openPullRequest).toHaveBeenCalledExactlyOnceWith(7); + useGhRepository.setState({ connection: null }); + await reviews.get("feature")?.open(); + expect(mocks.openPullRequest).toHaveBeenCalledTimes(1); + expect(useWorktreeReviewProvider.getState().lookup).toBeNull(); + } finally { + stop(); + } +}); diff --git a/src/features/github/worktreeReviews.ts b/src/features/github/worktreeReviews.ts new file mode 100644 index 000000000..7ac4e9c0e --- /dev/null +++ b/src/features/github/worktreeReviews.ts @@ -0,0 +1,89 @@ +import { call, commands } from "@/platform/ipc"; +import { ipcPath } from "@/platform/paths"; +import { useProject } from "@/platform/project"; +import { + registerWorktreeReviewProvider, + type WorktreeReview, + type WorktreeReviewQuery, +} from "@/workbench/contributions"; +import { rest } from "./api/client"; +import { sameRepository, type GHConnection, useGhRepository } from "./data/repository"; +import { openPullRequestQuery, trackedBranch } from "./reviewMode/model"; +import { openPullRequest } from "./toolwindow/open"; + +interface PullRequestMatch { + number: number; + title: string; + state: string; + head: { repo: { full_name: string } | null }; +} + +function normalizedPath(path: string) { + const normalized = ipcPath(path).replace(/\/+$/, ""); + return /^[A-Za-z]:\//.test(normalized) ? normalized.toLowerCase() : normalized; +} + +async function findReviews( + { root, paths, branches }: WorktreeReviewQuery, + connection: GHConnection, +): Promise> { + const reviews = new Map(); + const project = useProject.getState().project?.root; + const repo = connection.root ?? project; + if (!repo || ![root, ...paths].some((path) => normalizedPath(path) === normalizedPath(repo))) return reviews; + const isCurrent = () => + useGhRepository.getState().connection === connection && useProject.getState().project?.root === project; + const base = connection.coordinates; + const remotes = await call(commands.vcsRemotes(repo)); + if (!isCurrent()) return reviews; + await Promise.allSettled( + branches.map(async (branch) => { + const [remote, merge] = await Promise.all([ + call(commands.vcsConfigGet(repo, `branch.${branch}.remote`)), + call(commands.vcsConfigGet(repo, `branch.${branch}.merge`)), + ]); + const tracked = trackedBranch(remote, merge, remotes, base); + if (!tracked || !isCurrent()) return; + let match: PullRequestMatch | undefined; + if (tracked.pullRequest !== null && sameRepository(tracked.repository, base)) { + match = + (await rest( + "GET", + `repos/${base.owner}/${base.name}/pulls/${tracked.pullRequest}`, + )) ?? undefined; + } else { + const query = openPullRequestQuery(base, tracked); + if (!query) return; + const head = `${tracked.repository.owner}/${tracked.repository.name}`.toLowerCase(); + match = (await rest("GET", query))?.find( + (pr) => pr.head.repo?.full_name.toLowerCase() === head, + ); + } + if (match?.state !== "open" || !isCurrent()) return; + const { title, number } = match; + reviews.set(branch, { + title, + open: async () => { + if (isCurrent()) await openPullRequest(number); + }, + }); + }), + ); + return reviews; +} + +export function activateWorktreeReviews() { + let dispose: (() => void) | undefined; + const sync = (connection: GHConnection | null) => { + dispose?.(); + dispose = connection ? registerWorktreeReviewProvider((query) => findReviews(query, connection)) : undefined; + }; + const stop = useGhRepository.subscribe((state, previous) => { + if (state.connection !== previous.connection) sync(state.connection); + }); + sync(useGhRepository.getState().connection); + return () => { + stop(); + dispose?.(); + }; +} diff --git a/src/features/run/beforeLaunch.ts b/src/features/run/beforeLaunch.ts index bc5956673..cc2462cab 100644 --- a/src/features/run/beforeLaunch.ts +++ b/src/features/run/beforeLaunch.ts @@ -14,6 +14,7 @@ import { workflowSettings } from "@/platform/workflowSettings"; import { notifications, toolWindowService, useContributions } from "@/workbench/contributions"; import { externalToolConfig } from "./externalTools"; import { toolWindowTitle } from "@/workbench/toolwindows/title"; +import { runConfigurationToCompletion } from "./configurationChecks"; import { startRun, useRun } from "./store"; export const BUILD_ACTION = "build.buildProject"; @@ -67,7 +68,16 @@ export function taskLabel(task: BeforeLaunchTask, configs: readonly RunConfig[] } /** Runs `config` to completion: true when it exited with code 0. */ -async function runToEnd(config: RunConfig, chain: readonly string[], show?: boolean): Promise { +async function runToEnd( + config: RunConfig, + chain: readonly string[], + show?: boolean, + signal?: AbortSignal, +): Promise { + if (signal) { + const results = await runConfigurationToCompletion(config, signal, chain); + return results.every((result) => result.exitCode === 0 && !result.failedTests); + } let done!: (ok: boolean) => void; const exited = new Promise((resolve) => (done = resolve)); const session = await startRun(config, undefined, undefined, { @@ -84,6 +94,7 @@ async function runTask( config: RunConfig, chain: readonly string[], show?: boolean, + signal?: AbortSignal, ): Promise { const target = task.target ?? ""; switch (task.kind) { @@ -116,14 +127,14 @@ async function runTask( const other = useRun.getState().configs.find((c) => c.id === target); if (!other) return `Configuration '${target}' no longer exists`; if (isCMakeBuild(other)) return buildCMake(other.id, show === true); - return (await runToEnd(other, chain, show)) ? null : `'${other.name}' failed`; + return (await runToEnd(other, chain, show, signal)) ? null : `'${other.name}' failed`; } case "tool": { const tool = workflowSettings().externalTools.find((t) => t.id === target); if (!tool) return `External tool '${target}' no longer exists`; const run = await externalToolConfig(tool); if (!run) return `'${tool.name}' was not run`; - return (await runToEnd({ ...run, id: `${run.id}:before:${config.id}` }, chain, show)) + return (await runToEnd({ ...run, id: `${run.id}:before:${config.id}` }, chain, show, signal)) ? null : `'${tool.name}' failed`; } @@ -141,11 +152,11 @@ async function runTask( isTest: false, debugAdapter: null, }; - return (await runToEnd(run, chain, show)) ? null : `'${target}' failed`; + return (await runToEnd(run, chain, show, signal)) ? null : `'${target}' failed`; } case "toolWindow": { if (!useContributions.getState().toolWindows.has(target)) return `Tool window '${target}' is not available`; - toolWindowService().show(target, true); + if (!signal) toolWindowService().show(target, true); return null; } default: @@ -154,14 +165,21 @@ async function runTask( } /** The installed runner: every task in order; a failure is reported and aborts. */ -export async function runBeforeLaunch(config: RunConfig, chain: readonly string[], show?: boolean): Promise { +export async function runBeforeLaunch( + config: RunConfig, + chain: readonly string[], + show?: boolean, + signal?: AbortSignal, +): Promise { for (const task of config.beforeLaunch ?? []) { + signal?.throwIfAborted(); let error: string | null; try { - error = await runTask(task, config, chain, show); + error = await runTask(task, config, chain, show, signal); } catch (e) { error = e instanceof Error ? e.message : String(e); } + signal?.throwIfAborted(); if (error) { notifications().notify({ group: "run", diff --git a/src/features/run/configurationChecks.ts b/src/features/run/configurationChecks.ts new file mode 100644 index 000000000..6b40921f5 --- /dev/null +++ b/src/features/run/configurationChecks.ts @@ -0,0 +1,148 @@ +import type { RunConfig } from "@/bindings"; +import { useProject } from "@/platform/project"; +import { + toolWindowService, + type RunConfigurationCheckResult, + type RunConfigurationCheckService, +} from "@/workbench/contributions"; +import { isCMakeBuild } from "./cmake"; +import { compoundChildren } from "./configs"; +import { + closeSession, + loadConfigs, + prepareLaunch, + runtime, + startRun, + stopSession, + useRun, + type RunSession, +} from "./store"; +import { typeFor } from "./types"; + +function runnable(config: RunConfig) { + return !isCMakeBuild(config) && !typeFor(config.kind)?.debugOnly; +} + +function sessionOf(id: string) { + return useRun.getState().sessions.find((session) => session.id === id); +} + +function finished(session: RunSession | undefined) { + return !session || session.status === "finished" || session.status === "failed"; +} + +function waitForFinished(id: string): Promise { + const session = sessionOf(id); + if (finished(session)) return Promise.resolve(session); + return new Promise((resolve) => { + const unsubscribe = useRun.subscribe(() => { + const current = sessionOf(id); + if (!finished(current)) return; + unsubscribe(); + resolve(current); + }); + }); +} + +function showRun(id: string) { + if (!sessionOf(id)) return; + useRun.setState({ activeSession: id }); + toolWindowService().show("run", true); +} + +async function runSingle( + config: RunConfig, + signal: AbortSignal, + chain: readonly string[], +): Promise { + const name = config.name; + if (!runnable(config)) return { name, status: "notStarted" }; + let id: string | undefined; + const cancel = () => { + if (!id) return; + const session = sessionOf(id); + if (!session?.backgroundCheck) return; + if (session.runId === null) closeSession(id); + else if (!finished(session) && session.status !== "stopping") void stopSession(id); + }; + signal.addEventListener("abort", cancel, { once: true }); + try { + const started = await startRun(config, undefined, undefined, { + show: false, + chain, + check: { + signal, + own: (sessionId) => { + id = sessionId; + if (signal.aborted) cancel(); + }, + }, + }); + signal.throwIfAborted(); + if (!started) return { name, status: "notStarted" }; + const session = await waitForFinished(started.id); + signal.throwIfAborted(); + if (!session) return { name, status: "stopped" }; + const review = () => showRun(session.id); + if (session.stopped) return { name, status: "stopped", review }; + if (session.status === "failed") return { name, status: "notStarted", review }; + const failedTests = runtime(session.id)?.tests?.counts().failed ?? 0; + if (session.exitCode === 0 && failedTests === 0) { + closeSession(session.id); + return { name, status: "finished", exitCode: 0 }; + } + return { name, status: "finished", exitCode: session.exitCode, failedTests, review }; + } finally { + signal.removeEventListener("abort", cancel); + if (signal.aborted && id) { + await waitForFinished(id); + if (sessionOf(id)?.backgroundCheck) closeSession(id); + } + } +} + +export async function runConfigurationToCompletion( + config: RunConfig, + signal: AbortSignal, + chain: readonly string[] = [], +): Promise { + signal.throwIfAborted(); + if (config.kind !== "compound") return [await runSingle(config, signal, chain)]; + const children = compoundChildren(config, useRun.getState().configs); + if (!children.length || !(await prepareLaunch(config, chain, false, signal))) + return [{ name: config.name, status: "notStarted" }]; + const results: RunConfigurationCheckResult[] = []; + for (const child of children) { + results.push(await runSingle(child, signal, [...chain, config.id])); + signal.throwIfAborted(); + } + return results; +} + +let source: readonly RunConfig[] | undefined; +let options: readonly RunConfig[] = []; + +export const configurationChecks: RunConfigurationCheckService = { + configurations() { + const { configs } = useRun.getState(); + if (configs !== source) { + source = configs; + options = configs.filter(runnable); + } + return options; + }, + subscribe(listener) { + return useRun.subscribe((state, previous) => { + if (state.configs !== previous.configs) listener(); + }); + }, + async run(id, signal) { + const project = useProject.getState().project; + if (!project?.trusted) return []; + if (!useRun.getState().loaded) await loadConfigs(); + signal.throwIfAborted(); + if (useProject.getState().project !== project) return []; + const config = this.configurations().find((candidate) => candidate.id === id); + return config ? runConfigurationToCompletion(config, signal) : []; + }, +}; diff --git a/src/features/run/index.ts b/src/features/run/index.ts index 4a562d8f8..e4b2415c1 100644 --- a/src/features/run/index.ts +++ b/src/features/run/index.ts @@ -14,6 +14,7 @@ import { menuGroupItems, useDebugRunSessions, notifications, + provideRunConfigurationChecks, provideRunConfigurationLookup, provideRunOutput, registerMenuGroup, @@ -60,6 +61,7 @@ import { import { liveServiceSession, serviceSessions } from "./serviceSessions"; import { ServiceImportHost } from "./serviceImport"; import { cmakeBuildId } from "./cmake"; +import { configurationChecks } from "./configurationChecks"; import { runBeforeLaunch } from "./beforeLaunch"; import { compoundChildren } from "./configs"; import { containerDebuggable, remoteDebugBlocked } from "./remote"; @@ -922,6 +924,8 @@ export function activate(): () => void { setBeforeLaunchRunner(runBeforeLaunch); disposers.push(() => setBeforeLaunchRunner(null)); + provideRunConfigurationChecks(configurationChecks); + disposers.push(() => provideRunConfigurationChecks(undefined)); provideRunOutput({ subscribe: subscribeOutput }); disposers.push(() => provideRunOutput(undefined)); provideRunConfigurationLookup((kind, directory) => { diff --git a/src/features/run/store.ts b/src/features/run/store.ts index 29177ba35..dca080e99 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -100,6 +100,8 @@ export interface RunSession { httpPort?: number; /** Pinned tab: once finished, a later run opens a new tab instead of taking its place. */ pinned?: boolean; + /** Commit checks own these tabs so their output stays available for review. */ + backgroundCheck?: boolean; } interface SessionRuntime { @@ -754,7 +756,12 @@ function newRuntime(config: RunConfig): SessionRuntime { } /** Runs a configuration's before launch tasks; false aborts the launch. Installed by the feature. */ -export type BeforeLaunchRunner = (config: RunConfig, chain: readonly string[], show?: boolean) => Promise; +export type BeforeLaunchRunner = ( + config: RunConfig, + chain: readonly string[], + show?: boolean, + signal?: AbortSignal, +) => Promise; let beforeLaunch: BeforeLaunchRunner | null = null; export function setBeforeLaunchRunner(runner: BeforeLaunchRunner | null) { @@ -766,9 +773,12 @@ export async function prepareLaunch( config: RunConfig, chain: readonly string[] = [], show?: boolean, + signal?: AbortSignal, ): Promise { + signal?.throwIfAborted(); if (!config.beforeLaunch?.length || !beforeLaunch) return true; - return beforeLaunch(config, [...chain, config.id], show); + const next = [...chain, config.id]; + return signal ? beforeLaunch(config, next, show, signal) : beforeLaunch(config, next, show); } /** Starts every configuration of a compound (after the compound's own before launch tasks). */ @@ -798,7 +808,7 @@ export function sessionsOf(config: RunConfig, sessions = useRun.getState().sessi * Agents' commands keep to their own tabs. */ function reusableTab(sessions: readonly RunSession[], active: string | null, config: RunConfig) { - const free = sessions.filter((s) => !isLive(s) && !s.pinned && !claimedTabs.has(s.id)); + const free = sessions.filter((s) => !isLive(s) && !s.pinned && !s.backgroundCheck && !claimedTabs.has(s.id)); const same = free.find((s) => s.config.id === config.id); if (same || agentName(config) !== null) return same; const others = free.filter((s) => agentName(s.config) === null); @@ -827,6 +837,7 @@ interface StartRunOptions { chain?: readonly string[]; /** Runs before the stop signal when the user stops this run (run executors). */ beforeStop?: (runId: RunId) => Promise; + check?: { signal: AbortSignal; own: (sessionId: string) => void }; } /** Starts `config`, reusing the tab of a finished (or the given) session (see `reusableTab`). */ @@ -851,13 +862,16 @@ async function startRunIn( baseConfig: RunConfig | undefined, options: StartRunOptions, ): Promise { + const check = options.check; + check?.signal.throwIfAborted(); config = withRunTarget(config); try { config = await withExpandedCwd(config); } catch (e) { - notifyCwdError(config, e); + if (!check) notifyCwdError(config, e); return null; } + check?.signal.throwIfAborted(); if (!options.launch && isCMakeBuild(config)) { await buildCMake(config.id, options.show !== false); return null; @@ -878,7 +892,13 @@ async function startRunIn( }); return null; } - if (!options.launch && !options.prepared && !(await prepareLaunch(config, options.chain, options.show))) return null; + if ( + !options.launch && + !options.prepared && + !(await prepareLaunch(config, options.chain, options.show, check?.signal)) + ) + return null; + check?.signal.throwIfAborted(); const state = useRun.getState(); const busy = (s: RunSession) => isLive(s); let session = reuse ? state.sessions.find((s) => s.id === reuse) : undefined; @@ -889,10 +909,11 @@ async function startRunIn( : state.sessions.filter((s) => s.config.id === config.id && busy(s) && s.id !== session?.id); const debugging = config.allowParallel ? [] : liveDebugSessions(config.id); if (others.length || debugging.length) { + if (check) return null; const instances = others.length + debugging.length + (session && busy(session) ? 1 : 0); if (workflowSettings().run.confirmRerun && !(await confirmRerun(config.name, instances))) return null; await Promise.all([...others.map((s) => stopSession(s.id)), ...debugging.map((d) => d.stop())]); - session ??= others[0]; + session ??= others.find((item) => !item.backgroundCheck); } const stopping = others.map((s) => s.id); if (session && busy(session)) { @@ -903,7 +924,7 @@ async function startRunIn( // IDEA there is no time limit: a first Stop waits for the shutdown, a second one kills it. await waitForExit(stopping, null); const now = useRun.getState(); - const picked = session ? undefined : reusableTab(now.sessions, now.activeSession, config); + const picked = session || check ? undefined : reusableTab(now.sessions, now.activeSession, config); session ??= picked; if (picked) claimedTabs.add(picked.id); @@ -915,6 +936,14 @@ async function startRunIn( if (picked) claimedTabs.delete(picked.id); } + check?.signal.throwIfAborted(); + if ( + check && + !config.allowParallel && + (useRun.getState().sessions.some((s) => s.config.id === config.id && isLive(s)) || + liveDebugSessions(config.id).length) + ) + return null; const startedAt = Date.now(); if (session) { const prev = runtimes.get(session.id); @@ -934,6 +963,7 @@ async function startRunIn( stdinClosed: false, stopped: false, httpPort: undefined, + backgroundCheck: undefined, }; const updated = session; useRun.setState((s) => ({ @@ -951,22 +981,28 @@ async function startRunIn( endedAt: null, stdinClosed: false, baseConfig, - pinned: workflowSettings().run.pinTabs || undefined, + pinned: check ? undefined : workflowSettings().run.pinTabs || undefined, + backgroundCheck: !!check || undefined, }; runtimes.set(session.id, newRuntime(config)); const created = session; - useRun.setState((s) => ({ sessions: [...s.sessions, created], activeSession: created.id })); + useRun.setState((s) => ({ + sessions: [...s.sessions, created], + activeSession: check ? s.activeSession : created.id, + })); } bump(session.id); const sessionId = session.id; const rt = runtimes.get(sessionId)!; const generation = rt.generation; + check?.own(sessionId); + check?.signal.throwIfAborted(); if (options.onLine) rt.lineListeners.push(options.onLine); let browserOpened = false; rt.lineListeners.push((line) => { if (config.kind === "tomcat" && /Server startup in/.test(line)) { patchSession(sessionId, { httpPort: Number(config.params?.httpPort || "8080") }); - if (!browserOpened && config.params?.openBrowser === "true") { + if (!check && !browserOpened && config.params?.openBrowser === "true") { browserOpened = true; void openUrl(tomcatBrowserUrl(config)); } @@ -996,7 +1032,10 @@ async function startRunIn( channel.onmessage = (chunk) => { if (runtimes.get(sessionId)?.generation !== generation) return; enqueue(sessionId, chunk); - if ((chunk.kind === "stdout" && config.showOnStdout) || (chunk.kind === "stderr" && config.showOnStderr)) + if ( + !check && + ((chunk.kind === "stdout" && config.showOnStdout) || (chunk.kind === "stderr" && config.showOnStderr)) + ) revealSession(sessionId); }; try { @@ -1022,7 +1061,7 @@ async function startRunIn( const prepare = typeFor(launch.kind)?.prepareLaunch; if (prepare) { launch = await prepare(launch); - if (launch.kind === "tomcat") useRun.setState({ activeSession: sessionId }); + if (!check && launch.kind === "tomcat") useRun.setState({ activeSession: sessionId }); if (runtimes.get(sessionId)?.generation !== generation) return getSession(sessionId) ?? null; } // Debug launches read the agent's output lines: never through a terminal. @@ -1074,17 +1113,22 @@ async function startRunIn( finishSession(sessionId, exited); } } catch (e) { - if (getSession(sessionId)?.stopped || isCancelled(e)) return getSession(sessionId) ?? null; + if (getSession(sessionId)?.stopped) return getSession(sessionId) ?? null; + if (isCancelled(e)) { + if (check && runtimes.get(sessionId) === rt) patchSession(sessionId, { status: "failed", endedAt: Date.now() }); + return getSession(sessionId) ?? null; + } const message = e instanceof Error ? e.message : String(e); enqueue(sessionId, { kind: "stderr", text: tx`Error running '${config.name}': ${message}\n` }); flush(sessionId); patchSession(sessionId, { status: "failed", endedAt: Date.now() }); - notifications().notify({ - group: "run", - level: "error", - title: `Error running '${remoteLabel(config)}'`, - ...buildToolRecovery(message), - }); + if (!check) + notifications().notify({ + group: "run", + level: "error", + title: `Error running '${remoteLabel(config)}'`, + ...buildToolRecovery(message), + }); } return getSession(sessionId) ?? null; } @@ -1212,7 +1256,7 @@ function finishSession(sessionId: string, code: number | null) { } patchSession(sessionId, { status: "finished", exitCode: code, endedAt: Date.now() }); bump(sessionId); - notifyExit(sessionId, code); + if (!session.backgroundCheck) notifyExit(sessionId, code); try { rt.onExit?.(code, !!getSession(sessionId)?.stopped); } catch (e) { diff --git a/src/features/settings/__tests__/todoVimStaging.test.tsx b/src/features/settings/__tests__/todoVimStaging.test.tsx index d8ad056c3..a3b4f6dcd 100644 --- a/src/features/settings/__tests__/todoVimStaging.test.tsx +++ b/src/features/settings/__tests__/todoVimStaging.test.tsx @@ -1,8 +1,8 @@ import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { DEFAULT_TODO_SETTINGS } from "@/features/todo/model"; +import { DEFAULT_TODO_SETTINGS } from "@/platform/todo"; import { activateSettingsPages as activateTodoSettings } from "@/features/todo/settingsPages"; -import { useTodoSettings } from "@/features/todo/store"; +import { useTodoSettings } from "@/platform/todo"; import { DEFAULT_VIM_SETTINGS, useVimSettings, VIM_SETTINGS_KEY } from "@/features/vim/settings"; import { activateSettingsPages as activateVimSettings } from "@/features/vim/settingsPages"; import type { Settings } from "@/platform/ipc"; diff --git a/src/features/settings/pages/GitSettings.module.css b/src/features/settings/pages/GitSettings.module.css index 3b6b5a583..60abe2b96 100644 --- a/src/features/settings/pages/GitSettings.module.css +++ b/src/features/settings/pages/GitSettings.module.css @@ -20,6 +20,22 @@ width: 100%; } +.signingForm { + gap: var(--space-2); + padding: var(--space-1) var(--space-4) var(--space-2); + overflow-wrap: anywhere; +} + +.signingPicker { + width: 100%; +} + +.signingRoot, +.signingHint { + color: var(--fg-muted); + overflow-wrap: anywhere; +} + .updateMethods { display: flex; flex-wrap: wrap; diff --git a/src/features/settings/pages/GitSigningRow.tsx b/src/features/settings/pages/GitSigningRow.tsx new file mode 100644 index 000000000..4fd2105c3 --- /dev/null +++ b/src/features/settings/pages/GitSigningRow.tsx @@ -0,0 +1,263 @@ +import { useEffect, useId, useState } from "react"; +import { tx } from "@/platform/i18n"; +import { + call, + commands, + isTauri, + nextRequestId, + type GitSigningConfig, + type GpgSigningKey, + type VcsRoot, +} from "@/platform/ipc"; +import { basename, useProject } from "@/platform/project"; +import { Button, Dialog, Select, type SelectOption, T } from "@/ui"; +import { FormGroup, Row, Toggle } from "../components/Form"; +import { useSettingsDialog } from "../model/staging"; +import styles from "./GitSettings.module.css"; +import workflow from "./Workflow.module.css"; + +export function GitSigningRow() { + const project = useProject((s) => s.project); + const newProjects = useSettingsDialog((s) => s.newProjects); + const [open, setOpen] = useState(false); + const canConfigure = !!project?.trusted && !newProjects && isTauri(); + + return ( + + + {open && canConfigure && ( + setOpen(false)} /> + )} + + ); +} + +function SigningDialog({ projectRoot, onClose }: { projectRoot: string; onClose: () => void }) { + const [roots, setRoots] = useState(); + const [repo, setRepo] = useState(); + const [error, setError] = useState(); + useEffect(() => { + let live = true; + void call(commands.vcsRoots()).then( + (roots) => { + if (!live) return; + setRoots(roots); + setRepo(roots.find((root) => root.root === projectRoot)?.root ?? roots[0]?.root); + }, + (error: unknown) => live && setError(message(error)), + ); + return () => { + live = false; + }; + }, [projectRoot]); + + if (roots && repo) { + return ; + } + return ( + Configure GPG Signature} + onClose={onClose} + buttons={[{ label: "Close", role: "cancel" }]} + > +
+ {error ? ( +
+ {error} +
+ ) : roots ? ( + No Git repositories are configured for this project. + ) : ( + + Loading… + + )} +
+ + ); +} + +function RepositorySigning({ + repo, + roots, + onChooseRepo, + onClose, +}: { + repo: string; + roots: VcsRoot[]; + onChooseRepo: (repo: string) => void; + onClose: () => void; +}) { + const rootId = useId(); + const keyId = useId(); + const [initial, setInitial] = useState(); + const [enabled, setEnabled] = useState(false); + const [key, setKey] = useState(null); + const [keys, setKeys] = useState(); + const [keysError, setKeysError] = useState(); + const [error, setError] = useState(); + const [saving, setSaving] = useState(false); + + useEffect(() => { + let live = true; + let request: ReturnType | undefined; + void call(commands.vcsSigningConfig(repo)).then( + (config) => { + if (!live) return; + setInitial(config); + setEnabled(config.enabled); + setKey(config.key); + if (config.format !== "openpgp") return; + request = nextRequestId(); + void call(commands.vcsGpgSigningKeys(repo, request)) + .then( + (keys) => live && setKeys(keys), + (error: unknown) => live && setKeysError(message(error)), + ) + .finally(() => { + request = undefined; + }); + }, + (error: unknown) => live && setError(message(error)), + ); + return () => { + live = false; + if (request !== undefined) void commands.cancelRequest(request).catch(() => undefined); + }; + }, [repo]); + + const supported = initial?.format === "openpgp"; + const changedEnabled = initial && enabled !== initial.enabled; + const changedKey = enabled && key !== initial?.key; + const dirty = changedEnabled || changedKey; + const options: SelectOption[] = (keys ?? []).map((key) => ({ + value: key.fingerprint, + label: key.userId || key.fingerprint, + verbatim: true, + detail: key.userId ? key.fingerprint : undefined, + verbatimDetail: true, + })); + if (initial?.key && !options.some((option) => option.value === initial.key)) { + options.unshift({ value: initial.key, label: initial.key, verbatim: true }); + } + + async function save() { + if (!supported || !dirty || saving || (enabled && !key)) return; + setSaving(true); + setError(undefined); + try { + await call( + commands.vcsEditSigning(repo, { enabled: changedEnabled ? enabled : null, key: changedKey ? key : null }), + ); + onClose(); + } catch (error) { + setError(message(error)); + } finally { + setSaving(false); + } + } + + return ( + Configure GPG Signature
} + onClose={() => { + if (!saving) onClose(); + }} + width={540} + buttons={[ + { + label: "OK", + role: "default", + disabled: !supported || !dirty || saving || (enabled && !key), + onClick: () => void save(), + }, + { label: "Cancel", role: "cancel", disabled: saving }, + ]} + > + + {roots.length > 1 ? ( + + + + {dirty && ( +
+ Changes are saved to this repository's Git config. +
+ )} + + ) : ( + {tx`This repository uses ${initial.format} signing.`} + ) + ) : !error ? ( + + Loading… + + ) : null} + {error && ( +
+ {error} +
+ )} +
+ + ); +} + +function message(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/src/features/settings/pages/vcs.tsx b/src/features/settings/pages/vcs.tsx index c3c5a9928..f758c2cb5 100644 --- a/src/features/settings/pages/vcs.tsx +++ b/src/features/settings/pages/vcs.tsx @@ -25,11 +25,12 @@ import { import { choosePath } from "@/platform/choosePath"; import { Row, SearchLabel, SettingSelect } from "../components/Form"; import { useSetting } from "../components/context"; -import type { AgentModelCatalog, AgentProvider } from "@/bindings"; +import type { AgentModelCatalog, AgentProvider, FetchTagsMode } from "@/bindings"; import type { PageSpec } from "./spec"; -import { BoundToggle, Grid, Indented, TableEditor, ToggleNumber } from "./workflowControls"; +import { BoundToggle, Grid, Indented, RadioRow, TableEditor, ToggleNumber } from "./workflowControls"; import styles from "./Workflow.module.css"; import gitStyles from "./GitSettings.module.css"; +import { GitSigningRow } from "./GitSigningRow"; import { tx } from "@/platform/i18n"; const L = WORKFLOW_LIMITS; @@ -484,9 +485,17 @@ const PATCH_CREATED: SelectOption[] = [ const INCOMING: SelectOption[] = [ { value: "auto", label: "Auto" }, { value: "always", label: "Always" }, + { value: "check", label: "Check without fetching" }, { value: "never", label: "Never" }, ]; +const FETCH_TAGS: SelectOption[] = [ + { value: "auto", label: "Auto", detail: "Follow Git config" }, + { value: "sync", label: "Sync", detail: "Delete local tags missing on remote" }, + { value: "always", label: "Always", detail: "Fetch all remote tags" }, + { value: "never", label: "Never", detail: "Disable automatic tag fetching" }, +]; + // --------------------------------------------------------------------------- // Commit @@ -653,6 +662,7 @@ function AgentInstructionsRow() { } function CommitChecks() { + const [nonModal] = useSetting("vcs.commit.nonModal"); return ( + } /> @@ -747,6 +763,23 @@ function IssuePresets() { export const VCS_PAGES: PageSpec[] = [ // No sections: the page links to its sub-pages. { id: "vcs", title: "Version Control", order: 300, keywords: ["git", "vcs", "history"] }, + { + id: "vcs.changelists", + title: "Changelists", + order: 0, + keywords: ["cherry-pick", "revert", "local changes", "conflict"], + sections: [ + { + options: [ + { + kind: "toggle", + key: "vcs.createChangelistsAutomatically", + label: "Create changelists for conflicted cherry-picks and reverts", + }, + ], + }, + ], + }, { id: "vcs.commit", title: "Commit", @@ -910,6 +943,25 @@ export const VCS_PAGES: PageSpec[] = [ keywords: ["Test", "git version"], component: GitExecutableRow, }, + { + kind: "custom", + label: "Recursively clone submodules", + keywords: ["clone", "submodules"], + component: () => ( + Applies to all projects.
} + scope="global" + /> + ), + }, + { + kind: "custom", + label: "GPG signing", + keywords: ["Configure GPG Signature…", "Signing key", "Sign commits with GPG"], + component: GitSigningRow, + }, { kind: "custom", label: "Show inline blame for the current line", @@ -961,6 +1013,29 @@ export const VCS_PAGES: PageSpec[] = [ key: "vcs.git.warnBadFileNames", label: "Warn when committing files with names that might cause issues on other systems", }, + { + kind: "toggle", + key: "vcs.git.addCherryPickOrigin", + label: "Record the source of cherry-picked commits from protected branches", + hint: "Adds the source commit hash to the commit message.", + }, + { + kind: "custom", + label: "On empty cherry-pick", + keywords: ["Skip commit", "Create empty commit"], + component: () => ( + Applies to all projects.
} + scope="global" + choices={[ + { value: "skip", label: "Skip commit" }, + { value: "createEmpty", label: "Create empty commit" }, + ]} + /> + ), + }, { kind: "toggle", key: "vcs.git.signOff", @@ -995,16 +1070,31 @@ export const VCS_PAGES: PageSpec[] = [ keywords: ["Merge", "Rebase", "pull"], component: GitUpdateMethodRow, }, + { + kind: "custom", + label: "Clean working tree using", + keywords: ["Shelve", "Stash", "Smart Checkout"], + component: () => ( + + ), + }, { kind: "custom", label: "Explicitly check for incoming commits on remotes", - keywords: ["Auto", "Always", "Never", "fetch"], + keywords: ["Auto", "Always", "Never", "fetch", "check remote refs"], component: () => ( ), }, @@ -1016,6 +1106,12 @@ export const VCS_PAGES: PageSpec[] = [ integer: true, unit: "min", }, + { + kind: "custom", + label: "Fetch tags", + keywords: ["Auto", "Sync", "Always", "Never", "prune"], + component: () => , + }, ], }, { @@ -1033,6 +1129,23 @@ export const VCS_PAGES: PageSpec[] = [ title: "Stash", options: [ { kind: "toggle", key: "vcs.git.combineStashAndShelf", label: "Combine stashes and shelves in one tab" }, + { + kind: "custom", + label: "Compare stashed changes when showing a diff", + keywords: ["With the local version of a file", "With the parent commit"], + component: () => ( + Applies to all projects.
} + scope="global" + choices={[ + { value: "local", label: "With the local version of a file" }, + { value: "parent", label: "With the parent commit" }, + ]} + /> + ), + }, ], }, ], diff --git a/src/features/settings/pages/workflowControls.tsx b/src/features/settings/pages/workflowControls.tsx index c47bec5d4..29f127617 100644 --- a/src/features/settings/pages/workflowControls.tsx +++ b/src/features/settings/pages/workflowControls.tsx @@ -3,12 +3,12 @@ * pages: bound checkboxes, "[x] Limit … to: [N] unit" rows, * two-column grids, string lists and editable two-column tables. */ -import { useState, type KeyboardEvent, type ReactNode } from "react"; +import { useId, useState, type KeyboardEvent, type ReactNode } from "react"; import clsx from "clsx"; import { Checkbox, IconButton, Input } from "@/ui"; -import { NumberInput, SearchLabel, Toggle } from "../components/Form"; +import { NumberInput, Row, SearchLabel, Toggle } from "../components/Form"; import { useLabelMatch, useSetting } from "../components/context"; -import { selectPage } from "../model/staging"; +import { selectPage, type Scope } from "../model/staging"; import styles from "./Workflow.module.css"; export function BoundToggle({ @@ -16,13 +16,15 @@ export function BoundToggle({ label, hint, disabled, + scope, }: { k: string; label: string; hint?: ReactNode; disabled?: boolean; + scope?: Scope; }) { - const [value, set] = useSetting(k); + const [value, set] = useSetting(k, scope); return ; } @@ -89,6 +91,41 @@ export function ToggleNumber({ ); } +export interface RadioChoice { + value: V; + label: string; +} + +/** `Label: (•) A ( ) B ( ) C` bound to a key. */ +export function RadioRow({ + k, + label, + choices, + hint, + scope, +}: { + k: string; + label: string; + choices: readonly RadioChoice[]; + hint?: ReactNode; + scope?: Scope; +}) { + const [value, set] = useSetting(k, scope); + const name = useId(); + return ( + +
+ {choices.map((c) => ( + + ))} +
+
+ ); +} + /** Link-style button that jumps to another settings page. */ export function PageLink({ page, children }: { page: string; children: ReactNode }) { return ( diff --git a/src/features/todo/PreviewEditor.test.tsx b/src/features/todo/PreviewEditor.test.tsx index a274b6207..86c8a216d 100644 --- a/src/features/todo/PreviewEditor.test.tsx +++ b/src/features/todo/PreviewEditor.test.tsx @@ -21,6 +21,8 @@ function stubAttacher(docs: Map null, context: () => ({ doc: 1, path, language: "plaintext", uiMode: null, readOnly: !!docs.get(path)!.readOnly }), readOnly: !!docs.get(path)!.readOnly, + subscribeReadOnly: () => () => {}, + subscribeExternalChanges: () => () => {}, editorState: () => null, dispatchTransactions: (trs, view) => view.update(trs), extension: EditorView.updateListener.of((u) => { diff --git a/src/features/todo/TodoSettingsPage.module.css b/src/features/todo/TodoSettingsPage.module.css index 5cb0f0894..7cdf80409 100644 --- a/src/features/todo/TodoSettingsPage.module.css +++ b/src/features/todo/TodoSettingsPage.module.css @@ -32,6 +32,25 @@ .keyword { width: 120px; } +.filterName { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.empty { + padding: var(--space-1) var(--space-2); + color: var(--fg-muted); +} +.filterPatterns { + display: flex; + flex-direction: column; + gap: var(--space-1); + min-width: 0; + padding: var(--space-2); + border: 1px solid var(--border-strong); + border-radius: var(--radius-small); +} .swatch { width: 10px; height: 10px; diff --git a/src/features/todo/TodoSettingsPage.tsx b/src/features/todo/TodoSettingsPage.tsx index 771d59bfe..b448e62a1 100644 --- a/src/features/todo/TodoSettingsPage.tsx +++ b/src/features/todo/TodoSettingsPage.tsx @@ -1,8 +1,14 @@ /** Settings › Editor › TODO: patterns, colours, matching options. */ -import { Button, Checkbox, IconButton, Input, Select, T } from "@/ui"; +import { useState } from "react"; +import { Button, Checkbox, Dialog, IconButton, Input, Select, T } from "@/ui"; import { useSettingsForm } from "@/workbench/contributions"; -import { DEFAULT_PATTERNS, type TodoPattern } from "./model"; -import { updateTodoSettings, useTodoSettings } from "./store"; +import { + DEFAULT_PATTERNS, + updateTodoSettings, + useTodoSettings, + type TodoFilter, + type TodoPattern, +} from "@/platform/todo"; import styles from "./TodoSettingsPage.module.css"; import { tx } from "@/platform/i18n"; @@ -15,9 +21,86 @@ const COLORS = [ { value: "var(--fg-muted)", label: "Grey" }, ]; +function TodoFilterDialog({ + filter, + filters, + patterns, + onClose, + onSave, +}: { + filter: TodoFilter; + filters: readonly TodoFilter[]; + patterns: readonly TodoPattern[]; + onClose: () => void; + onSave: (filter: TodoFilter) => void; +}) { + const [name, setName] = useState(filter.name); + const [selected, setSelected] = useState(() => new Set(filter.patternIds)); + const available = patterns.filter(({ keyword }) => keyword.trim()); + const patternIds = available.filter(({ id }) => selected.has(id)).map(({ id }) => id); + const trimmed = name.trim(); + const duplicate = filters.some((candidate) => candidate.id !== filter.id && candidate.name === trimmed); + return ( + onSave({ ...filter, name: trimmed, patternIds }), + }, + { role: "cancel", label: "Cancel" }, + ]} + > +
+ setName(event.currentTarget.value)} + placeholder="Filter name" + aria-label="Filter name" + data-autofocus + /> + {duplicate && ( + + A TODO filter with this name already exists. + + )} +
+ + Patterns + + {available.map(({ id, keyword }) => ( + {keyword}} + checked={selected.has(id)} + onChange={(checked) => { + const next = new Set(selected); + if (checked) next.add(id); + else next.delete(id); + setSelected(next); + }} + /> + ))} +
+ {!patternIds.length && ( + + Select at least one TODO pattern. + + )} +
+
+ ); +} + export function TodoSettingsPage() { const form = useSettingsForm(); const saved = useTodoSettings(); + const [editingFilter, setEditingFilter] = useState(null); const caseSensitive = form.useExternal("caseSensitive", saved.caseSensitive, async (value) => { updateTodoSettings({ caseSensitive: value }); return value; @@ -30,6 +113,19 @@ export function TodoSettingsPage() { updateTodoSettings({ patterns: value }); return value; }); + const { value: filters, set: setFilters } = form.useExternal("filters", saved.filters, async (value) => { + updateTodoSettings({ filters: value }); + return value; + }); + const replacePatterns = (next: TodoPattern[]) => { + setPatterns(next); + const valid = new Set(next.map(({ id }) => id)); + const updated = filters.map((filter) => { + const patternIds = filter.patternIds.filter((id) => valid.has(id)); + return patternIds.length === filter.patternIds.length ? filter : { ...filter, patternIds }; + }); + if (updated.some((filter, index) => filter !== filters[index])) setFilters(updated); + }; const patch = (id: string, p: Partial) => setPatterns(patterns.map((x) => (x.id === id ? { ...x, ...p } : x))); @@ -81,16 +177,66 @@ export function TodoSettingsPage() { icon="trash" size="small" title="Remove Pattern" - onClick={() => setPatterns(patterns.filter((x) => x.id !== p.id))} + onClick={() => replacePatterns(patterns.filter((x) => x.id !== p.id))} /> ))}
-
+
+ + Filters + + keyword.trim())} + onClick={() => setEditingFilter({ id: crypto.randomUUID(), name: "", patternIds: [] })} + /> +
+
+ {!filters.length && ( +
+ No TODO filters +
+ )} + {filters.map((filter) => ( +
+ + {filter.name} + + setEditingFilter(filter)} /> + setFilters(filters.filter(({ id }) => id !== filter.id))} + /> +
+ ))} +
+ {editingFilter && ( + setEditingFilter(null)} + onSave={(filter) => { + setFilters( + editingFilter.name + ? filters.map((existing) => (existing.id === filter.id ? filter : existing)) + : [...filters, filter], + ); + setEditingFilter(null); + }} + /> + )} ); } diff --git a/src/features/todo/TodoView.module.css b/src/features/todo/TodoView.module.css index a6582a12d..ee4c4502e 100644 --- a/src/features/todo/TodoView.module.css +++ b/src/features/todo/TodoView.module.css @@ -41,6 +41,37 @@ color: var(--warning); border-bottom: 1px solid var(--border); } +.skippedSummary, +.skippedOnly { + padding: var(--space-2) var(--space-3); + overflow: auto; +} +.skippedSummary { + max-block-size: 45%; + border-bottom: 1px solid var(--border); +} +.skippedSummary summary { + cursor: pointer; +} +.skippedOnly h3 { + margin: 0; + font: inherit; + font-weight: 600; +} +.skippedFiles { + margin: var(--space-2) 0 0; + padding-inline-start: calc(var(--space-4) + var(--space-1)); + overflow-wrap: anywhere; +} +.skippedFiles li + li { + margin-top: var(--space-2); +} +.skippedFiles li > * { + display: block; +} +.skipDetail { + color: var(--fg-muted); +} .scopeBar { flex: none; display: flex; diff --git a/src/features/todo/TodoView.tsx b/src/features/todo/TodoView.tsx index 719c2b54a..18417f4ee 100644 --- a/src/features/todo/TodoView.tsx +++ b/src/features/todo/TodoView.tsx @@ -1,19 +1,21 @@ /** TODO tool window: "Project", "Current File", "Scope Based" and "Changes" tabs, grouped by file. */ -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { create } from "zustand"; import { useShallow } from "zustand/react/shallow"; import clsx from "clsx"; import { openEditorPaths, useEditorRegistry } from "@/editor/api"; +import { previewColors } from "@/editor/lineTokens"; import { executeAction } from "@/platform/actions"; import { basename, relativeDir, useProject } from "@/platform/project"; import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search"; -import { editorService, useLocalChanges, useOccurrenceNavigator } from "@/workbench/contributions"; +import { editorService, toolWindowService, useLocalChanges, useOccurrenceNavigator } from "@/workbench/contributions"; import { EmptyState, Icon, IconButton, Menu, Select, + SourcePreview, SplitGroup, SplitHandle, SplitPanel, @@ -31,21 +33,45 @@ import { previewText } from "./ipc"; import { PreviewEditor } from "./PreviewEditor"; import { BUILTIN_TODO_SCOPES, - activePatterns, changedPaths, countItems, groupTodos, mergeLive, todoSearchScope, type TodoGroup, - type TodoItem, type TodoScope, } from "./model"; -import { scanProject, scanScope, updateTodoSettings, useTodoSettings, useTodos } from "./store"; +import { + activePatterns, + todoFilterKeywords, + updateTodoSettings, + useTodoSettings, + type TodoItem, +} from "@/platform/todo"; +import { setTodoFilterSelection, useTodoFilterSelection } from "@/platform/todoFilterSelection"; +import { editTodoFiltersItem, todoFilterChoices } from "@/workbench/todoFilterMenu"; +import { + provideTodoReview, + type TodoReview, + type TodoReviewFile, + type TodoReviewSkippedFile, +} from "@/workbench/todoReview"; +import { scanProject, scanScope, useTodos } from "./store"; import styles from "./TodoView.module.css"; import { tx } from "@/platform/i18n"; -type Tab = "project" | "file" | "scope" | "changes"; +type ScopeTab = "project" | "file" | "scope" | "changes"; +type ReviewId = `review:${number}`; +type Tab = ScopeTab | ReviewId; + +interface ReviewTab { + id: ReviewId; + review: TodoReview; +} + +function isReviewId(tab: Tab): tab is ReviewId { + return tab.startsWith("review:"); +} const SCOPE_KEY = "openidea.todo.scope.v1"; @@ -60,7 +86,9 @@ function loadScope(): TodoScope { } interface ViewState { - tab: Tab; + tab: ScopeTab; + activeReview: ReviewId | null; + reviewTabs: ReviewTab[]; /** Hidden keywords (filter). */ hidden: string[]; collapsed: Set; @@ -68,7 +96,7 @@ interface ViewState { scope: TodoScope; /** The Changes tab's change list (null: the active one). */ changelist: string | null; - setTab(tab: Tab): void; + setTab(tab: ScopeTab): void; setScope(scope: TodoScope): void; toggleKeyword(k: string): void; showAll(): void; @@ -76,11 +104,13 @@ interface ViewState { export const useTodoView = create((set) => ({ tab: "project", + activeReview: null, + reviewTabs: [], hidden: [], collapsed: new Set(), scope: loadScope(), changelist: null, - setTab: (tab) => set({ tab }), + setTab: (tab) => set({ tab, activeReview: null }), setScope: (scope) => { set({ scope }); try { @@ -94,6 +124,42 @@ export const useTodoView = create((set) => ({ showAll: () => set({ hidden: [] }), })); +let reviewSequence = 0; + +function closeReview(id: string) { + useTodoView.setState((state) => { + const at = state.reviewTabs.findIndex((tab) => tab.id === id); + if (at === -1) return state; + const reviewTabs = state.reviewTabs.filter((tab) => tab.id !== id); + return { + reviewTabs, + activeReview: + state.activeReview === id ? (reviewTabs[Math.min(at, reviewTabs.length - 1)]?.id ?? null) : state.activeReview, + }; + }); +} + +export function installTodoReviews() { + const clear = () => useTodoView.setState({ reviewTabs: [], activeReview: null }); + const dispose = provideTodoReview((review) => { + useTodoView.setState((state) => { + const existing = state.reviewTabs.find((tab) => tab.review === review); + if (existing) return { activeReview: existing.id }; + const id: ReviewId = `review:${++reviewSequence}`; + return { reviewTabs: [...state.reviewTabs, { id, review }], activeReview: id }; + }); + toolWindowService().show("todo", true); + }); + const unsubscribe = useProject.subscribe((state, before) => { + if (state.project !== before.project) clear(); + }); + return () => { + dispose(); + unsubscribe(); + clear(); + }; +} + // View options (persisted), in the tool window's ⋮ menu. IDEA's defaults: // preview on, no autoscroll. const OPTIONS_KEY = "openidea.todo.view.v1"; @@ -128,20 +194,23 @@ useTodoViewOptions.subscribe((s) => { /** The TODO tool window's ⋮ menu entries. */ export function useTodoHeaderMenu(): MenuItem[] { const o = useTodoViewOptions(); - return [ + const review = useTodoView((state) => state.activeReview !== null); + const items: MenuItem[] = [ { id: "preview", label: "Show Preview", checked: o.preview, run: () => useTodoViewOptions.setState({ preview: !o.preview }), }, - { + ]; + if (!review) + items.push({ id: "autoscroll", label: "Autoscroll to Source", checked: o.autoscroll, run: () => useTodoViewOptions.setState({ autoscroll: !o.autoscroll }), - }, - ]; + }); + return items; } type Node = { kind: "file"; key: string; group: TodoGroup } | { kind: "item"; key: string; item: TodoItem }; @@ -158,19 +227,22 @@ function useChangedPaths(): Set { } /** Groups for a tab (exported for the badge and tests). */ -export function useTodoGroups(tab: Tab, openPaths?: ReadonlySet): TodoGroup[] { +export function useTodoGroups(tab: ScopeTab, openPaths?: ReadonlySet): TodoGroup[] { const scanned = useTodos((s) => s.scanned); const scoped = useTodos((s) => s.scoped); const live = useTodos((s) => s.live); const hidden = useTodoView((s) => s.hidden); - const patterns = useTodoSettings((s) => s.patterns); + const settings = useTodoSettings(); + const selectedFilter = useTodoFilterSelection("view"); const current = useEditorRegistry((s) => s.active?.ctx.path ?? null); const changed = useChangedPaths(); return useMemo(() => { - const keywords = keywordFilter( - hidden, - patterns.map((p) => p.keyword.trim()), - ); + const keywords = + todoFilterKeywords(settings, selectedFilter) ?? + keywordFilter( + hidden, + activePatterns(settings).map((p) => p.keyword.trim()), + ); if (tab === "scope") { // Open Files membership comes from the tabs, even when the last scan found no matches there. if (openPaths) return groupTodos(mergeLive(scoped, live), { keywords, paths: openPaths }); @@ -181,7 +253,7 @@ export function useTodoGroups(tab: Tab, openPaths?: ReadonlySet): TodoGr const merged = mergeLive(scanned, live); if (tab === "changes") return groupTodos(merged, { keywords, paths: changed }); return groupTodos(merged, tab === "file" ? { keywords, path: current } : { keywords }); - }, [scanned, scoped, live, hidden, patterns, tab, current, changed, openPaths]); + }, [scanned, scoped, live, hidden, settings, selectedFilter, tab, current, changed, openPaths]); } /** The Scope Based tab's scope as the backend scope, with a key that changes when it does. */ @@ -301,43 +373,86 @@ function ItemText({ item }: { item: TodoItem }) { ); } -function TodoToolbar() { +function TodoToolbar({ review }: { review: boolean }) { const settings = useTodoSettings(); const hidden = useTodoView((s) => s.hidden); const toggleKeyword = useTodoView((s) => s.toggleKeyword); const showAll = useTodoView((s) => s.showAll); + const filterId = useTodoFilterSelection("view"); + const selected = settings.filters.find(({ id }) => id === filterId)?.id ?? null; + const keywords = todoFilterKeywords(settings, selected); + const patterns = activePatterns(settings); const scanning = useTodos((s) => s.scanning); const [anchor, setAnchor] = useState(null); const items: MenuItem[] = [ - { id: "all", label: "Show All", checked: hidden.length === 0, run: showAll }, + ...todoFilterChoices( + settings, + selected, + (id) => { + showAll(); + setTodoFilterSelection("view", id); + }, + selected === null && hidden.length === 0, + ), + { + id: "keywords", + label: "Filter by Keyword", + disabled: !patterns.length, + submenu: patterns.map(({ id, keyword }) => ({ + id, + label: keyword, + verbatim: true, + checked: keywords?.has(keyword.trim()) ?? !hidden.includes(keyword.trim()), + run: () => { + if (keywords) { + useTodoView.setState({ + hidden: patterns.map((pattern) => pattern.keyword.trim()).filter((word) => !keywords.has(word)), + }); + setTodoFilterSelection("view", null); + } + toggleKeyword(keyword.trim()); + }, + })), + }, { kind: "separator" }, - ...activePatterns(settings).map((p) => ({ - id: p.id, - label: p.keyword, - checked: !hidden.includes(p.keyword.trim()), - run: () => toggleKeyword(p.keyword.trim()), - })), + editTodoFiltersItem, ]; return ( - 0} - onClick={(e) => setAnchor(anchor ? null : e.currentTarget)} - /> - setAnchor(null)} aria-label="TODO filters" /> - updateTodoSettings({ caseSensitive: !settings.caseSensitive })} - /> - void scanProject()} /> + {!review && ( + <> + 0} + onClick={(e) => setAnchor(anchor ? null : e.currentTarget)} + /> + setAnchor(null)} + aria-label="TODO filters" + /> + updateTodoSettings({ caseSensitive: !settings.caseSensitive })} + /> + void scanProject()} + /> + + )} ); } @@ -346,6 +461,8 @@ function TodoToolbar() { export function TodoTabs() { const tab = useTodoView((s) => s.tab); const setTab = useTodoView((s) => s.setTab); + const reviews = useTodoView((s) => s.reviewTabs); + const activeReview = useTodoView((s) => s.activeReview); const current = useEditorRegistry((s) => s.active?.ctx.path ?? null); const projectCount = countItems(useTodoGroups("project")); const fileCount = countItems(useTodoGroups("file")); @@ -355,8 +472,13 @@ export function TodoTabs() { variant="compact" aria-label="TODO scope" className={styles.tabs} - activeId={tab} - onSelect={(id) => setTab(id as Tab)} + activeId={activeReview ?? tab} + onSelect={(id) => { + const tab = id as Tab; + if (isReviewId(tab)) useTodoView.setState({ activeReview: tab }); + else setTab(tab); + }} + onClose={closeReview} items={[ { id: "project", @@ -382,6 +504,22 @@ export function TodoTabs() { tooltip: "TODO items in files of a changelist", trailing: changesCount ? {changesCount} : undefined, }, + ...reviews.map(({ id, review }) => { + const title = tx(review.kind === "pending" ? "Commit TODOs" : "Committed TODOs"); + const count = review.files.reduce((total, file) => total + file.items.length, 0); + return { + id, + closable: true, + label: ( + <> + {title} + {review.subject && {review.subject}} + + ), + text: review.subject ? `${title} · ${review.subject}` : title, + trailing: count ? {count} : undefined, + }; + }), ]} /> ); @@ -389,22 +527,131 @@ export function TodoTabs() { export function TodoView() { const tab = useTodoView((s) => s.tab); - const collapsed = useTodoView((s) => s.collapsed); - const root = useProject((s) => s.project?.root ?? ""); + const activeReview = useTodoView((s) => s.activeReview); + const review = useTodoView((s) => s.reviewTabs.find(({ id }) => id === activeReview)?.review); const current = useEditorRegistry((s) => s.active?.ctx.path ?? null); const { scanning, error, limitHit, scannedOnce, scopedScanning, scopedKey } = useTodos(); const scope = useScopeQuery(); - const groups = useTodoGroups(tab, scope.openPaths); - useScopeScan(tab === "scope", scope); + const liveGroups = useTodoGroups(tab, scope.openPaths); + useScopeScan(!review && tab === "scope", scope); + const groups = useMemo( + () => review?.files.map(({ path, items }) => ({ path, items })) ?? liveGroups, + [review, liveGroups], + ); + + const empty = + tab === "file" && !current ? ( + + ) : tab === "scope" ? ( + scopedScanning || scopedKey !== scope.key ? ( +
+ Scanning for TODO items… +
+ ) : ( + + ) + ) : tab === "changes" ? ( + + ) : error && tab === "project" ? ( + + {error} + + ) : scanning || (!scannedOnce && tab === "project") ? ( +
+ Scanning for TODO items… +
+ ) : ( + + ); + + return ( +
+ {(!review || groups.length > 0) && } +
+ {!review && tab === "project" && limitHit && ( +
+ Too many matches; showing the first 10 000. +
+ )} + {!review && tab === "scope" && } + {!review && tab === "changes" && } + {review && review.skipped.length > 0 && ( + 0} /> + )} + {(!review || groups.length > 0) && ( + + )} +
+
+ ); +} + +function SkippedTodoFiles({ files, collapsible }: { files: readonly TodoReviewSkippedFile[]; collapsible: boolean }) { + const root = useProject((state) => state.project?.root ?? ""); + const list = ( +
    + {files.map(({ path, reason, detail }) => { + const directory = relativeDir(root, path); + const label = directory ? `${directory}/${basename(path)}` : basename(path); + return ( +
  • + {label} + {reason} + {detail && {detail}} +
  • + ); + })} +
+ ); + return collapsible ? ( +
+ + Files Not Checked {files.length} + + {list} +
+ ) : ( +
+

+ Files Not Checked +

+ {list} +
+ ); +} + +function itemKey({ path, line, col }: TodoItem) { + return `${path}\u0000${line}:${col}`; +} + +function TodoResults({ groups, empty, review }: { groups: TodoGroup[]; empty: ReactNode; review?: TodoReview }) { + const liveCollapsed = useTodoView((s) => s.collapsed); + const [reviewCollapsed, setReviewCollapsed] = useState(() => new Set()); + const collapsed = review ? reviewCollapsed : liveCollapsed; + const root = useProject((s) => s.project?.root ?? ""); const showPreview = useTodoViewOptions((o) => o.preview); const tree = useRef(null); - const [lead, setLead] = useState(null); + const first = review ? groups[0]?.items[0] : undefined; + const [lead, setLead] = useState(() => + first ? { kind: "item", key: itemKey(first), item: first } : null, + ); + + const activate = (item: TodoItem, focus: boolean) => { + if (review) { + void review.files.find(({ path }) => path === item.path)?.open(item, focus); + } else open(item, focus); + }; useOccurrenceNavigator("todo", (dir, focus) => { const step = tree.current?.selectOccurrence(dir); - const n = step?.node as Node | undefined; - if (!step || n?.kind !== "item") return null; - open(n.item, focus); + const node = step?.node as Node | undefined; + if (!step || node?.kind !== "item") return null; + if (!review || focus) activate(node.item, focus); return step; }); @@ -414,10 +661,8 @@ export function TodoView() { [roots, collapsed], ); const getChildren = useCallback( - (n: Node): Node[] | undefined => - n.kind === "file" - ? n.group.items.map((item) => ({ kind: "item", key: `${item.path}\u0000${item.line}:${item.col}`, item })) - : undefined, + (node: Node): Node[] | undefined => + node.kind === "file" ? node.group.items.map((item) => ({ kind: "item", key: itemKey(item), item })) : undefined, [], ); @@ -454,101 +699,73 @@ export function TodoView() { ); }; - const empty = - tab === "file" && !current ? ( - - ) : tab === "scope" ? ( - scopedScanning || scopedKey !== scope.key ? ( -
- Scanning for TODO items… -
- ) : ( - - ) - ) : tab === "changes" ? ( - - ) : error && tab === "project" ? ( - - {error} - - ) : scanning || (!scannedOnce && tab === "project") ? ( -
- Scanning for TODO items… -
- ) : ( - - ); - return ( -
- -
- {tab === "project" && limitHit && ( -
- Too many matches; showing the first 10 000. -
- )} - {tab === "scope" && } - {tab === "changes" && } - - - - handleRef={tree} - roots={roots} - getKey={(n) => n.key} - getLabel={(n) => (n.kind === "file" ? basename(n.group.path) : n.item.text)} - getChildren={getChildren} - isExpandable={(n) => n.kind === "file"} - expanded={expanded} - onExpandedChange={(_next, node, isExpanded) => - useTodoView.setState((s) => { - const c = new Set(s.collapsed); - if (isExpanded) c.delete(node.key); - else c.add(node.key); - return { collapsed: c }; - }) - } - renderNode={renderNode} - onActivate={(n) => { - if (n.kind === "item") open(n.item, true); - else if (n.group.items[0]) open(n.group.items[0], true); - }} - onSelectionChange={(_sel, node) => { - setLead(node); - // Autoscroll to Source (off by default, as in IDEA). - if (node?.kind === "item" && useTodoViewOptions.getState().autoscroll) open(node.item, false); - }} - activateExpandable={false} - multiSelect={false} - speedSearch - aria-label="TODO items" - empty={empty} - /> + + + + handleRef={tree} + roots={roots} + getKey={(node) => node.key} + getLabel={(node) => (node.kind === "file" ? basename(node.group.path) : node.item.text)} + getChildren={getChildren} + isExpandable={(node) => node.kind === "file"} + expanded={expanded} + defaultSelected={first ? [itemKey(first)] : undefined} + onExpandedChange={(_next, node, isExpanded) => { + const updated = new Set(collapsed); + if (isExpanded) updated.delete(node.key); + else updated.add(node.key); + if (review) setReviewCollapsed(updated); + else useTodoView.setState({ collapsed: updated }); + }} + renderNode={renderNode} + onActivate={(node) => { + const item = node.kind === "item" ? node.item : node.group.items[0]; + if (item) activate(item, true); + }} + onSelectionChange={(_selection, node) => { + setLead(node); + if (!review && node?.kind === "item" && useTodoViewOptions.getState().autoscroll) open(node.item, false); + }} + activateExpandable={false} + multiSelect={false} + speedSearch + aria-label="TODO items" + empty={empty} + /> + + {showPreview && ( + <> + + + - {showPreview && ( - <> - - - - - - )} - -
-
+ + )} + ); } -function TodoPreview({ node }: { node: Node | null }) { +function TodoPreview({ node, review }: { node: Node | null; review?: TodoReview }) { const item = node?.kind === "item" ? node.item : (node?.group.items[0] ?? null); const highlights = item ? [{ line: item.line, ranges: [[item.col, item.col + item.text.length] as const] }] : []; - // IDEA's TODO preview is simply an editor on the file: editable in place, - // with read-only files falling back to the read-only preview (in PreviewEditor). + const snapshot: TodoReviewFile | undefined = review?.files.find(({ path }) => path === item?.path); + const load = useCallback(async () => snapshot?.text ?? "", [snapshot]); + if (review) + return ( + + ); return ( } | for (const p of activePatterns(s)) colors.set(s.caseSensitive ? p.keyword.trim() : p.keyword.trim().toLowerCase(), p.color); // Keyword only; the decoration runs to the end of the comment line. - return { re: new RegExp(source.replace(/\.\*$/, ""), s.caseSensitive ? "gu" : "giu"), colors }; + return { re: new RegExp(source, s.caseSensitive ? "gu" : "giu"), colors }; } const markCache = new Map(); diff --git a/src/features/todo/index.ts b/src/features/todo/index.ts index a5681b58d..f44c53c5a 100644 --- a/src/features/todo/index.ts +++ b/src/features/todo/index.ts @@ -4,13 +4,15 @@ import { registerEditorContribution } from "@/editor/api"; import { registerToolWindow, toolWindowService } from "@/workbench/contributions"; import { hasIcon } from "@/ui"; import { activateSettingsPages } from "./settingsPages"; -import { TodoTabs, TodoView, useTodoBadge, useTodoHeaderMenu, useTodoView } from "./TodoView"; +import { installTodoReviews, TodoTabs, TodoView, useTodoBadge, useTodoHeaderMenu, useTodoView } from "./TodoView"; import { todoEditorExtension } from "./highlight"; -import { installTodoIndex, scanProject, syncTodoSettingsFromStorage } from "./store"; +import { syncTodoSettingsFromStorage } from "@/platform/todo"; +import { installTodoIndex, scanProject } from "./store"; export function activate(): () => void { const disposers = [ installTodoIndex(), + installTodoReviews(), syncTodoSettingsFromStorage(), registerEditorContribution({ id: "todo.highlight", order: 120, extensions: todoEditorExtension }), registerToolWindow({ diff --git a/src/features/todo/model.ts b/src/features/todo/model.ts index cd5a844f9..c0556a551 100644 --- a/src/features/todo/model.ts +++ b/src/features/todo/model.ts @@ -1,146 +1,9 @@ -/** - * TODO items: patterns, the Find-in-Files query, conversion of search - * matches, local scanning of editor text, grouping and filters. - */ -import type { FileMatches, SearchQuery, SearchScope } from "@/platform/ipc"; +/** TODO tool window grouping and search scopes. */ +import type { SearchScope } from "@/platform/ipc"; import type { CustomScope } from "@/platform/search"; +import type { TodoItem } from "@/platform/todo"; import { localChangedPaths, type LocalChangelist } from "@/workbench/contributions"; -export interface TodoPattern { - id: string; - keyword: string; - /** CSS colour token, e.g. `var(--info)`. */ - color: string; - enabled: boolean; -} - -export interface TodoSettings { - patterns: TodoPattern[]; - caseSensitive: boolean; - /** Only count matches that follow a comment marker on their line. */ - commentsOnly: boolean; -} - -export const DEFAULT_PATTERNS: TodoPattern[] = [ - { id: "todo", keyword: "TODO", color: "var(--info)", enabled: true }, - { id: "fixme", keyword: "FIXME", color: "var(--danger)", enabled: true }, - { id: "hack", keyword: "HACK", color: "var(--warning)", enabled: true }, - { id: "xxx", keyword: "XXX", color: "var(--warning)", enabled: true }, -]; - -export const DEFAULT_TODO_SETTINGS: TodoSettings = { - patterns: DEFAULT_PATTERNS, - caseSensitive: true, - commentsOnly: true, -}; - -export interface TodoItem { - path: string; - /** 0-based line. */ - line: number; - /** UTF-16 column of the keyword in the real line. */ - col: number; - /** Pattern keyword as configured (e.g. `TODO`). */ - keyword: string; - /** Text from the keyword to the end of the comment. */ - text: string; -} - -const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - -export const activePatterns = (s: TodoSettings) => s.patterns.filter((p) => p.enabled && p.keyword.trim()); - -/** `\b(TODO|FIXME|HACK|XXX)\b.*`, or null when no pattern is enabled. */ -export function todoRegexSource(s: TodoSettings): string | null { - const kws = activePatterns(s).map((p) => escapeRe(p.keyword.trim())); - return kws.length ? `\\b(${kws.join("|")})\\b.*` : null; -} - -export function buildTodoQuery(s: TodoSettings, scope: SearchScope = { kind: "project" }): SearchQuery | null { - const pattern = todoRegexSource(s); - if (!pattern) return null; - return { - pattern, - isRegex: true, - caseSensitive: s.caseSensitive, - wholeWord: false, - include: [], - exclude: [], - scope, - maxMatches: 0, - }; -} - -// Comment openers that count anywhere on the line, at its start or after whitespace: // /* |-\}|\*\)|"""|''')\s*$/, "").replace(/\s+$/, ""); -} - -function patternFor(s: TodoSettings, matched: string): TodoPattern | undefined { - const pats = activePatterns(s); - return s.caseSensitive - ? pats.find((p) => matched.startsWith(p.keyword.trim())) - : pats.find((p) => matched.toLowerCase().startsWith(p.keyword.trim().toLowerCase())); -} - -/** Converts one file's search matches to TODO items. */ -export function itemsFromMatches(fm: FileMatches, s: TodoSettings): TodoItem[] { - const out: TodoItem[] = []; - for (const lm of fm.matches) { - for (const [start, end] of lm.ranges) { - const matched = lm.text.slice(start, end); - const p = patternFor(s, matched); - if (!p) continue; - if (s.commentsOnly && !looksLikeComment(lm.text.slice(0, start), lm.textOffset > 0)) continue; - out.push({ - path: fm.path, - line: lm.line, - col: lm.textOffset + start, - keyword: p.keyword.trim(), - text: cleanText(matched), - }); - } - } - return out; -} - -/** Scans document text locally (open editors), same rules as the backend search. */ -export function scanText(path: string, text: string, s: TodoSettings): TodoItem[] { - const source = todoRegexSource(s); - if (!source) return []; - const re = new RegExp(source, s.caseSensitive ? "gu" : "giu"); - const out: TodoItem[] = []; - let line = 0; - let lineStart = 0; - for (const m of text.matchAll(re)) { - const idx = m.index!; - for (let nl = text.indexOf("\n", lineStart); nl !== -1 && nl < idx; nl = text.indexOf("\n", nl + 1)) { - line++; - lineStart = nl + 1; - } - const p = patternFor(s, m[0]); - if (!p) continue; - if (s.commentsOnly && !looksLikeComment(text.slice(lineStart, idx), false)) continue; - out.push({ path, line, col: idx - lineStart, keyword: p.keyword.trim(), text: cleanText(m[0]) }); - } - return out; -} - export interface TodoGroup { path: string; items: TodoItem[]; diff --git a/src/features/todo/store.ts b/src/features/todo/store.ts index ca7dc7e02..7f0dab222 100644 --- a/src/features/todo/store.ts +++ b/src/features/todo/store.ts @@ -8,39 +8,7 @@ import { call, cancelRequestSafe, commands, isTauri, nextRequestId, onIdeEvent } import type { RequestId, SearchEvent, SearchQuery, SearchScope } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { onEditorEvent } from "@/editor/api"; -import { buildTodoQuery, DEFAULT_TODO_SETTINGS, itemsFromMatches, type TodoItem, type TodoSettings } from "./model"; - -const SETTINGS_KEY = "openidea.todo.v1"; - -function loadSettings(): TodoSettings { - try { - const raw = globalThis.localStorage?.getItem(SETTINGS_KEY); - if (raw) return { ...DEFAULT_TODO_SETTINGS, ...JSON.parse(raw) }; - } catch { - // ignore - } - return DEFAULT_TODO_SETTINGS; -} - -export const useTodoSettings = create(() => loadSettings()); - -export function updateTodoSettings(patch: Partial) { - useTodoSettings.setState(patch); - try { - globalThis.localStorage?.setItem(SETTINGS_KEY, JSON.stringify(useTodoSettings.getState())); - } catch { - // ignore - } -} - -/** Picks up changes saved by another window (the Settings window). */ -export function syncTodoSettingsFromStorage(): () => void { - const onStorage = (e: StorageEvent) => { - if (e.key === SETTINGS_KEY) useTodoSettings.setState(loadSettings(), true); - }; - window.addEventListener("storage", onStorage); - return () => window.removeEventListener("storage", onStorage); -} +import { buildTodoQuery, itemsFromMatches, useTodoSettings, type TodoItem } from "@/platform/todo"; interface TodoState { /** Results of the last project scan, per absolute path. */ diff --git a/src/features/todo/todo.test.ts b/src/features/todo/todo.test.ts index cfcc1e973..ac9409a92 100644 --- a/src/features/todo/todo.test.ts +++ b/src/features/todo/todo.test.ts @@ -6,19 +6,15 @@ import { languages } from "@codemirror/language-data"; import type { FileMatches } from "@/platform/ipc"; import { buildTodoQuery, - changedPaths, - todoSearchScope, - countItems, DEFAULT_TODO_SETTINGS, - groupTodos, itemsFromMatches, looksLikeComment, - mergeLive, scanText, todoRegexSource, type TodoItem, type TodoSettings, -} from "./model"; +} from "@/platform/todo"; +import { changedPaths, todoSearchScope, countItems, groupTodos, mergeLive } from "./model"; import { todoDecorations } from "./highlight"; const S = DEFAULT_TODO_SETTINGS; @@ -71,7 +67,7 @@ describe("comment markers", () => { describe("query", () => { it("builds the keyword regex from enabled patterns", () => { - expect(todoRegexSource(S)).toBe("\\b(TODO|FIXME|HACK|XXX)\\b.*"); + expect(todoRegexSource(S)).toBe("\\b(FIXME|TODO|HACK|XXX)\\b"); const q = buildTodoQuery({ ...S, caseSensitive: false }, { kind: "files", paths: ["/a"] })!; expect(q).toMatchObject({ isRegex: true, caseSensitive: false, scope: { kind: "files", paths: ["/a"] } }); const none: TodoSettings = { ...S, patterns: S.patterns.map((p) => ({ ...p, enabled: false })) }; @@ -84,10 +80,10 @@ describe("matches → items", () => { path: "/p/src/a.ts", relPath: "src/a.ts", matches: [ - { line: 3, text: " // TODO: fix this", ranges: [[5, 19]], textOffset: 0 }, - { line: 9, text: "const TODO_LIST = 1; /* FIXME later */", ranges: [[24, 38]], textOffset: 0 }, - { line: 12, text: 'const s = "TODO nope";', ranges: [[11, 21]], textOffset: 0 }, - { line: 20, text: "…x # HACK around", ranges: [[5, 16]], textOffset: 100 }, + { line: 3, text: " // TODO: fix this", ranges: [[5, 9]], textOffset: 0 }, + { line: 9, text: "const TODO_LIST = 1; /* FIXME later */", ranges: [[24, 29]], textOffset: 0 }, + { line: 12, text: 'const s = "TODO nope";', ranges: [[11, 15]], textOffset: 0 }, + { line: 20, text: "…x # HACK around", ranges: [[5, 9]], textOffset: 100 }, ], }; @@ -106,6 +102,22 @@ describe("matches → items", () => { }); describe("local scan", () => { + it("finds each pattern on a line, including one after a keyword outside a comment", () => { + const text = 'const example = "TODO"; // FIXME now; TODO later'; + const matches = scanText("/p/a.ts", text, S); + expect(matches.map(({ keyword, text }) => [keyword, text])).toEqual([ + ["FIXME", "FIXME now; TODO later"], + ["TODO", "TODO later"], + ]); + const ranges: [number, number][] = [...text.matchAll(new RegExp(todoRegexSource(S)!, "g"))].map((match) => [ + match.index!, + match.index! + match[0].length, + ]); + expect( + itemsFromMatches({ path: "/p/a.ts", relPath: "a.ts", matches: [{ line: 0, text, ranges, textOffset: 0 }] }, S), + ).toEqual(matches); + }); + it("finds items with 0-based lines and columns", () => { const text = "fn a() {}\n// todo lower\n // TODO: one\n/* XXX two */\nlet TODO = 1;"; expect(scanText("/f.rs", text, S)).toEqual([ diff --git a/src/features/vcs/AmendTargetMenu.tsx b/src/features/vcs/AmendTargetMenu.tsx new file mode 100644 index 000000000..b0573a90f --- /dev/null +++ b/src/features/vcs/AmendTargetMenu.tsx @@ -0,0 +1,114 @@ +import { useEffect, useRef, useState } from "react"; +import { executeActionFrom } from "@/platform/actions"; +import { tx } from "@/platform/i18n"; +import { Button, Popup, SelectListbox, T, tooltipAttrs, type SelectOption } from "@/ui"; +import { loadAmendTargets, SELECT_AMEND_TARGET, type AmendTargets } from "./amendTargets"; +import { useCommit } from "./commitStore"; +import styles from "./CommitView.module.css"; + +const LAST_COMMIT = "last"; + +export function AmendTargetMenu({ root }: { root: string }) { + const target = useCommit((s) => s.amendTarget); + const busy = useCommit((s) => !!s.operation); + const anchor = useRef(null); + const [initialQuery, setInitialQuery] = useState(null); + const [result, setResult] = useState<{ root: string; targets: AmendTargets | null } | null>(null); + const open = initialQuery !== null; + + useEffect(() => { + if (!open) return; + let current = true; + void loadAmendTargets(root).then( + (targets) => { + if (current) setResult({ root, targets }); + }, + () => { + if (current) setResult({ root, targets: null }); + }, + ); + return () => { + current = false; + }; + }, [open, root]); + + const close = () => setInitialQuery(null); + const openPicker = (query = "") => { + setResult(null); + setInitialQuery(query); + }; + const available = result?.root === root ? result.targets : undefined; + const options: SelectOption[] = [ + { + value: LAST_COMMIT, + label: "Amend Last Commit", + detail: available?.latest?.summary, + verbatimDetail: true, + }, + ...(available?.earlier.map(({ commit }) => ({ + value: commit.id, + label: commit.summary || commit.shortId, + verbatim: true, + })) ?? []), + ]; + + return ( + <> + + + + No matches + + ) + } + onChoose={(value) => { + close(); + const earlier = available?.earlier.find((option) => option.commit.id === value); + if (value === LAST_COMMIT || earlier) void executeActionFrom("menu", SELECT_AMEND_TARGET, earlier); + }} + /> + {available == null && ( +
+ {available === null ? "Could not load earlier commits" : "Loading commits…"} +
+ )} +
+ + ); +} diff --git a/src/features/vcs/ApplyPatch.module.css b/src/features/vcs/ApplyPatch.module.css index 8434b0767..e5d5f2b03 100644 --- a/src/features/vcs/ApplyPatch.module.css +++ b/src/features/vcs/ApplyPatch.module.css @@ -60,7 +60,13 @@ font-weight: 500; } -.list { +.filesHeading { + display: flex; + align-items: center; + gap: var(--space-2); +} + +.tree { flex: 1; min-height: 0; } @@ -80,6 +86,21 @@ text-overflow: ellipsis; } +.chooseBase { + flex: none; + padding: 0; + border: 0; + background: none; + color: var(--link); + font: inherit; + cursor: pointer; +} + +.chooseBase:hover { + color: var(--link-hover); + text-decoration: underline; +} + .stats { flex: none; color: var(--fg-secondary); @@ -119,3 +140,60 @@ .error { color: var(--danger); } + +.patchDiff { + display: flex; + flex: 1; + flex-direction: column; + min-height: 0; +} + +.patchDiffNav { + display: flex; + align-items: center; + gap: var(--space-1); + min-height: var(--h-field); + padding-inline: var(--space-3); + border-bottom: 1px solid var(--border); +} + +.diffEmpty { + display: grid; + flex: 1; + place-items: center; + color: var(--fg-secondary); +} + +.rawPatch { + display: flex; + flex: 1; + min-height: 0; +} + +.rawPatch > section { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; +} + +.rawPatch > section + section { + border-left: 1px solid var(--border); +} + +.rawPatch h2 { + margin: 0; + padding: var(--space-2) var(--space-3); + border-bottom: 1px solid var(--border); + font-size: var(--fs-ui); + font-weight: 500; +} + +.rawPatch pre { + flex: 1; + margin: 0; + overflow: auto; + padding: var(--space-2) var(--space-3); + background: var(--bg-app); + font: var(--fw-code, 400) var(--fs-code) / var(--lh-code) var(--font-mono); +} diff --git a/src/features/vcs/BranchComparisonEditor.tsx b/src/features/vcs/BranchComparisonEditor.tsx new file mode 100644 index 000000000..cf7b2993b --- /dev/null +++ b/src/features/vcs/BranchComparisonEditor.tsx @@ -0,0 +1,70 @@ +import { useEffect } from "react"; +import { executeAction } from "@/platform/actions"; +import { tx } from "@/platform/i18n"; +import { Button, SplitGroup, SplitHandle, SplitPanel } from "@/ui"; +import type { EditorInput } from "@/workbench/contributions"; +import { comparisonPaneIds, type BranchComparisonData } from "./CompareBranches"; +import styles from "./CompareBranches.module.css"; +import { LogView } from "./GitLog"; +import { useDropdownMenu } from "./log/logHooks"; +import { LogScope } from "./LogScope"; +import { ensureEditorLog, focusLogView, useRootGitLog } from "./logStore"; +import { repoName, useVcs } from "./store"; + +export function BranchComparisonEditor({ input }: { input: EditorInput }) { + const data = input.data as BranchComparisonData; + const { branch, current, repositories } = data; + const [incoming, outgoing] = comparisonPaneIds(input.key); + const root = useVcs((s) => s.root); + const ready = useRootGitLog( + (s) => s.logTabs.some((t) => t.id === incoming) && s.logTabs.some((t) => t.id === outgoing), + ); + useEffect(() => { + ensureEditorLog(incoming, branch.name, { comparison: { from: current.rev, to: branch.rev }, repositories }); + ensureEditorLog(outgoing, current.name, { comparison: { from: branch.rev, to: current.rev }, repositories }); + if (useRootGitLog.getState().shownLog !== outgoing) focusLogView(incoming); + }, [root, incoming, outgoing, branch, current, repositories]); + const [menu, dropdown] = useDropdownMenu(); + const diff = (repo: string) => void executeAction("vcs.log.compareBranchTrees", { ...data, repo }); + return ( +
+
+ + {dropdown} +
+ {ready && ( + + + + + + )} +
+ ); +} + +function ComparisonPane({ id, label }: { id: string; label: string }) { + return ( + +
+

{label}

+ + + +
+
+ ); +} diff --git a/src/features/vcs/BranchSync.tsx b/src/features/vcs/BranchSync.tsx index 72c450850..583e3e149 100644 --- a/src/features/vcs/BranchSync.tsx +++ b/src/features/vcs/BranchSync.tsx @@ -7,6 +7,9 @@ import styles from "./BranchSync.module.css"; interface BranchSyncProps { ahead: number; behind: number; + unfetched?: boolean; + incomingRepositories?: number; + outgoingRepositories?: number; /** Include the commit counts; the title-bar widget passes false and keeps them in the tooltip. */ showCounts?: boolean; className?: string; @@ -15,12 +18,38 @@ interface BranchSyncProps { } /** Incoming / outgoing branch markers shared by the branch widget, popup and Git Log tree. */ -export function BranchSync({ ahead, behind, showCounts = true, className, onSelect }: BranchSyncProps) { - if (ahead <= 0 && behind <= 0) return null; +export function BranchSync({ + ahead, + behind, + unfetched, + incomingRepositories = 0, + outgoingRepositories = 0, + showCounts = true, + className, + onSelect, +}: BranchSyncProps) { + if (ahead <= 0 && behind <= 0 && !unfetched) return null; return ( - {behind > 0 && } - {ahead > 0 && } + {(behind > 0 || unfetched) && ( + 0 ? behind : null} + direction="incoming" + repositories={incomingRepositories} + unfetched={unfetched} + showCount={showCounts} + onSelect={onSelect} + /> + )} + {ahead > 0 && ( + + )} ); } @@ -28,15 +57,30 @@ export function BranchSync({ ahead, behind, showCounts = true, className, onSele function BranchSyncItem({ count, direction, + repositories, + unfetched, showCount, onSelect, }: { - count: number; + count: number | null; direction: SyncDirection; + repositories: number; + unfetched?: boolean; showCount: boolean; onSelect?: (direction: SyncDirection) => void; }) { - const label = direction === "incoming" ? tx`${count} incoming commits` : tx`${count} outgoing commits`; + let commits = ""; + if (count !== null) { + commits = + repositories > 1 + ? direction === "incoming" + ? tx`${count} incoming commits in ${repositories} repositories` + : tx`${count} outgoing commits in ${repositories} repositories` + : direction === "incoming" + ? tx`${count} incoming commits` + : tx`${count} outgoing commits`; + } + const label = [commits, unfetched ? tx("Remote changes available to fetch") : ""].filter(Boolean).join("\n"); return ( - {showCount && {count}} + {showCount && count !== null && {count > 99 ? "99+" : count}} ); } diff --git a/src/features/vcs/BranchWidget.tsx b/src/features/vcs/BranchWidget.tsx index 68442411f..a0cb6ca73 100644 --- a/src/features/vcs/BranchWidget.tsx +++ b/src/features/vcs/BranchWidget.tsx @@ -3,12 +3,11 @@ import { branchesByRepo } from "./multiRoot"; import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react"; import clsx from "clsx"; import { create } from "zustand"; -import type { Branch, BranchInfo } from "@/bindings"; +import type { Branch } from "@/bindings"; import { executeAction } from "@/platform/actions"; import { call, commands } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { bindingsFor, normalizeBinding, registerKeyClaim, shortcutLabel, strokeOf } from "@/platform/keymap"; -import { useEditorRegistry } from "@/editor/api"; import { BarButton, HighlightedText, @@ -26,6 +25,7 @@ import { } from "@/ui"; import { useRowHeight } from "@/ui/density"; import type { PopupAnchor } from "@/ui/Popup"; +import { useActiveRepository, useWidgetBranch } from "./activeRepository"; import { buildBranchRows, preferredBranchRow, @@ -36,22 +36,30 @@ import { } from "./branches"; import { branchPresentation, extensionPopupActions, useBranchWidgetExtensions } from "./branchWidgetExtensions"; import { branchMenu, commonBranchMenu, inRepo, tagMenu } from "./branchMenu"; -import { loadFavoriteBranches, recentBranches, toggleFavoriteBranch, useFavoriteBranches } from "./branchOps"; +import { + loadFavoriteBranches, + recentBranches, + configuredRemoteNames, + toggleFavoriteBranch, + useFavoriteBranches, +} from "./branchOps"; import { inProgress, operationTitle, type InProgress } from "./operations"; import { branchRepositoryRoots, buildMultiRepoRows, - currentRepoFor, preferredRepoRow, repoHeadLabel, widgetShowsRepo, type RepoEntry, type RepoRow, } from "./repoBranches"; -import { currentRepo, focusRepo, loadBranches, repoName, useVcs } from "./store"; +import { currentRepo, currentRepoRoot, focusRepo, loadBranches, repoName, unfetchedBranch, useVcs } from "./store"; +import { useBranchWorktrees } from "./worktrees"; import { BranchSync } from "./BranchSync"; -import { showSyncCommits } from "./SyncCommitsPopup"; -import type { SyncDirection } from "./syncCommits"; +import { summarizeBranchSync, type BranchSyncSummary } from "./branchSyncState"; +import { FetchButton } from "./FetchButton"; +import { showBranchSync } from "./SyncCommitsPopup"; +import { outgoingCount, outgoingDestination, type SyncDirection } from "./syncCommits"; import styles from "./BranchWidget.module.css"; import { tx } from "@/platform/i18n"; import { useWorkflowSettings } from "@/platform/workflowSettings"; @@ -81,12 +89,6 @@ export function headLabel(branch: { head: string | null; headCommit: string | nu return branch.headCommit ? branch.headCommit.slice(0, 8) : tx("No commits"); } -/** The current repository (see `currentRepoFor`): the widget and the popup show the same one. */ -function useCurrentRepo(): string | null { - const path = useEditorRegistry((s) => s.active?.ctx.path ?? null); - return useVcs((s) => currentRepoFor(path, s.roots, s.repo)); -} - function useBranchRepositories(current: string | null) { const roots = useVcs((s) => s.roots); const branchRoots = useVcs((s) => s.branchRoots); @@ -95,54 +97,49 @@ function useBranchRepositories(current: string | null) { export function BranchWidget() { const available = useVcs((s) => s.available); - const selected = useVcs((s) => s.branch); - const current = useCurrentRepo(); + const current = useActiveRepository(); const roots = useBranchRepositories(current); + const count = roots.length; + const branch = useWidgetBranch(current); const heads = useVcs((s) => s.heads); const branchRoot = useVcs((s) => (current ? (s.branchRoots[current] ?? current) : null)); + const selected = useVcs((s) => s.repo ?? s.roots[0] ?? null); // Several repositories on different branches: the widget names the current one. const diverged = widgetShowsRepo(roots.map((r) => ({ head: heads[r]?.head ?? null }))); - // The current repository is not the selected one: its HEAD from the last scan (no upstream). - const other = useVcs((s) => - (diverged || roots.length === 1) && current && current !== s.repo ? (s.heads[current] ?? null) : null, - ); - const otherOp = useVcs((s) => (current ? (s.operations[current] ?? null) : null)); + const pending = useVcs((s) => unfetchedBranch(s.unfetched, current, branch?.head, branch?.trackedTip)); const open = useBranchesPopup((s) => s.open); const extensions = useBranchWidgetExtensions((s) => s.extensions); - if (!available || !selected) return null; + if (!available || !branch) return null; // Another feature presents the current branch (the GitHub pull request on it). - const presented = other ? null : branchPresentation(extensions); + const presented = current === selected ? branchPresentation(extensions) : null; const repo = diverged && branchRoot ? repoName(branchRoot) : null; - const branch: BranchInfo = other - ? { head: other.head, headCommit: other.headCommit, upstream: null, ahead: 0, behind: 0, operation: otherOp } - : selected; const head = branch.operation ? `${headLabel(branch)} (${branch.operation})` : headLabel(branch); + const ahead = outgoingCount(branch); + const destination = outgoingDestination(branch.outgoing); const sync = - branch.behind > 0 && branch.ahead > 0 - ? tx`${branch.behind} incoming, ${branch.ahead} outgoing commits` + branch.behind > 0 && ahead > 0 + ? tx`${branch.behind} incoming, ${ahead} outgoing commits` : branch.behind > 0 ? tx`${branch.behind} incoming commits` - : branch.ahead > 0 - ? tx`${branch.ahead} outgoing commits` + : ahead > 0 + ? tx`${ahead} outgoing commits` : ""; const tooltip = [ presented?.tooltip ?? "", repo ? tx`Repository: ${repo}` : "", tx`Git branch: ${head}`, branch.upstream ? tx`Tracking ${branch.upstream}` : "", - roots.length > 1 && !repo ? tx`In all ${roots.length} repositories` : "", + destination && destination !== branch.upstream ? tx`Push destination: ${destination}` : "", + count > 1 && !repo ? tx`In all ${count} repositories` : "", sync, + pending ? tx("Remote changes available to fetch") : "", ] .filter(Boolean) .join("\n"); // A marker lists its commits; the rest of the widget keeps opening the branches popup. const openSync = (direction: SyncDirection) => { useBranchesPopup.setState({ open: false }); - showSyncCommits({ - repo: current, - branch: { branch: branch.head, upstream: branch.upstream, ahead: branch.ahead, behind: branch.behind }, - direction, - }); + showBranchSync(current, branch, direction); }; return ( <> @@ -157,7 +154,7 @@ export function BranchWidget() { onClick={() => useBranchesPopup.setState({ open: !open })} > - {repo && ( + {diverged && repo && ( {repo} @@ -171,7 +168,7 @@ export function BranchWidget() { {branch.operation} )} {/* Like IDEA's widget: icons only; counts are in the tooltip. */} - + @@ -190,15 +187,15 @@ const POPUP_ACTIONS: PopupAction[] = [ { id: "vcs.commit", label: "Commit…", icon: "commit", group: "sync" }, { id: "vcs.push", label: "Push…", icon: "git-push", group: "sync" }, { id: "vcs.syncCommits", label: "Incoming and Outgoing Commits…", icon: "history", group: "sync" }, + { id: "vcs.newWorktree", label: "New Worktree…", icon: "folder", group: "branch" }, { id: "vcs.newBranch", label: "New Branch…", icon: "plus", group: "branch" }, - { id: "vcs.newWorktree", label: "New Worktree…", group: "branch" }, { id: "vcs.checkoutRevision", label: "Checkout Tag or Revision…", icon: "branch", group: "branch" }, ]; /** A single repository's own entries (its submenu in the popup with several repositories). */ const REPO_ACTIONS: PopupAction[] = [ { id: "vcs.newBranch", label: "New Branch…", icon: "plus", group: "branch" }, - { id: "vcs.newWorktree", label: "New Worktree…", group: "branch" }, + { id: "vcs.newWorktree", label: "New Worktree…", icon: "folder", group: "branch" }, { id: "vcs.checkoutRevision", label: "Checkout Tag or Revision…", icon: "branch", group: "branch" }, ]; @@ -412,10 +409,11 @@ const caretAt = (e: KeyboardEvent, where: "start" | "end") => { }; function BranchesPopup({ anchor, onClose }: { anchor: PopupAnchor; onClose: () => void }) { - const current = useCurrentRepo(); + const current = useActiveRepository(); const roots = useBranchRepositories(current); const selected = useVcs((s) => s.repo); const multi = roots.length > 1; + const worktreeFor = useBranchWorktrees(); const extensions = useBranchWidgetExtensions((s) => s.extensions); const actions = useMemo(() => [...POPUP_ACTIONS, ...extensionPopupActions(extensions)], [extensions]); // ⌥⌘N is also Inline (enabled while a popup is open over an editor): the search field handles it here. @@ -438,11 +436,12 @@ function BranchesPopup({ anchor, onClose }: { anchor: PopupAnchor; onClose: () = onResized={savePopupSize} > {multi ? ( - + ) : ( )} @@ -453,6 +452,7 @@ function BranchesPopup({ anchor, onClose }: { anchor: PopupAnchor; onClose: () = interface BranchesPanelProps { onClose: () => void; actions: readonly PopupAction[]; + worktreeFor: ReturnType; /** A repository other than the selected one (the submenu of a repository): it is selected before acting. */ root?: string; /** Its branches until the selected repository's are loaded. */ @@ -461,8 +461,25 @@ interface BranchesPanelProps { onBack?: () => void; } +function useBranchSubmenu() { + const [menuFor, setMenuFor] = useState<{ items: MenuItem[]; label: string; el: HTMLElement } | null>(null); + const openTagMenu = (tag: string, el: HTMLElement, done: () => void, root?: string) => { + const repo = root ?? currentRepoRoot(); + const items = (remotes?: string[]) => { + const menu = tagMenu(tag, done, { repo, remotes }); + return root ? inRepo(root, menu) : menu; + }; + const pending = { items: items(), label: tx`Tag ${tag}`, el }; + setMenuFor(pending); + void configuredRemoteNames(repo).then((remotes) => + setMenuFor((menu) => (menu === pending && el.isConnected ? { ...menu, items: items(remotes) } : menu)), + ); + }; + return { menuFor, setMenuFor, openTagMenu }; +} + /** Search, actions and the branches of one repository (the selected one, or `root`). */ -function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }: BranchesPanelProps) { +function BranchesPanel({ onClose, actions: baseActions, worktreeFor, root, fallback, onBack }: BranchesPanelProps) { const rowHeight = useRowHeight(ROW_HEIGHT); const selected = useVcs((s) => s.repo); const live = root === undefined || selected === root; @@ -478,7 +495,7 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack } const [query, setQuery] = useState(""); const [recent] = useState(recentBranches); const [active, setActive] = useState(0); - const [menuFor, setMenuFor] = useState<{ items: MenuItem[]; label: string; el: HTMLElement } | null>(null); + const { menuFor, setMenuFor, openTagMenu } = useBranchSubmenu(); const listRef = useRef(null); const favorites = useFavoriteBranches((s) => s.names); const [tags, setTags] = useState([]); @@ -530,15 +547,29 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack } if (row?.type !== "branch" && row?.type !== "tag") return; const el = rowElement(listRef.current, row.key); if (!el) return; - setMenuFor( - row.type === "branch" - ? { items: scoped(branchMenu(row.branch, current, closeAll)), label: tx`Branch ${row.branch.name}`, el } - : { items: scoped(tagMenu(row.tag, closeAll)), label: tx`Tag ${row.tag}`, el }, - ); + if (row.type === "tag") { + openTagMenu(row.tag, el, closeAll, root); + return; + } + setMenuFor({ + items: scoped( + branchMenu(row.branch, current, closeAll, { + branches, + headCommit: root ? (useVcs.getState().heads[root]?.headCommit ?? null) : undefined, + existingWorktree: worktreeFor(root ?? currentRepo(), row.branch.name), + }), + ), + label: tx`Branch ${row.branch.name}`, + el, + }); }; const run = (id: string, arg?: unknown) => { onClose(); + if (root && (id === "vcs.newWorktree" || id === "vcs.checkoutRevision")) { + void executeAction(id, { repo: root }); + return; + } void (root ? focusRepo(root) : Promise.resolve()).then(() => executeAction(id, arg)); }; const activate = (i: number) => { @@ -607,7 +638,7 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack } variant="bare" onKeyDown={onKeyDown} /> - {!root && } + {!root && } {!root && 0} />}
@@ -632,7 +663,7 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack } aria-label="Branches" className={styles.list} empty={{loaded ? tx("No matching branches") : tx("Loading…")}} - renderItem={(r) => (r.type === "group" ? : )} + renderItem={(r) => (r.type === "group" ? : )} />
{menuFor && setMenuFor(null)} />} @@ -677,9 +708,8 @@ function MultiRepoPanel({ actions: popupActions, roots, current, -}: { - onClose: () => void; - actions: readonly PopupAction[]; + worktreeFor, +}: Pick & { roots: readonly string[]; current: string | null; }) { @@ -697,7 +727,8 @@ function MultiRepoPanel({ const options = usePopupOptions(); const sync = useWorkflowSettings((s) => s.vcs.git.syncBranchOperations); const [all, setAll] = useState>({}); - const [menuFor, setMenuFor] = useState<{ items: MenuItem[]; label: string; el: HTMLElement } | null>(null); + const unfetched = useVcs((s) => s.unfetched); + const { menuFor, setMenuFor, openTagMenu } = useBranchSubmenu(); const [repoMenu, setRepoMenu] = useState<{ root: string; el: HTMLElement; focus: boolean } | null>(null); const listRef = useRef(null); const searchRef = useRef(null); @@ -747,6 +778,7 @@ function MultiRepoPanel({ ...operationActions(op, conflicts), ...popupActions.map((a) => { if (a.id === "vcs.newBranch" && sync) return { ...a, arg: { repos: roots } }; + if (a.id === "vcs.checkoutRevision") return { ...a, arg: sync ? { repos: roots } : { repo: current } }; if (a.id === "vcs.newWorktree") return { ...a, arg: { repo: current } }; return a; }), @@ -795,17 +827,25 @@ function MultiRepoPanel({ } setRepoMenu(null); if (row.type === "common") { + const checkedOutInWorktree = !row.branch.remote && roots.some((root) => worktreeFor(root, row.branch.name)); const shared = widgetShowsRepo(repos) ? null : (repos[0]?.head ?? null); setMenuFor({ - items: commonBranchMenu(row.branch, roots, shared, closeAll), + items: commonBranchMenu(row.branch, roots, shared, closeAll, checkedOutInWorktree), label: tx`Branch ${row.branch.name}`, el, }); } else if (row.type === "branch") { - const items = inRepo(row.repo.root, branchMenu(row.branch, row.repo.head, closeAll)); + const items = inRepo( + row.repo.root, + branchMenu(row.branch, row.repo.head, closeAll, { + branches: all[row.repo.root], + headCommit: row.repo.headCommit, + existingWorktree: worktreeFor(row.repo.root, row.branch.name), + }), + ); setMenuFor({ items, label: tx`Branch ${row.branch.name} of ${row.repo.name}`, el }); } else if (row.type === "tag") { - setMenuFor({ items: inRepo(row.repo.root, tagMenu(row.tag, closeAll)), label: tx`Tag ${row.tag}`, el }); + openTagMenu(row.tag, el, closeAll, row.repo.root); } }; const activate = (i: number) => { @@ -813,7 +853,7 @@ function MultiRepoPanel({ if (!row) return; if (row.type === "action") { onClose(); - void executeAction(row.action.id, row.action.arg); + void executeAction(row.action.id, row.action.id === "vcs.newWorktree" ? { repo: current } : row.action.arg); } else if (row.type === "group") { if (!query.trim()) setOpen(row.key, !row.expanded); } else { @@ -878,7 +918,7 @@ function MultiRepoPanel({ variant="bare" onKeyDown={onKeyDown} /> - + 0} />
@@ -914,7 +954,18 @@ function MultiRepoPanel({ } renderItem={(r) => ( - + [root, r.branch.members[i]!]), + unfetched, + ) + : undefined + } + /> )} />
@@ -935,6 +986,7 @@ function MultiRepoPanel({ root={repoMenu.root} fallback={all[repoMenu.root]} actions={REPO_ACTIONS} + worktreeFor={worktreeFor} onClose={closeAll} onBack={closeRepoMenu} /> @@ -949,10 +1001,11 @@ function branchIndent(depth: number) { return depth ? { paddingInlineStart: `min(${depth * INDENT}px, ${(30 * depth) / (depth + 3)}%)` } : undefined; } -function RepoRowView({ row, operation }: { row: RepoRow; operation?: string }) { +function RepoRowView({ row, operation, sync }: { row: RepoRow; operation?: string; sync?: BranchSyncSummary }) { switch (row.type) { - case "action": case "branch": + return ; + case "action": case "tag": return ; case "repo": @@ -990,6 +1043,7 @@ function RepoRowView({ row, operation }: { row: RepoRow; operation?: string }) { current )} + {sync && } ); @@ -1014,7 +1068,18 @@ function GroupRowView({ row }: { row: { key: string; label: string; expanded: bo ); } -function BranchRowView({ row }: { row: BranchRow | Extract }) { +function BranchRowView({ + row, + repo, +}: { + row: BranchRow | Extract; + repo?: string; +}) { + const pending = useVcs((s) => + row.type === "branch" + ? unfetchedBranch(s.unfetched, repo ?? s.repo ?? s.roots[0] ?? null, row.branch.name, row.branch.trackedTip) + : undefined, + ); const indent = "depth" in row ? branchIndent(row.depth) : undefined; if (row.type === "action") { const keys = shortcutLabel(row.action.id); @@ -1083,7 +1148,7 @@ function BranchRowView({ row }: { row: BranchRow | Extractcurrent )} - + {!b.remote && b.upstream && ( {b.upstream} diff --git a/src/features/vcs/CombinedDiff.tsx b/src/features/vcs/CombinedDiff.tsx index 44af85b1e..80981b515 100644 --- a/src/features/vcs/CombinedDiff.tsx +++ b/src/features/vcs/CombinedDiff.tsx @@ -9,10 +9,11 @@ import { tx } from "@/platform/i18n"; import { relativeDir, useProject } from "@/platform/project"; import { Icon, IconButton, T, fileIconName } from "@/ui"; import { editorService, type EditorInput } from "@/workbench/contributions"; -import { setAllInOneDiff, type CombinedDiffData } from "./allInOneDiff"; -import { DiffEditor } from "./DiffEditor"; -import { diffInput, openDiff, withChain, type DiffData } from "./diffInput"; +import { combinedDiffDocumentOwner, setAllInOneDiff, type CombinedDiffData } from "./allInOneDiff"; +import { ResolvedDiffEditor } from "./DiffEditor"; +import { diffInput, hasGitlink, openDiff, withChain, type DiffData } from "./diffInput"; import { loadDiffOptions, saveDiffOptions } from "./diffOptions"; +import { useGitDiffEntries } from "./gitDiffEntries"; import { KIND_COLOR, KIND_LABEL, baseName, fileCount } from "./model"; import styles from "./CombinedDiff.module.css"; @@ -34,6 +35,7 @@ function Block({ collapsed, onToggle, mode, + tabKey, }: { item: DiffData; index: number; @@ -41,6 +43,7 @@ function Block({ collapsed: boolean; onToggle: () => void; mode: "split" | "unified"; + tabKey: string; }) { const ref = useRef(null); // Without IntersectionObserver (tests), every block loads at once. @@ -57,7 +60,10 @@ function Block({ io.observe(el); return () => io.disconnect(); }, [near]); - const input: EditorInput = useMemo(() => diffInput({ ...item, mode }), [item, mode]); + const request = useMemo(() => ({ ...item, mode }), [item, mode]); + const input = useMemo(() => diffInput(request), [request]); + const diff = useGitDiffEntries(request, near); + const gitlink = hasGitlink(diff.data); const kind = blockKind(item); const name = baseName(item.path); const root = useProject((s) => s.project?.root ?? ""); @@ -85,7 +91,7 @@ function Block({ // The file's own diff, still knowing its siblings for Compare Next File. onClick={() => void editorService().openInput(diffInput(withChain(items, index)), { focus: true })} /> - {item.right.type === "worktree" && ( + {near && !diff.loading && !gitlink && item.right.type === "worktree" && ( {name} + {gitlink && {tx("Submodule")}} {dir && {dir}} @@ -106,7 +113,12 @@ function Block({ working-tree document and, with autosave off, drop its unsaved edits. */} {near ? ( ) : ( !collapsed &&
@@ -215,6 +227,7 @@ export function CombinedDiffTab({ input }: { input: EditorInput }) { collapsed={collapsed.has(item.path)} onToggle={() => toggle(item.path)} mode={mode} + tabKey={input.key} /> )) ) : ( diff --git a/src/features/vcs/CommitAuthorFields.tsx b/src/features/vcs/CommitAuthorFields.tsx new file mode 100644 index 000000000..ec915a482 --- /dev/null +++ b/src/features/vcs/CommitAuthorFields.tsx @@ -0,0 +1,86 @@ +import { useId } from "react"; +import { tx } from "@/platform/i18n"; +import { IconButton, Input, T } from "@/ui"; +import styles from "./CommitView.module.css"; + +function localDateInput(date: Date): string { + return new Date(date.getTime() - date.getTimezoneOffset() * 60_000).toISOString().slice(0, 19); +} + +function gitAuthorDate(value: string): string | null { + const date = new Date(value); + if (!Number.isFinite(date.getTime())) return null; + const offset = -date.getTimezoneOffset(); + const pad = (number: number) => String(number).padStart(2, "0"); + const hours = pad(Math.floor(Math.abs(offset) / 60)); + const minutes = pad(Math.abs(offset) % 60); + return `${localDateInput(date)}${offset < 0 ? "-" : "+"}${hours}:${minutes}`; +} + +interface CommitAuthor { + author: string; + authorDate: string | null; +} + +export function CommitAuthorFields({ + author, + authorDate, + preserveOriginal, + focusAuthor, + onChange, +}: CommitAuthor & { + preserveOriginal: boolean; + focusAuthor?: boolean; + onChange: (update: Partial) => void; +}) { + const authorDateId = useId(); + const date = authorDate ? new Date(authorDate) : null; + return ( + <> + +
+ +
+ onChange({ authorDate: gitAuthorDate(e.target.value) })} + /> + {authorDate && ( + onChange({ authorDate: null })} + /> + )} +
+
+ + ); +} diff --git a/src/features/vcs/CommitCheckSummary.tsx b/src/features/vcs/CommitCheckSummary.tsx new file mode 100644 index 000000000..89dfc721e --- /dev/null +++ b/src/features/vcs/CommitCheckSummary.tsx @@ -0,0 +1,59 @@ +import { tx } from "@/platform/i18n"; +import { Icon, T } from "@/ui"; +import type { CommitCheckRun } from "./commitChecks"; +import styles from "./CommitView.module.css"; + +export function CommitCheckSummary({ + result, + onInspect, + onOpenToolWindow, +}: { + result: CommitCheckRun & { stale?: boolean }; + onInspect?: () => void; + onOpenToolWindow?: () => void; +}) { + const passed = !result.problems.length; + return ( +
{ + if (event.target instanceof Element && event.target.closest("button")) onInspect?.(); + }} + > + +
+ {passed ? ( + Commit checks passed + ) : ( + result.problems.map((p, i) => ( +
+ {tx(p.title)} + {" · "} + {typeof p.text === "string" ? tx(p.text) : p.text} + {p.details && ( + <> + {" "} + + + )} +
+ )) + )} +
+
+ ); +} diff --git a/src/features/vcs/CommitDialog.tsx b/src/features/vcs/CommitDialog.tsx index 69c9f208a..50734c7de 100644 --- a/src/features/vcs/CommitDialog.tsx +++ b/src/features/vcs/CommitDialog.tsx @@ -25,8 +25,11 @@ let open = false; /** Opens the Commit dialog (or focuses the message of the one open). */ export function showCommitDialog() { - useCommit.setState((s) => ({ tab: "changes", focusTick: s.focusTick + 1 })); - if (open) return; + if (open) { + useCommit.setState((s) => ({ focusTick: s.focusTick + 1 })); + return; + } + useCommit.setState({ tab: "changes" }); open = true; openDialog((close) => ( void }) { const included = useIncludedCount(); const amend = useCommit((s) => s.amend); - const problems = useCommit((s) => s.checkProblems.length > 0); + const blocked = useCommit((s) => !!s.checkResult?.blocked && !s.checkResult.stale); const remoteBusy = useVcs((s) => s.remoteBusy); const runner = useCommitRunner(included, onClose); return ( @@ -52,7 +55,7 @@ function CommitDialog({ onClose }: { onClose: () => void }) { width={880} buttons={[ { - label: commitLabel(amend, problems), + label: commitLabel(amend, blocked), role: "default", disabled: !runner.canCommit, title: "⌘↩", @@ -90,7 +93,7 @@ function CommitDialog({ onClose }: { onClose: () => void }) {
- +
diff --git a/src/features/vcs/CommitMessageDialog.module.css b/src/features/vcs/CommitMessageDialog.module.css index 2a2adf514..671955204 100644 --- a/src/features/vcs/CommitMessageDialog.module.css +++ b/src/features/vcs/CommitMessageDialog.module.css @@ -25,3 +25,48 @@ resize: none; line-height: 1.55; } + +.review { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +.filesColumn { + flex: 1 1 220px; + min-width: 0; + display: flex; + flex-direction: column; + gap: var(--space-1); +} + +.reviewOptions { + flex: 1 1 260px; + min-width: 0; + display: flex; + flex-direction: column; + gap: var(--space-2); + margin: 0; + padding: var(--space-2); + border: 1px solid var(--border); +} + +.files { + max-height: 160px; + overflow: auto; + margin: 0; + padding: var(--space-1); + border: 1px solid var(--border); + list-style: none; +} + +.files .file { + width: 100%; + justify-content: flex-start; +} + +.file span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} diff --git a/src/features/vcs/CommitMessageDialog.tsx b/src/features/vcs/CommitMessageDialog.tsx new file mode 100644 index 000000000..d3222c7cc --- /dev/null +++ b/src/features/vcs/CommitMessageDialog.tsx @@ -0,0 +1,207 @@ +import { useId, useLayoutEffect, useRef, useState, type ReactNode } from "react"; +import type { ApplyCommitOptions, ApplyCommitReview } from "@/bindings"; +import { fontWeightOf } from "@/platform/editorSettings"; +import { resolveMonoFont } from "@/platform/fonts"; +import { tx } from "@/platform/i18n"; +import { useProject } from "@/platform/project"; +import { Button, Checkbox, Dialog, T } from "@/ui"; +import { CommitAuthorFields } from "./CommitAuthorFields"; +import { withChain, workingDiffData } from "./diffInput"; +import { openDialog } from "./dialogs"; +import { relTo } from "./model"; +import styles from "./common.module.css"; +import messageStyles from "./CommitMessageDialog.module.css"; + +type ApplyOptionsForm = { + author: string; + authorDate: string | null; + signOff: boolean; + runHooks: boolean; +}; + +export async function promptApplyCommitMessage( + title: string, + repo: string, + review: ApplyCommitReview, + draft?: ApplyCommitOptions, +): Promise<{ message: string; options: ApplyCommitOptions } | null> { + let options: ApplyOptionsForm = { + author: draft?.author?.trim() || review.author || "", + authorDate: draft?.authorDate ?? review.authorDate ?? null, + signOff: draft?.signOff ?? false, + runHooks: draft?.runHooks ?? true, + }; + const showDiff = async (index: number) => { + const { openDiffDialog } = await import("./diffDialog"); + openDiffDialog( + withChain( + review.paths.map((path) => workingDiffData(path, undefined, "staged")), + index, + ), + ); + }; + const message = await promptCommitMessage( + title, + tx("Commit message"), + review.message, + "Commit and Continue", +
+
+ + Staged Changes + +
    + {review.paths.map((path, index) => ( +
  • + +
  • + ))} +
+
+ { + options = next; + }} + /> +
, + ); + if (message === null) return null; + const author = options.author.trim(); + return { + message, + options: { + ...options, + author: !author || author === review.author ? null : author, + authorDate: options.authorDate === review.authorDate ? null : options.authorDate, + }, + }; +} + +function ApplyCommitFields({ + initial, + preserveOriginal, + onChange, +}: { + initial: ApplyOptionsForm; + preserveOriginal: boolean; + onChange: (options: ApplyOptionsForm) => void; +}) { + const [options, setOptions] = useState(initial); + const update = (patch: Partial) => { + const next = { ...options, ...patch }; + setOptions(next); + onChange(next); + }; + return ( +
+ + Commit Options + + + update({ signOff })} /> + update({ runHooks })} /> +
+ ); +} + +export function promptCommitMessage( + title: string, + label: string, + initial: string, + okLabel = "OK", + children?: ReactNode, +): Promise { + return new Promise((resolve) => { + const close = openDialog(() => ( + { + close(); + resolve(m); + }} + > + {children} + + )); + }); +} + +function MessageDialog({ + title, + label, + initial, + okLabel, + onDone, + children, +}: { + title: string; + label: string; + initial: string; + okLabel: string; + onDone: (message: string | null) => void; + children?: ReactNode; +}) { + const id = useId(); + const field = useRef(null); + const [message, setMessage] = useState(initial); + const editor = useProject((s) => s.settings?.editor); + const { family, size } = resolveMonoFont(undefined, editor); + useLayoutEffect(() => field.current?.setSelectionRange(0, 0), []); + + return ( + onDone(null)} + width={620} + minWidth={340} + resizable="both" + className={messageStyles.dialog} + buttons={[ + { label: okLabel, role: "default", disabled: !message.trim(), onClick: () => onDone(message) }, + { label: "Cancel", role: "cancel" }, + ]} + > +
+ {children} + +