diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 172c77e..59b53e6 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1294,6 +1294,325 @@ "gitSearchBranches": "Search branches...", "gitSearchTags": "Search tags...", "gitNoBranches": "No branches", + + "gitRemoteBranches": "Remote Branches", + "gitLocalBranches": "Local Branches", + "gitNoRemoteBranches": "No remote branches yet — fetch first", + "gitCheckoutRemoteBranch": "Check out as local branch", + "gitRemoteBranchCheckedOut": "Already checked out locally", + "gitCheckoutRemoteBranchSuccess": "Created and switched to local branch {branch} from {remote}", + "@gitCheckoutRemoteBranchSuccess": { + "placeholders": { + "remote": { + "type": "String" + }, + "branch": { + "type": "String" + } + } + }, + "gitSearchRemoteBranches": "Search remote branches...", + + "gitRepairCheck": "Repository Check", + "gitRepairCheckRunning": "Checking...", + "gitRepairCheckHealthy": "Repository is intact, no missing objects", + "gitRepairCheckHealthyHint": "Object database verified. Committing and syncing should work normally.", + "gitRepairCheckObjectLoss": "Missing objects detected ({count} problems)", + "@gitRepairCheckObjectLoss": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "gitRepairCheckObjectLossHint": "This kind of damage causes \"Error building trees\" on commit. It usually happens when the container is rebuilt and .git/objects is lost. Back up the project directory first, then follow the advice below.", + "gitRepairCheckDangling": "{count} dangling objects (normal, no action needed)", + "@gitRepairCheckDangling": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "gitRepairCheckFailed": "The check could not complete", + "gitRepairCheckFailedHint": "The repository may be large or the command timed out. Try again later.", + "gitRepairCheckRerun": "Run Again", + "gitRepairAdviceTitle": "How to handle this", + "gitRepairAdviceRemoveStale": "Uncommitted broken entries: run git reset to realign the index with the last commit, then stage the files again.", + "gitRepairAdviceRestore": "Damaged committed history: re-clone from the remote, or restore from another copy.", + + "gitClone": "Clone Repository", + "gitCloneUrl": "Repository URL", + "gitCloneUrlHint": "https://github.com/user/repo.git", + "gitCloneDirName": "Local directory name", + "gitCloneDirNameHint": "Leave empty to derive from the URL", + "gitCloneBranch": "Branch (optional)", + "gitCloneBranchHint": "Leave empty to use the remote default branch", + "gitCloneDepth": "Shallow clone depth (optional)", + "gitCloneDepthHint": "e.g. 1 clones only the latest commit", + "gitCloneUrlRequired": "Please enter a repository URL", + "gitCloneDirRequired": "Please enter a local directory name", + "gitCloneDirExists": "Directory already exists, choose another name", + "gitCloneRunning": "Cloning...", + "gitCloneSuccess": "Clone complete: {name}", + "@gitCloneSuccess": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "gitCloneFailed": "Clone failed", + "gitCloneCancel": "Cancel clone", + + "gitPushTargetTooltip": "Push target: {name}\n{reason}", + "@gitPushTargetTooltip": { + "placeholders": { + "name": { + "type": "String" + }, + "reason": { + "type": "String" + } + } + }, + "gitPushReasonPushRemote": "Set by branch config branch.*.pushRemote", + "gitPushReasonPushDefault": "Set by repo config remote.pushDefault", + "gitPushReasonUpstream": "The upstream remote of this branch", + "gitPushReasonBranchRemote": "Set by branch config branch.*.remote", + "gitPushReasonFallback": "Default remote (origin preferred)", + "gitPushReasonOverridden": "You switched it manually in this session", + "gitFetchTargetTooltip": "Fetch target: {name}", + "@gitFetchTargetTooltip": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "gitTogglePushTarget": "Choose push target", + "gitSyncCloudTooltip": "Sync: fetch / pull / push", + "gitPushTargetChanged": "Push target switched to {name}", + "@gitPushTargetChanged": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "gitPushTargetDiffers": "Push target differs from upstream", + "gitPushTargetDiffersNotice": "Pull from {upstream}, push to {push}", + "@gitPushTargetDiffersNotice": { + "placeholders": { + "upstream": { + "type": "String" + }, + "push": { + "type": "String" + } + } + }, + "gitRemoteRoleUpstream": "Upstream (fetch)", + + "gitErrAuthFailed": "Authentication failed: invalid or expired token, or username mismatch", + "gitErrAuthFailedHint": "Check the token in Git Accounts, and make sure the username matches your login name on that platform.", + "gitErrWritePermissionDenied": "This account has no write access to this repository", + "gitErrWritePermissionDeniedHint": "If this is someone else's repository (upstream), fork it to your own account first, then point the remote at your fork (e.g. https://github.com/your-name/repo.git).", + "gitErrRepositoryNotFound": "Repository not found, or this account has no access to it", + "gitErrRepositoryNotFoundHint": "GitHub returns 404 for both \"no permission\" and \"does not exist\". Verify the remote URL and that the token can access this repository.", + "gitErrProxyAuthRequired": "The network proxy requires authentication", + "gitErrProxyAuthRequiredHint": "This network goes through an authenticated proxy (HTTP 407). Check the proxy configuration and credentials inside the container.", + "gitErrRequestRejected": "The server rejected this request", + "gitErrRequestRejectedHint": "Usually means the pushed content or branch reference is invalid (HTTP 422), e.g. a branch name that violates platform rules or a blocked commit.", + "gitErrRateLimited": "Too many requests, rate limited by the platform", + "gitErrRateLimitedHint": "Wait a few minutes and retry (HTTP 429). Retrying repeatedly will extend the limit.", + "gitErrHttpError": "The server returned an error status code", + "gitErrHttpErrorHint": "Check the status code below: 401 invalid token, 403 no permission, 404 not found or no access, 407 proxy auth required, 429 rate limited.", + "gitErrPasswordAuthDisabled": "This platform has disabled password authentication", + "gitErrPasswordAuthDisabledHint": "Add the account again using a personal access token (PAT) in Git Accounts.", + "gitErrNetworkUnreachable": "Cannot reach the remote server over the network", + "gitErrNetworkUnreachableHint": "Check your network connection and the container DNS configuration (/etc/resolv.conf).", + "gitErrSshPublicKeyDenied": "SSH public key authentication was rejected", + "gitErrSshPublicKeyDeniedHint": "Make sure the container's public key is added to the platform's SSH keys, or switch to HTTPS with an access token.", + "gitErrSshKeyUnusable": "The SSH private key is unusable (bad permissions or format)", + "gitErrSshKeyUnusableHint": "The private key must have mode 600. You can regenerate the key pair in Git Accounts.", + "gitErrHostKeyUnverified": "The server host fingerprint is not confirmed yet, connection aborted", + "gitErrHostKeyUnverifiedHint": "The first connection requires confirming the host fingerprint. If the server key changed, clear ~/.ssh/known_hosts in the container and retry.", + "gitErrNonFastForward": "Push rejected: the remote has commits you do not have locally", + "gitErrNonFastForwardHint": "Pull first (rebase mode) to merge the remote changes, then push again.", + "gitErrStaleForcePush": "Force push rejected: someone else updated the remote branch", + "gitErrStaleForcePushHint": "Fetch the latest remote state first, review the differences, then force push again.", + "gitErrConflictDetected": "Merge/rebase conflicts must be resolved manually", + "gitErrConflictDetectedHint": "Resolve the conflicting files one by one, or abort this operation (git rebase --abort).", + "gitErrLocalChanges": "Local uncommitted changes would be overwritten, operation aborted", + "gitErrLocalChangesHint": "Commit your changes first, or stash them, then retry.", + "gitErrNoUpstream": "This branch is not tracking a remote branch yet", + "gitErrNoUpstreamHint": "Use Publish Branch to push it to the remote and set up tracking.", + "gitErrRefLockFailed": "A Git reference file is locked (stale lock)", + "gitErrRefLockFailedHint": "Another Git process may be running. Retry shortly, or remove the .lock files under .git.", + "gitErrOutOfSpace": "Not enough storage space on the device", + "gitErrOutOfSpaceHint": "Free up space in the container or on the device, then retry.", + "gitErrTimeout": "Operation timed out", + "gitErrTimeoutHint": "Large repositories or slow networks can time out. Watch the progress in the terminal instead, or retry on a better connection.", + "gitErrIncomplete": "The operation did not finish, and no specific error was returned", + "gitErrIncompleteHint": "It was most likely interrupted by a timeout or a dropped connection. For large repositories, run fetch in the terminal to watch progress, or retry on a better connection.", + "gitErrUnknown": "Git operation failed", + "gitErrUnknownHint": "Expand the raw output below for details.", + "gitRawOutput": "Raw output", + + "gitElapsed": "Elapsed {time}", + "@gitElapsed": { + "placeholders": { + "time": { + "type": "String" + } + } + }, + "gitElapsedMinutesSeconds": "{minutes}:{seconds}", + "@gitElapsedMinutesSeconds": { + "placeholders": { + "minutes": { + "type": "int" + }, + "seconds": { + "type": "String" + } + } + }, + + "gitFetch": "Fetch", + "gitFetchTooltip": "Fetch the latest commits from the remote without merging", + "gitPull": "Pull", + "gitPullTooltip": "Pull remote commits and rebase the current branch onto them", + "gitPush": "Push", + "gitPushTooltip": "Push local commits to the remote", + "gitPublishBranch": "Publish Branch", + "gitPublishBranchTooltip": "Push this local branch to the remote and set up tracking", + "gitSync": "Sync", + "gitSyncTooltip": "Pull remote changes, then push local commits", + "gitCancelOperation": "Cancel", + "gitRemoteOperationRunning": "Remote operation in progress...", + "gitRemoteOperationCancelled": "Operation cancelled", + "gitRemoteOperationBusy": "Another remote operation is already running", + "gitFetchSuccess": "Fetch completed", + "gitFetchNoChanges": "Already up to date", + "gitPullSuccess": "Pull completed", + "gitPullAlreadyUpToDate": "Already up to date, nothing to pull", + "gitPushSuccess": "Push completed", + "gitPushUpToDate": "Remote is already up to date, nothing to push", + "gitNoRemoteConfigured": "No Remote Configured", + "gitNoRemoteDesc": "Add a remote repository URL to fetch, pull, and push your code.", + "gitAddRemote": "Add Remote", + "gitRemoteManagement": "Remote Repositories", + "gitRemoteName": "Remote Name", + "gitRemoteNameHint": "e.g. origin", + "gitRemoteUrl": "Remote URL", + "gitRemoteUrlHint": "https://github.com/user/repo.git or git@github.com:user/repo.git", + "gitRemotePushUrl": "Push URL (optional)", + "gitRemotePushUrlHint": "Leave empty to use the fetch URL", + "gitRemoteNameRequired": "Please enter a remote name", + "gitRemoteUrlRequired": "Please enter a remote URL", + "gitRemoteAdded": "Added remote {name}", + "@gitRemoteAdded": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "gitRemoteRemoved": "Removed remote {name}", + "@gitRemoteRemoved": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "gitRemoteRenamed": "Renamed {old} to {newName}", + "@gitRemoteRenamed": { + "placeholders": { + "old": { + "type": "String" + }, + "newName": { + "type": "String" + } + } + }, + "gitRemoteUrlUpdated": "Remote URL updated", + "gitRemotePruned": "Pruned stale remote branches", + "gitRemoteRemoveConfirm": "Remove remote {name}? Your local code will not be deleted.", + "@gitRemoteRemoveConfirm": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "gitRemoteEdit": "Edit Remote", + "gitRemoteFetchUrl": "Fetch URL", + "gitRemoteSetPushUrl": "Set Push URL", + "gitRemotePrune": "Prune Stale Branches", + "gitCheckConnection": "Test Connection", + "gitCheckConnectionSuccess": "Connection OK, authentication works", + "gitNoRemotes": "No remotes", + "gitFetchFailed": "Fetch failed", + "gitPullFailed": "Pull failed", + "gitPushFailed": "Push failed", + "gitForcePush": "Force Push", + "gitForcePushTooltip": "Overwrite the remote branch (uses --force-with-lease for safety)", + "gitForcePushWarning": "Force pushing overwrites the remote branch with your local commits and may discard other people's work.", + "gitForcePushConfirm": "Confirm Force Push", + "gitForcePushConfirmDesc": "This rewrites the history of remote branch {branch}. Only use it when you are certain nobody else pushed new commits.", + "@gitForcePushConfirmDesc": { + "placeholders": { + "branch": { + "type": "String" + } + } + }, + "gitForcePushUseLease": "Use safe force push (--force-with-lease)", + "gitPullThenPush": "Pull Then Push", + "gitPullThenPushDesc": "The remote has commits you do not have. Pull and merge them before pushing.", + "gitConflictAbort": "Abort Rebase", + "gitConflictAbortConfirm": "Abort this rebase and return to the state before it started?", + "gitUncommittedChangesTitle": "Uncommitted Changes", + "gitUncommittedChangesDesc": "Local uncommitted changes must be handled before pulling, or they may be overwritten.", + "gitUncommittedStashAndPull": "Stash and Pull", + "gitUncommittedCommitFirst": "Commit First", + "gitUncommittedCancel": "Cancel", + "gitStashAndPullSuccess": "Stashed local changes and pulled successfully", + "gitViewOperationLog": "View Details", + "gitHideOperationLog": "Hide Details", + "gitAheadBehind": "{ahead} ahead / {behind} behind", + "@gitAheadBehind": { + "placeholders": { + "ahead": { + "type": "int" + }, + "behind": { + "type": "int" + } + } + }, + "gitUpstreamGone": "Upstream branch no longer exists", + "gitBehindTooltip": "{behind} commits behind the remote", + "@gitBehindTooltip": { + "placeholders": { + "behind": { + "type": "int" + } + } + }, + "gitAheadTooltip": "{ahead} commits ahead of the remote", + "@gitAheadTooltip": { + "placeholders": { + "ahead": { + "type": "int" + } + } + }, + "gitDiff": "Diff", "gitDiffOriginal": "Original", "gitDiffModified": "Modified", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index c74306e..e8734a3 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3766,6 +3766,1008 @@ abstract class AppLocalizations { /// **'暂无分支'** String get gitNoBranches; + /// No description provided for @gitRemoteBranches. + /// + /// In zh, this message translates to: + /// **'远端分支'** + String get gitRemoteBranches; + + /// No description provided for @gitLocalBranches. + /// + /// In zh, this message translates to: + /// **'本地分支'** + String get gitLocalBranches; + + /// No description provided for @gitNoRemoteBranches. + /// + /// In zh, this message translates to: + /// **'暂无远端分支,请先执行抓取'** + String get gitNoRemoteBranches; + + /// No description provided for @gitCheckoutRemoteBranch. + /// + /// In zh, this message translates to: + /// **'检出为本地分支'** + String get gitCheckoutRemoteBranch; + + /// No description provided for @gitRemoteBranchCheckedOut. + /// + /// In zh, this message translates to: + /// **'该远端分支已在本地检出'** + String get gitRemoteBranchCheckedOut; + + /// No description provided for @gitCheckoutRemoteBranchSuccess. + /// + /// In zh, this message translates to: + /// **'已基于 {remote} 创建并切换到本地分支 {branch}'** + String gitCheckoutRemoteBranchSuccess(String remote, String branch); + + /// No description provided for @gitSearchRemoteBranches. + /// + /// In zh, this message translates to: + /// **'搜索远端分支...'** + String get gitSearchRemoteBranches; + + /// No description provided for @gitRepairCheck. + /// + /// In zh, this message translates to: + /// **'仓库自检'** + String get gitRepairCheck; + + /// No description provided for @gitRepairCheckRunning. + /// + /// In zh, this message translates to: + /// **'正在自检...'** + String get gitRepairCheckRunning; + + /// No description provided for @gitRepairCheckHealthy. + /// + /// In zh, this message translates to: + /// **'仓库完整,未发现对象丢失'** + String get gitRepairCheckHealthy; + + /// No description provided for @gitRepairCheckHealthyHint. + /// + /// In zh, this message translates to: + /// **'对象库校验通过,可以正常提交与同步。'** + String get gitRepairCheckHealthyHint; + + /// No description provided for @gitRepairCheckObjectLoss. + /// + /// In zh, this message translates to: + /// **'检测到对象丢失({count} 处问题)'** + String gitRepairCheckObjectLoss(int count); + + /// No description provided for @gitRepairCheckObjectLossHint. + /// + /// In zh, this message translates to: + /// **'这类损坏会导致提交时报错 Error building trees。常见原因是容器被重建导致 .git/objects 丢失。建议先备份项目目录,再按下方提示处理。'** + String get gitRepairCheckObjectLossHint; + + /// No description provided for @gitRepairCheckDangling. + /// + /// In zh, this message translates to: + /// **'另有 {count} 个悬空对象(正常现象,无需处理)'** + String gitRepairCheckDangling(int count); + + /// No description provided for @gitRepairCheckFailed. + /// + /// In zh, this message translates to: + /// **'自检未能完成'** + String get gitRepairCheckFailed; + + /// No description provided for @gitRepairCheckFailedHint. + /// + /// In zh, this message translates to: + /// **'可能因为仓库过大或执行超时,可稍后重试。'** + String get gitRepairCheckFailedHint; + + /// No description provided for @gitRepairCheckRerun. + /// + /// In zh, this message translates to: + /// **'重新自检'** + String get gitRepairCheckRerun; + + /// No description provided for @gitRepairAdviceTitle. + /// + /// In zh, this message translates to: + /// **'如何处理'** + String get gitRepairAdviceTitle; + + /// No description provided for @gitRepairAdviceRemoveStale. + /// + /// In zh, this message translates to: + /// **'未提交的损坏条目:执行 git reset 让索引与最后一次提交对齐,然后重新暂存需要的文件。'** + String get gitRepairAdviceRemoveStale; + + /// No description provided for @gitRepairAdviceRestore. + /// + /// In zh, this message translates to: + /// **'已提交的历史损坏:需要从远端重新克隆,或从其他副本恢复。'** + String get gitRepairAdviceRestore; + + /// No description provided for @gitClone. + /// + /// In zh, this message translates to: + /// **'克隆远程仓库'** + String get gitClone; + + /// No description provided for @gitCloneUrl. + /// + /// In zh, this message translates to: + /// **'仓库地址'** + String get gitCloneUrl; + + /// No description provided for @gitCloneUrlHint. + /// + /// In zh, this message translates to: + /// **'https://github.com/user/repo.git'** + String get gitCloneUrlHint; + + /// No description provided for @gitCloneDirName. + /// + /// In zh, this message translates to: + /// **'本地目录名'** + String get gitCloneDirName; + + /// No description provided for @gitCloneDirNameHint. + /// + /// In zh, this message translates to: + /// **'留空则从地址自动推导'** + String get gitCloneDirNameHint; + + /// No description provided for @gitCloneBranch. + /// + /// In zh, this message translates to: + /// **'指定分支(可选)'** + String get gitCloneBranch; + + /// No description provided for @gitCloneBranchHint. + /// + /// In zh, this message translates to: + /// **'留空则使用远端默认分支'** + String get gitCloneBranchHint; + + /// No description provided for @gitCloneDepth. + /// + /// In zh, this message translates to: + /// **'浅克隆深度(可选)'** + String get gitCloneDepth; + + /// No description provided for @gitCloneDepthHint. + /// + /// In zh, this message translates to: + /// **'如 1 表示只克隆最近 1 个提交'** + String get gitCloneDepthHint; + + /// No description provided for @gitCloneUrlRequired. + /// + /// In zh, this message translates to: + /// **'请输入仓库地址'** + String get gitCloneUrlRequired; + + /// No description provided for @gitCloneDirRequired. + /// + /// In zh, this message translates to: + /// **'请输入本地目录名'** + String get gitCloneDirRequired; + + /// No description provided for @gitCloneDirExists. + /// + /// In zh, this message translates to: + /// **'目录已存在,请换一个名字'** + String get gitCloneDirExists; + + /// No description provided for @gitCloneRunning. + /// + /// In zh, this message translates to: + /// **'正在克隆...'** + String get gitCloneRunning; + + /// No description provided for @gitCloneSuccess. + /// + /// In zh, this message translates to: + /// **'克隆完成:{name}'** + String gitCloneSuccess(String name); + + /// No description provided for @gitCloneFailed. + /// + /// In zh, this message translates to: + /// **'克隆失败'** + String get gitCloneFailed; + + /// No description provided for @gitCloneCancel. + /// + /// In zh, this message translates to: + /// **'取消克隆'** + String get gitCloneCancel; + + /// No description provided for @gitPushTargetTooltip. + /// + /// In zh, this message translates to: + /// **'推送目标:{name}\n{reason}'** + String gitPushTargetTooltip(String name, String reason); + + /// No description provided for @gitPushReasonPushRemote. + /// + /// In zh, this message translates to: + /// **'由分支配置 branch.*.pushRemote 决定'** + String get gitPushReasonPushRemote; + + /// No description provided for @gitPushReasonPushDefault. + /// + /// In zh, this message translates to: + /// **'由仓库配置 remote.pushDefault 决定'** + String get gitPushReasonPushDefault; + + /// No description provided for @gitPushReasonUpstream. + /// + /// In zh, this message translates to: + /// **'当前分支的上游远程'** + String get gitPushReasonUpstream; + + /// No description provided for @gitPushReasonBranchRemote. + /// + /// In zh, this message translates to: + /// **'由分支配置 branch.*.remote 决定'** + String get gitPushReasonBranchRemote; + + /// No description provided for @gitPushReasonFallback. + /// + /// In zh, this message translates to: + /// **'默认远程(origin 优先)'** + String get gitPushReasonFallback; + + /// No description provided for @gitPushReasonOverridden. + /// + /// In zh, this message translates to: + /// **'你已在本次会话中手动切换'** + String get gitPushReasonOverridden; + + /// No description provided for @gitFetchTargetTooltip. + /// + /// In zh, this message translates to: + /// **'抓取目标:{name}'** + String gitFetchTargetTooltip(String name); + + /// No description provided for @gitTogglePushTarget. + /// + /// In zh, this message translates to: + /// **'选择推送目标'** + String get gitTogglePushTarget; + + /// No description provided for @gitSyncCloudTooltip. + /// + /// In zh, this message translates to: + /// **'同步:抓取 / 拉取 / 推送'** + String get gitSyncCloudTooltip; + + /// No description provided for @gitPushTargetChanged. + /// + /// In zh, this message translates to: + /// **'推送目标已切换为 {name}'** + String gitPushTargetChanged(String name); + + /// No description provided for @gitPushTargetDiffers. + /// + /// In zh, this message translates to: + /// **'推送目标与上游不同'** + String get gitPushTargetDiffers; + + /// No description provided for @gitPushTargetDiffersNotice. + /// + /// In zh, this message translates to: + /// **'拉取走 {upstream},推送走 {push}'** + String gitPushTargetDiffersNotice(String upstream, String push); + + /// No description provided for @gitRemoteRoleUpstream. + /// + /// In zh, this message translates to: + /// **'上游(拉取)'** + String get gitRemoteRoleUpstream; + + /// No description provided for @gitErrAuthFailed. + /// + /// In zh, this message translates to: + /// **'认证失败:令牌无效、已过期或用户名不匹配'** + String get gitErrAuthFailed; + + /// No description provided for @gitErrAuthFailedHint. + /// + /// In zh, this message translates to: + /// **'请到「Git 账号管理」检查令牌是否有效,并确认账号用户名与平台登录名一致。'** + String get gitErrAuthFailedHint; + + /// No description provided for @gitErrWritePermissionDenied. + /// + /// In zh, this message translates to: + /// **'当前账号对该仓库没有写权限'** + String get gitErrWritePermissionDenied; + + /// No description provided for @gitErrWritePermissionDeniedHint. + /// + /// In zh, this message translates to: + /// **'若这是别人的仓库(上游),请先 Fork 到你自己的账号,再把远端地址改为你的 Fork(如 https://github.com/你的用户名/仓库.git)。'** + String get gitErrWritePermissionDeniedHint; + + /// No description provided for @gitErrRepositoryNotFound. + /// + /// In zh, this message translates to: + /// **'仓库不存在,或当前账号无权访问'** + String get gitErrRepositoryNotFound; + + /// No description provided for @gitErrRepositoryNotFoundHint. + /// + /// In zh, this message translates to: + /// **'GitHub 对「无权限」和「不存在」都返回 404。请确认远端地址拼写正确,且该令牌有权访问该仓库。'** + String get gitErrRepositoryNotFoundHint; + + /// No description provided for @gitErrProxyAuthRequired. + /// + /// In zh, this message translates to: + /// **'网络代理需要认证'** + String get gitErrProxyAuthRequired; + + /// No description provided for @gitErrProxyAuthRequiredHint. + /// + /// In zh, this message translates to: + /// **'当前网络经过需要认证的代理(HTTP 407)。请检查容器内代理配置与凭据。'** + String get gitErrProxyAuthRequiredHint; + + /// No description provided for @gitErrRequestRejected. + /// + /// In zh, this message translates to: + /// **'服务器拒绝了本次请求'** + String get gitErrRequestRejected; + + /// No description provided for @gitErrRequestRejectedHint. + /// + /// In zh, this message translates to: + /// **'通常表示推送内容或分支引用不合法(HTTP 422),例如分支名不符合平台规则或提交信息被策略拦截。'** + String get gitErrRequestRejectedHint; + + /// No description provided for @gitErrRateLimited. + /// + /// In zh, this message translates to: + /// **'请求过于频繁,已被平台限流'** + String get gitErrRateLimited; + + /// No description provided for @gitErrRateLimitedHint. + /// + /// In zh, this message translates to: + /// **'请稍等几分钟后重试(HTTP 429)。短时间内反复重试会延长限制时间。'** + String get gitErrRateLimitedHint; + + /// No description provided for @gitErrHttpError. + /// + /// In zh, this message translates to: + /// **'服务器返回了错误状态码'** + String get gitErrHttpError; + + /// No description provided for @gitErrHttpErrorHint. + /// + /// In zh, this message translates to: + /// **'请根据下方状态码排查:401 令牌无效、403 无权限、404 仓库不存在或无权访问、407 需要代理认证、429 被限流。'** + String get gitErrHttpErrorHint; + + /// No description provided for @gitErrPasswordAuthDisabled. + /// + /// In zh, this message translates to: + /// **'该平台已禁用账号密码认证'** + String get gitErrPasswordAuthDisabled; + + /// No description provided for @gitErrPasswordAuthDisabledHint. + /// + /// In zh, this message translates to: + /// **'请在「Git 账号管理」中使用个人访问令牌 (PAT) 重新添加账号。'** + String get gitErrPasswordAuthDisabledHint; + + /// No description provided for @gitErrNetworkUnreachable. + /// + /// In zh, this message translates to: + /// **'网络无法连接到远端服务器'** + String get gitErrNetworkUnreachable; + + /// No description provided for @gitErrNetworkUnreachableHint. + /// + /// In zh, this message translates to: + /// **'请检查网络连接,以及容器内 DNS 配置(/etc/resolv.conf)是否正常。'** + String get gitErrNetworkUnreachableHint; + + /// No description provided for @gitErrSshPublicKeyDenied. + /// + /// In zh, this message translates to: + /// **'SSH 公钥认证被拒绝'** + String get gitErrSshPublicKeyDenied; + + /// No description provided for @gitErrSshPublicKeyDeniedHint. + /// + /// In zh, this message translates to: + /// **'请确认容器内的公钥已添加到平台的 SSH Keys 中,或改用 HTTPS + 访问令牌。'** + String get gitErrSshPublicKeyDeniedHint; + + /// No description provided for @gitErrSshKeyUnusable. + /// + /// In zh, this message translates to: + /// **'SSH 私钥无法使用(权限或格式异常)'** + String get gitErrSshKeyUnusable; + + /// No description provided for @gitErrSshKeyUnusableHint. + /// + /// In zh, this message translates to: + /// **'私钥权限需为 600。可在「Git 账号管理」中重新生成密钥对。'** + String get gitErrSshKeyUnusableHint; + + /// No description provided for @gitErrHostKeyUnverified. + /// + /// In zh, this message translates to: + /// **'目标服务器的主机指纹尚未确认,连接被中断'** + String get gitErrHostKeyUnverified; + + /// No description provided for @gitErrHostKeyUnverifiedHint. + /// + /// In zh, this message translates to: + /// **'首次连接需要确认主机指纹。若刚更换过服务器密钥,请清理容器内 ~/.ssh/known_hosts 后重试。'** + String get gitErrHostKeyUnverifiedHint; + + /// No description provided for @gitErrNonFastForward. + /// + /// In zh, this message translates to: + /// **'推送被拒绝:远端存在本地尚无的提交'** + String get gitErrNonFastForward; + + /// No description provided for @gitErrNonFastForwardHint. + /// + /// In zh, this message translates to: + /// **'请先执行 Pull(rebase 方式)合并远端改动,再重新推送。'** + String get gitErrNonFastForwardHint; + + /// No description provided for @gitErrStaleForcePush. + /// + /// In zh, this message translates to: + /// **'强推被拒绝:远端分支已被他人更新'** + String get gitErrStaleForcePush; + + /// No description provided for @gitErrStaleForcePushHint. + /// + /// In zh, this message translates to: + /// **'请先执行 Fetch 获取最新远端状态,确认差异后再强制推送。'** + String get gitErrStaleForcePushHint; + + /// No description provided for @gitErrConflictDetected. + /// + /// In zh, this message translates to: + /// **'合并/rebase 出现冲突,需要手动解决'** + String get gitErrConflictDetected; + + /// No description provided for @gitErrConflictDetectedHint. + /// + /// In zh, this message translates to: + /// **'请逐个解决冲突文件,或放弃本次操作(git rebase --abort)。'** + String get gitErrConflictDetectedHint; + + /// No description provided for @gitErrLocalChanges. + /// + /// In zh, this message translates to: + /// **'本地未提交的改动会被覆盖,操作已中止'** + String get gitErrLocalChanges; + + /// No description provided for @gitErrLocalChangesHint. + /// + /// In zh, this message translates to: + /// **'请先提交改动,或将其贮藏(stash)后再执行。'** + String get gitErrLocalChangesHint; + + /// No description provided for @gitErrNoUpstream. + /// + /// In zh, this message translates to: + /// **'当前分支尚未关联远端分支'** + String get gitErrNoUpstream; + + /// No description provided for @gitErrNoUpstreamHint. + /// + /// In zh, this message translates to: + /// **'请使用「发布分支」将本地分支推送到远端并建立追踪关系。'** + String get gitErrNoUpstreamHint; + + /// No description provided for @gitErrRefLockFailed. + /// + /// In zh, this message translates to: + /// **'Git 引用文件被占用(存在残留锁)'** + String get gitErrRefLockFailed; + + /// No description provided for @gitErrRefLockFailedHint. + /// + /// In zh, this message translates to: + /// **'可能有另一个 Git 进程正在运行。稍后重试,或清理 .git 目录下的 .lock 文件。'** + String get gitErrRefLockFailedHint; + + /// No description provided for @gitErrOutOfSpace. + /// + /// In zh, this message translates to: + /// **'设备存储空间不足'** + String get gitErrOutOfSpace; + + /// No description provided for @gitErrOutOfSpaceHint. + /// + /// In zh, this message translates to: + /// **'请清理容器或设备空间后重试。'** + String get gitErrOutOfSpaceHint; + + /// No description provided for @gitErrTimeout. + /// + /// In zh, this message translates to: + /// **'操作超时'** + String get gitErrTimeout; + + /// No description provided for @gitErrTimeoutHint. + /// + /// In zh, this message translates to: + /// **'仓库较大或网络较慢时可能超时。可改用终端观察进度,或在网络较好时重试。'** + String get gitErrTimeoutHint; + + /// No description provided for @gitErrIncomplete. + /// + /// In zh, this message translates to: + /// **'操作未完成,但没有返回具体错误信息'** + String get gitErrIncomplete; + + /// No description provided for @gitErrIncompleteHint. + /// + /// In zh, this message translates to: + /// **'通常是被超时或网络中断打断。仓库较大时建议改用终端执行 fetch 观察进度,或稍后在网络较好时重试。'** + String get gitErrIncompleteHint; + + /// No description provided for @gitErrUnknown. + /// + /// In zh, this message translates to: + /// **'Git 操作失败'** + String get gitErrUnknown; + + /// No description provided for @gitErrUnknownHint. + /// + /// In zh, this message translates to: + /// **'请展开下方原始输出查看详细信息。'** + String get gitErrUnknownHint; + + /// No description provided for @gitRawOutput. + /// + /// In zh, this message translates to: + /// **'原始输出'** + String get gitRawOutput; + + /// No description provided for @gitElapsed. + /// + /// In zh, this message translates to: + /// **'已用 {time}'** + String gitElapsed(String time); + + /// No description provided for @gitElapsedMinutesSeconds. + /// + /// In zh, this message translates to: + /// **'{minutes}:{seconds}'** + String gitElapsedMinutesSeconds(int minutes, String seconds); + + /// No description provided for @gitFetch. + /// + /// In zh, this message translates to: + /// **'抓取'** + String get gitFetch; + + /// No description provided for @gitFetchTooltip. + /// + /// In zh, this message translates to: + /// **'从远端抓取最新提交(不合并到本地)'** + String get gitFetchTooltip; + + /// No description provided for @gitPull. + /// + /// In zh, this message translates to: + /// **'拉取'** + String get gitPull; + + /// No description provided for @gitPullTooltip. + /// + /// In zh, this message translates to: + /// **'拉取远端提交并以 rebase 方式合并到当前分支'** + String get gitPullTooltip; + + /// No description provided for @gitPush. + /// + /// In zh, this message translates to: + /// **'推送'** + String get gitPush; + + /// No description provided for @gitPushTooltip. + /// + /// In zh, this message translates to: + /// **'将本地提交推送到远端'** + String get gitPushTooltip; + + /// No description provided for @gitPublishBranch. + /// + /// In zh, this message translates to: + /// **'发布分支'** + String get gitPublishBranch; + + /// No description provided for @gitPublishBranchTooltip. + /// + /// In zh, this message translates to: + /// **'将本地分支推送到远端并建立追踪关系'** + String get gitPublishBranchTooltip; + + /// No description provided for @gitSync. + /// + /// In zh, this message translates to: + /// **'同步'** + String get gitSync; + + /// No description provided for @gitSyncTooltip. + /// + /// In zh, this message translates to: + /// **'先拉取远端改动,再推送本地提交'** + String get gitSyncTooltip; + + /// No description provided for @gitCancelOperation. + /// + /// In zh, this message translates to: + /// **'取消'** + String get gitCancelOperation; + + /// No description provided for @gitRemoteOperationRunning. + /// + /// In zh, this message translates to: + /// **'云端操作进行中...'** + String get gitRemoteOperationRunning; + + /// No description provided for @gitRemoteOperationCancelled. + /// + /// In zh, this message translates to: + /// **'操作已取消'** + String get gitRemoteOperationCancelled; + + /// No description provided for @gitRemoteOperationBusy. + /// + /// In zh, this message translates to: + /// **'已有云端操作正在进行,请稍候'** + String get gitRemoteOperationBusy; + + /// No description provided for @gitFetchSuccess. + /// + /// In zh, this message translates to: + /// **'抓取完成'** + String get gitFetchSuccess; + + /// No description provided for @gitFetchNoChanges. + /// + /// In zh, this message translates to: + /// **'已是最新状态'** + String get gitFetchNoChanges; + + /// No description provided for @gitPullSuccess. + /// + /// In zh, this message translates to: + /// **'拉取完成'** + String get gitPullSuccess; + + /// No description provided for @gitPullAlreadyUpToDate. + /// + /// In zh, this message translates to: + /// **'已是最新,无需拉取'** + String get gitPullAlreadyUpToDate; + + /// No description provided for @gitPushSuccess. + /// + /// In zh, this message translates to: + /// **'推送完成'** + String get gitPushSuccess; + + /// No description provided for @gitPushUpToDate. + /// + /// In zh, this message translates to: + /// **'远端已是最新,无需推送'** + String get gitPushUpToDate; + + /// No description provided for @gitNoRemoteConfigured. + /// + /// In zh, this message translates to: + /// **'尚未配置远程仓库'** + String get gitNoRemoteConfigured; + + /// No description provided for @gitNoRemoteDesc. + /// + /// In zh, this message translates to: + /// **'添加远程仓库地址后,即可抓取、拉取与推送代码。'** + String get gitNoRemoteDesc; + + /// No description provided for @gitAddRemote. + /// + /// In zh, this message translates to: + /// **'添加远程仓库'** + String get gitAddRemote; + + /// No description provided for @gitRemoteManagement. + /// + /// In zh, this message translates to: + /// **'远程仓库管理'** + String get gitRemoteManagement; + + /// No description provided for @gitRemoteName. + /// + /// In zh, this message translates to: + /// **'远程名称'** + String get gitRemoteName; + + /// No description provided for @gitRemoteNameHint. + /// + /// In zh, this message translates to: + /// **'例如 origin'** + String get gitRemoteNameHint; + + /// No description provided for @gitRemoteUrl. + /// + /// In zh, this message translates to: + /// **'远程地址'** + String get gitRemoteUrl; + + /// No description provided for @gitRemoteUrlHint. + /// + /// In zh, this message translates to: + /// **'https://github.com/user/repo.git 或 git@github.com:user/repo.git'** + String get gitRemoteUrlHint; + + /// No description provided for @gitRemotePushUrl. + /// + /// In zh, this message translates to: + /// **'推送地址(可选)'** + String get gitRemotePushUrl; + + /// No description provided for @gitRemotePushUrlHint. + /// + /// In zh, this message translates to: + /// **'留空则与抓取地址相同'** + String get gitRemotePushUrlHint; + + /// No description provided for @gitRemoteNameRequired. + /// + /// In zh, this message translates to: + /// **'请输入远程名称'** + String get gitRemoteNameRequired; + + /// No description provided for @gitRemoteUrlRequired. + /// + /// In zh, this message translates to: + /// **'请输入远程地址'** + String get gitRemoteUrlRequired; + + /// No description provided for @gitRemoteAdded. + /// + /// In zh, this message translates to: + /// **'已添加远程仓库 {name}'** + String gitRemoteAdded(String name); + + /// No description provided for @gitRemoteRemoved. + /// + /// In zh, this message translates to: + /// **'已移除远程仓库 {name}'** + String gitRemoteRemoved(String name); + + /// No description provided for @gitRemoteRenamed. + /// + /// In zh, this message translates to: + /// **'已将 {old} 重命名为 {newName}'** + String gitRemoteRenamed(String old, String newName); + + /// No description provided for @gitRemoteUrlUpdated. + /// + /// In zh, this message translates to: + /// **'已更新远程地址'** + String get gitRemoteUrlUpdated; + + /// No description provided for @gitRemotePruned. + /// + /// In zh, this message translates to: + /// **'已清理远端已删除的分支'** + String get gitRemotePruned; + + /// No description provided for @gitRemoteRemoveConfirm. + /// + /// In zh, this message translates to: + /// **'确定要移除远程仓库 {name} 吗?本地代码不会被删除。'** + String gitRemoteRemoveConfirm(String name); + + /// No description provided for @gitRemoteEdit. + /// + /// In zh, this message translates to: + /// **'编辑远程仓库'** + String get gitRemoteEdit; + + /// No description provided for @gitRemoteFetchUrl. + /// + /// In zh, this message translates to: + /// **'抓取地址'** + String get gitRemoteFetchUrl; + + /// No description provided for @gitRemoteSetPushUrl. + /// + /// In zh, this message translates to: + /// **'设置推送地址'** + String get gitRemoteSetPushUrl; + + /// No description provided for @gitRemotePrune. + /// + /// In zh, this message translates to: + /// **'清理失效分支'** + String get gitRemotePrune; + + /// No description provided for @gitCheckConnection. + /// + /// In zh, this message translates to: + /// **'检测连接'** + String get gitCheckConnection; + + /// No description provided for @gitCheckConnectionSuccess. + /// + /// In zh, this message translates to: + /// **'连接正常,认证可用'** + String get gitCheckConnectionSuccess; + + /// No description provided for @gitNoRemotes. + /// + /// In zh, this message translates to: + /// **'暂无远程仓库'** + String get gitNoRemotes; + + /// No description provided for @gitFetchFailed. + /// + /// In zh, this message translates to: + /// **'抓取失败'** + String get gitFetchFailed; + + /// No description provided for @gitPullFailed. + /// + /// In zh, this message translates to: + /// **'拉取失败'** + String get gitPullFailed; + + /// No description provided for @gitPushFailed. + /// + /// In zh, this message translates to: + /// **'推送失败'** + String get gitPushFailed; + + /// No description provided for @gitForcePush. + /// + /// In zh, this message translates to: + /// **'强制推送'** + String get gitForcePush; + + /// No description provided for @gitForcePushTooltip. + /// + /// In zh, this message translates to: + /// **'覆盖远端分支(使用 --force-with-lease 安全校验)'** + String get gitForcePushTooltip; + + /// No description provided for @gitForcePushWarning. + /// + /// In zh, this message translates to: + /// **'强制推送会用本地提交覆盖远端分支,可能导致他人提交丢失。'** + String get gitForcePushWarning; + + /// No description provided for @gitForcePushConfirm. + /// + /// In zh, this message translates to: + /// **'确认强制推送'** + String get gitForcePushConfirm; + + /// No description provided for @gitForcePushConfirmDesc. + /// + /// In zh, this message translates to: + /// **'该操作将改写远端 {branch} 分支的历史。仅在确认远端没有他人新提交时使用。'** + String gitForcePushConfirmDesc(String branch); + + /// No description provided for @gitForcePushUseLease. + /// + /// In zh, this message translates to: + /// **'使用安全强推(--force-with-lease)'** + String get gitForcePushUseLease; + + /// No description provided for @gitPullThenPush. + /// + /// In zh, this message translates to: + /// **'先拉取再推送'** + String get gitPullThenPush; + + /// No description provided for @gitPullThenPushDesc. + /// + /// In zh, this message translates to: + /// **'远端存在本地没有的提交,先拉取合并后再推送。'** + String get gitPullThenPushDesc; + + /// No description provided for @gitConflictAbort. + /// + /// In zh, this message translates to: + /// **'放弃本次变基'** + String get gitConflictAbort; + + /// No description provided for @gitConflictAbortConfirm. + /// + /// In zh, this message translates to: + /// **'确定要放弃本次变基操作并回到操作前的状态吗?'** + String get gitConflictAbortConfirm; + + /// No description provided for @gitUncommittedChangesTitle. + /// + /// In zh, this message translates to: + /// **'存在未提交的改动'** + String get gitUncommittedChangesTitle; + + /// No description provided for @gitUncommittedChangesDesc. + /// + /// In zh, this message translates to: + /// **'拉取前需要先处理本地未提交的改动,否则可能被覆盖。'** + String get gitUncommittedChangesDesc; + + /// No description provided for @gitUncommittedStashAndPull. + /// + /// In zh, this message translates to: + /// **'贮藏并拉取'** + String get gitUncommittedStashAndPull; + + /// No description provided for @gitUncommittedCommitFirst. + /// + /// In zh, this message translates to: + /// **'先去提交'** + String get gitUncommittedCommitFirst; + + /// No description provided for @gitUncommittedCancel. + /// + /// In zh, this message translates to: + /// **'取消'** + String get gitUncommittedCancel; + + /// No description provided for @gitStashAndPullSuccess. + /// + /// In zh, this message translates to: + /// **'已贮藏本地改动并完成拉取'** + String get gitStashAndPullSuccess; + + /// No description provided for @gitViewOperationLog. + /// + /// In zh, this message translates to: + /// **'查看详情'** + String get gitViewOperationLog; + + /// No description provided for @gitHideOperationLog. + /// + /// In zh, this message translates to: + /// **'收起详情'** + String get gitHideOperationLog; + + /// No description provided for @gitAheadBehind. + /// + /// In zh, this message translates to: + /// **'领先 {ahead} / 落后 {behind}'** + String gitAheadBehind(int ahead, int behind); + + /// No description provided for @gitUpstreamGone. + /// + /// In zh, this message translates to: + /// **'上游分支已不存在'** + String get gitUpstreamGone; + + /// No description provided for @gitBehindTooltip. + /// + /// In zh, this message translates to: + /// **'本地落后远端 {behind} 个提交'** + String gitBehindTooltip(int behind); + + /// No description provided for @gitAheadTooltip. + /// + /// In zh, this message translates to: + /// **'本地领先远端 {ahead} 个提交'** + String gitAheadTooltip(int ahead); + /// No description provided for @gitDiff. /// /// In zh, this message translates to: diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 7475b84..b6d5fec 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -2250,6 +2250,605 @@ class AppLocalizationsEn extends AppLocalizations { @override String get gitNoBranches => 'No branches'; + @override + String get gitRemoteBranches => 'Remote Branches'; + + @override + String get gitLocalBranches => 'Local Branches'; + + @override + String get gitNoRemoteBranches => 'No remote branches yet — fetch first'; + + @override + String get gitCheckoutRemoteBranch => 'Check out as local branch'; + + @override + String get gitRemoteBranchCheckedOut => 'Already checked out locally'; + + @override + String gitCheckoutRemoteBranchSuccess(String remote, String branch) { + return 'Created and switched to local branch $branch from $remote'; + } + + @override + String get gitSearchRemoteBranches => 'Search remote branches...'; + + @override + String get gitRepairCheck => 'Repository Check'; + + @override + String get gitRepairCheckRunning => 'Checking...'; + + @override + String get gitRepairCheckHealthy => + 'Repository is intact, no missing objects'; + + @override + String get gitRepairCheckHealthyHint => + 'Object database verified. Committing and syncing should work normally.'; + + @override + String gitRepairCheckObjectLoss(int count) { + return 'Missing objects detected ($count problems)'; + } + + @override + String get gitRepairCheckObjectLossHint => + 'This kind of damage causes \"Error building trees\" on commit. It usually happens when the container is rebuilt and .git/objects is lost. Back up the project directory first, then follow the advice below.'; + + @override + String gitRepairCheckDangling(int count) { + return '$count dangling objects (normal, no action needed)'; + } + + @override + String get gitRepairCheckFailed => 'The check could not complete'; + + @override + String get gitRepairCheckFailedHint => + 'The repository may be large or the command timed out. Try again later.'; + + @override + String get gitRepairCheckRerun => 'Run Again'; + + @override + String get gitRepairAdviceTitle => 'How to handle this'; + + @override + String get gitRepairAdviceRemoveStale => + 'Uncommitted broken entries: run git reset to realign the index with the last commit, then stage the files again.'; + + @override + String get gitRepairAdviceRestore => + 'Damaged committed history: re-clone from the remote, or restore from another copy.'; + + @override + String get gitClone => 'Clone Repository'; + + @override + String get gitCloneUrl => 'Repository URL'; + + @override + String get gitCloneUrlHint => 'https://github.com/user/repo.git'; + + @override + String get gitCloneDirName => 'Local directory name'; + + @override + String get gitCloneDirNameHint => 'Leave empty to derive from the URL'; + + @override + String get gitCloneBranch => 'Branch (optional)'; + + @override + String get gitCloneBranchHint => + 'Leave empty to use the remote default branch'; + + @override + String get gitCloneDepth => 'Shallow clone depth (optional)'; + + @override + String get gitCloneDepthHint => 'e.g. 1 clones only the latest commit'; + + @override + String get gitCloneUrlRequired => 'Please enter a repository URL'; + + @override + String get gitCloneDirRequired => 'Please enter a local directory name'; + + @override + String get gitCloneDirExists => + 'Directory already exists, choose another name'; + + @override + String get gitCloneRunning => 'Cloning...'; + + @override + String gitCloneSuccess(String name) { + return 'Clone complete: $name'; + } + + @override + String get gitCloneFailed => 'Clone failed'; + + @override + String get gitCloneCancel => 'Cancel clone'; + + @override + String gitPushTargetTooltip(String name, String reason) { + return 'Push target: $name\n$reason'; + } + + @override + String get gitPushReasonPushRemote => + 'Set by branch config branch.*.pushRemote'; + + @override + String get gitPushReasonPushDefault => + 'Set by repo config remote.pushDefault'; + + @override + String get gitPushReasonUpstream => 'The upstream remote of this branch'; + + @override + String get gitPushReasonBranchRemote => + 'Set by branch config branch.*.remote'; + + @override + String get gitPushReasonFallback => 'Default remote (origin preferred)'; + + @override + String get gitPushReasonOverridden => + 'You switched it manually in this session'; + + @override + String gitFetchTargetTooltip(String name) { + return 'Fetch target: $name'; + } + + @override + String get gitTogglePushTarget => 'Choose push target'; + + @override + String get gitSyncCloudTooltip => 'Sync: fetch / pull / push'; + + @override + String gitPushTargetChanged(String name) { + return 'Push target switched to $name'; + } + + @override + String get gitPushTargetDiffers => 'Push target differs from upstream'; + + @override + String gitPushTargetDiffersNotice(String upstream, String push) { + return 'Pull from $upstream, push to $push'; + } + + @override + String get gitRemoteRoleUpstream => 'Upstream (fetch)'; + + @override + String get gitErrAuthFailed => + 'Authentication failed: invalid or expired token, or username mismatch'; + + @override + String get gitErrAuthFailedHint => + 'Check the token in Git Accounts, and make sure the username matches your login name on that platform.'; + + @override + String get gitErrWritePermissionDenied => + 'This account has no write access to this repository'; + + @override + String get gitErrWritePermissionDeniedHint => + 'If this is someone else\'s repository (upstream), fork it to your own account first, then point the remote at your fork (e.g. https://github.com/your-name/repo.git).'; + + @override + String get gitErrRepositoryNotFound => + 'Repository not found, or this account has no access to it'; + + @override + String get gitErrRepositoryNotFoundHint => + 'GitHub returns 404 for both \"no permission\" and \"does not exist\". Verify the remote URL and that the token can access this repository.'; + + @override + String get gitErrProxyAuthRequired => + 'The network proxy requires authentication'; + + @override + String get gitErrProxyAuthRequiredHint => + 'This network goes through an authenticated proxy (HTTP 407). Check the proxy configuration and credentials inside the container.'; + + @override + String get gitErrRequestRejected => 'The server rejected this request'; + + @override + String get gitErrRequestRejectedHint => + 'Usually means the pushed content or branch reference is invalid (HTTP 422), e.g. a branch name that violates platform rules or a blocked commit.'; + + @override + String get gitErrRateLimited => + 'Too many requests, rate limited by the platform'; + + @override + String get gitErrRateLimitedHint => + 'Wait a few minutes and retry (HTTP 429). Retrying repeatedly will extend the limit.'; + + @override + String get gitErrHttpError => 'The server returned an error status code'; + + @override + String get gitErrHttpErrorHint => + 'Check the status code below: 401 invalid token, 403 no permission, 404 not found or no access, 407 proxy auth required, 429 rate limited.'; + + @override + String get gitErrPasswordAuthDisabled => + 'This platform has disabled password authentication'; + + @override + String get gitErrPasswordAuthDisabledHint => + 'Add the account again using a personal access token (PAT) in Git Accounts.'; + + @override + String get gitErrNetworkUnreachable => + 'Cannot reach the remote server over the network'; + + @override + String get gitErrNetworkUnreachableHint => + 'Check your network connection and the container DNS configuration (/etc/resolv.conf).'; + + @override + String get gitErrSshPublicKeyDenied => + 'SSH public key authentication was rejected'; + + @override + String get gitErrSshPublicKeyDeniedHint => + 'Make sure the container\'s public key is added to the platform\'s SSH keys, or switch to HTTPS with an access token.'; + + @override + String get gitErrSshKeyUnusable => + 'The SSH private key is unusable (bad permissions or format)'; + + @override + String get gitErrSshKeyUnusableHint => + 'The private key must have mode 600. You can regenerate the key pair in Git Accounts.'; + + @override + String get gitErrHostKeyUnverified => + 'The server host fingerprint is not confirmed yet, connection aborted'; + + @override + String get gitErrHostKeyUnverifiedHint => + 'The first connection requires confirming the host fingerprint. If the server key changed, clear ~/.ssh/known_hosts in the container and retry.'; + + @override + String get gitErrNonFastForward => + 'Push rejected: the remote has commits you do not have locally'; + + @override + String get gitErrNonFastForwardHint => + 'Pull first (rebase mode) to merge the remote changes, then push again.'; + + @override + String get gitErrStaleForcePush => + 'Force push rejected: someone else updated the remote branch'; + + @override + String get gitErrStaleForcePushHint => + 'Fetch the latest remote state first, review the differences, then force push again.'; + + @override + String get gitErrConflictDetected => + 'Merge/rebase conflicts must be resolved manually'; + + @override + String get gitErrConflictDetectedHint => + 'Resolve the conflicting files one by one, or abort this operation (git rebase --abort).'; + + @override + String get gitErrLocalChanges => + 'Local uncommitted changes would be overwritten, operation aborted'; + + @override + String get gitErrLocalChangesHint => + 'Commit your changes first, or stash them, then retry.'; + + @override + String get gitErrNoUpstream => + 'This branch is not tracking a remote branch yet'; + + @override + String get gitErrNoUpstreamHint => + 'Use Publish Branch to push it to the remote and set up tracking.'; + + @override + String get gitErrRefLockFailed => + 'A Git reference file is locked (stale lock)'; + + @override + String get gitErrRefLockFailedHint => + 'Another Git process may be running. Retry shortly, or remove the .lock files under .git.'; + + @override + String get gitErrOutOfSpace => 'Not enough storage space on the device'; + + @override + String get gitErrOutOfSpaceHint => + 'Free up space in the container or on the device, then retry.'; + + @override + String get gitErrTimeout => 'Operation timed out'; + + @override + String get gitErrTimeoutHint => + 'Large repositories or slow networks can time out. Watch the progress in the terminal instead, or retry on a better connection.'; + + @override + String get gitErrIncomplete => + 'The operation did not finish, and no specific error was returned'; + + @override + String get gitErrIncompleteHint => + 'It was most likely interrupted by a timeout or a dropped connection. For large repositories, run fetch in the terminal to watch progress, or retry on a better connection.'; + + @override + String get gitErrUnknown => 'Git operation failed'; + + @override + String get gitErrUnknownHint => 'Expand the raw output below for details.'; + + @override + String get gitRawOutput => 'Raw output'; + + @override + String gitElapsed(String time) { + return 'Elapsed $time'; + } + + @override + String gitElapsedMinutesSeconds(int minutes, String seconds) { + return '$minutes:$seconds'; + } + + @override + String get gitFetch => 'Fetch'; + + @override + String get gitFetchTooltip => + 'Fetch the latest commits from the remote without merging'; + + @override + String get gitPull => 'Pull'; + + @override + String get gitPullTooltip => + 'Pull remote commits and rebase the current branch onto them'; + + @override + String get gitPush => 'Push'; + + @override + String get gitPushTooltip => 'Push local commits to the remote'; + + @override + String get gitPublishBranch => 'Publish Branch'; + + @override + String get gitPublishBranchTooltip => + 'Push this local branch to the remote and set up tracking'; + + @override + String get gitSync => 'Sync'; + + @override + String get gitSyncTooltip => 'Pull remote changes, then push local commits'; + + @override + String get gitCancelOperation => 'Cancel'; + + @override + String get gitRemoteOperationRunning => 'Remote operation in progress...'; + + @override + String get gitRemoteOperationCancelled => 'Operation cancelled'; + + @override + String get gitRemoteOperationBusy => + 'Another remote operation is already running'; + + @override + String get gitFetchSuccess => 'Fetch completed'; + + @override + String get gitFetchNoChanges => 'Already up to date'; + + @override + String get gitPullSuccess => 'Pull completed'; + + @override + String get gitPullAlreadyUpToDate => 'Already up to date, nothing to pull'; + + @override + String get gitPushSuccess => 'Push completed'; + + @override + String get gitPushUpToDate => 'Remote is already up to date, nothing to push'; + + @override + String get gitNoRemoteConfigured => 'No Remote Configured'; + + @override + String get gitNoRemoteDesc => + 'Add a remote repository URL to fetch, pull, and push your code.'; + + @override + String get gitAddRemote => 'Add Remote'; + + @override + String get gitRemoteManagement => 'Remote Repositories'; + + @override + String get gitRemoteName => 'Remote Name'; + + @override + String get gitRemoteNameHint => 'e.g. origin'; + + @override + String get gitRemoteUrl => 'Remote URL'; + + @override + String get gitRemoteUrlHint => + 'https://github.com/user/repo.git or git@github.com:user/repo.git'; + + @override + String get gitRemotePushUrl => 'Push URL (optional)'; + + @override + String get gitRemotePushUrlHint => 'Leave empty to use the fetch URL'; + + @override + String get gitRemoteNameRequired => 'Please enter a remote name'; + + @override + String get gitRemoteUrlRequired => 'Please enter a remote URL'; + + @override + String gitRemoteAdded(String name) { + return 'Added remote $name'; + } + + @override + String gitRemoteRemoved(String name) { + return 'Removed remote $name'; + } + + @override + String gitRemoteRenamed(String old, String newName) { + return 'Renamed $old to $newName'; + } + + @override + String get gitRemoteUrlUpdated => 'Remote URL updated'; + + @override + String get gitRemotePruned => 'Pruned stale remote branches'; + + @override + String gitRemoteRemoveConfirm(String name) { + return 'Remove remote $name? Your local code will not be deleted.'; + } + + @override + String get gitRemoteEdit => 'Edit Remote'; + + @override + String get gitRemoteFetchUrl => 'Fetch URL'; + + @override + String get gitRemoteSetPushUrl => 'Set Push URL'; + + @override + String get gitRemotePrune => 'Prune Stale Branches'; + + @override + String get gitCheckConnection => 'Test Connection'; + + @override + String get gitCheckConnectionSuccess => 'Connection OK, authentication works'; + + @override + String get gitNoRemotes => 'No remotes'; + + @override + String get gitFetchFailed => 'Fetch failed'; + + @override + String get gitPullFailed => 'Pull failed'; + + @override + String get gitPushFailed => 'Push failed'; + + @override + String get gitForcePush => 'Force Push'; + + @override + String get gitForcePushTooltip => + 'Overwrite the remote branch (uses --force-with-lease for safety)'; + + @override + String get gitForcePushWarning => + 'Force pushing overwrites the remote branch with your local commits and may discard other people\'s work.'; + + @override + String get gitForcePushConfirm => 'Confirm Force Push'; + + @override + String gitForcePushConfirmDesc(String branch) { + return 'This rewrites the history of remote branch $branch. Only use it when you are certain nobody else pushed new commits.'; + } + + @override + String get gitForcePushUseLease => 'Use safe force push (--force-with-lease)'; + + @override + String get gitPullThenPush => 'Pull Then Push'; + + @override + String get gitPullThenPushDesc => + 'The remote has commits you do not have. Pull and merge them before pushing.'; + + @override + String get gitConflictAbort => 'Abort Rebase'; + + @override + String get gitConflictAbortConfirm => + 'Abort this rebase and return to the state before it started?'; + + @override + String get gitUncommittedChangesTitle => 'Uncommitted Changes'; + + @override + String get gitUncommittedChangesDesc => + 'Local uncommitted changes must be handled before pulling, or they may be overwritten.'; + + @override + String get gitUncommittedStashAndPull => 'Stash and Pull'; + + @override + String get gitUncommittedCommitFirst => 'Commit First'; + + @override + String get gitUncommittedCancel => 'Cancel'; + + @override + String get gitStashAndPullSuccess => + 'Stashed local changes and pulled successfully'; + + @override + String get gitViewOperationLog => 'View Details'; + + @override + String get gitHideOperationLog => 'Hide Details'; + + @override + String gitAheadBehind(int ahead, int behind) { + return '$ahead ahead / $behind behind'; + } + + @override + String get gitUpstreamGone => 'Upstream branch no longer exists'; + + @override + String gitBehindTooltip(int behind) { + return '$behind commits behind the remote'; + } + + @override + String gitAheadTooltip(int ahead) { + return '$ahead commits ahead of the remote'; + } + @override String get gitDiff => 'Diff'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index a79a7ed..7c62ed1 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -2187,6 +2187,558 @@ class AppLocalizationsZh extends AppLocalizations { @override String get gitNoBranches => '暂无分支'; + @override + String get gitRemoteBranches => '远端分支'; + + @override + String get gitLocalBranches => '本地分支'; + + @override + String get gitNoRemoteBranches => '暂无远端分支,请先执行抓取'; + + @override + String get gitCheckoutRemoteBranch => '检出为本地分支'; + + @override + String get gitRemoteBranchCheckedOut => '该远端分支已在本地检出'; + + @override + String gitCheckoutRemoteBranchSuccess(String remote, String branch) { + return '已基于 $remote 创建并切换到本地分支 $branch'; + } + + @override + String get gitSearchRemoteBranches => '搜索远端分支...'; + + @override + String get gitRepairCheck => '仓库自检'; + + @override + String get gitRepairCheckRunning => '正在自检...'; + + @override + String get gitRepairCheckHealthy => '仓库完整,未发现对象丢失'; + + @override + String get gitRepairCheckHealthyHint => '对象库校验通过,可以正常提交与同步。'; + + @override + String gitRepairCheckObjectLoss(int count) { + return '检测到对象丢失($count 处问题)'; + } + + @override + String get gitRepairCheckObjectLossHint => + '这类损坏会导致提交时报错 Error building trees。常见原因是容器被重建导致 .git/objects 丢失。建议先备份项目目录,再按下方提示处理。'; + + @override + String gitRepairCheckDangling(int count) { + return '另有 $count 个悬空对象(正常现象,无需处理)'; + } + + @override + String get gitRepairCheckFailed => '自检未能完成'; + + @override + String get gitRepairCheckFailedHint => '可能因为仓库过大或执行超时,可稍后重试。'; + + @override + String get gitRepairCheckRerun => '重新自检'; + + @override + String get gitRepairAdviceTitle => '如何处理'; + + @override + String get gitRepairAdviceRemoveStale => + '未提交的损坏条目:执行 git reset 让索引与最后一次提交对齐,然后重新暂存需要的文件。'; + + @override + String get gitRepairAdviceRestore => '已提交的历史损坏:需要从远端重新克隆,或从其他副本恢复。'; + + @override + String get gitClone => '克隆远程仓库'; + + @override + String get gitCloneUrl => '仓库地址'; + + @override + String get gitCloneUrlHint => 'https://github.com/user/repo.git'; + + @override + String get gitCloneDirName => '本地目录名'; + + @override + String get gitCloneDirNameHint => '留空则从地址自动推导'; + + @override + String get gitCloneBranch => '指定分支(可选)'; + + @override + String get gitCloneBranchHint => '留空则使用远端默认分支'; + + @override + String get gitCloneDepth => '浅克隆深度(可选)'; + + @override + String get gitCloneDepthHint => '如 1 表示只克隆最近 1 个提交'; + + @override + String get gitCloneUrlRequired => '请输入仓库地址'; + + @override + String get gitCloneDirRequired => '请输入本地目录名'; + + @override + String get gitCloneDirExists => '目录已存在,请换一个名字'; + + @override + String get gitCloneRunning => '正在克隆...'; + + @override + String gitCloneSuccess(String name) { + return '克隆完成:$name'; + } + + @override + String get gitCloneFailed => '克隆失败'; + + @override + String get gitCloneCancel => '取消克隆'; + + @override + String gitPushTargetTooltip(String name, String reason) { + return '推送目标:$name\n$reason'; + } + + @override + String get gitPushReasonPushRemote => '由分支配置 branch.*.pushRemote 决定'; + + @override + String get gitPushReasonPushDefault => '由仓库配置 remote.pushDefault 决定'; + + @override + String get gitPushReasonUpstream => '当前分支的上游远程'; + + @override + String get gitPushReasonBranchRemote => '由分支配置 branch.*.remote 决定'; + + @override + String get gitPushReasonFallback => '默认远程(origin 优先)'; + + @override + String get gitPushReasonOverridden => '你已在本次会话中手动切换'; + + @override + String gitFetchTargetTooltip(String name) { + return '抓取目标:$name'; + } + + @override + String get gitTogglePushTarget => '选择推送目标'; + + @override + String get gitSyncCloudTooltip => '同步:抓取 / 拉取 / 推送'; + + @override + String gitPushTargetChanged(String name) { + return '推送目标已切换为 $name'; + } + + @override + String get gitPushTargetDiffers => '推送目标与上游不同'; + + @override + String gitPushTargetDiffersNotice(String upstream, String push) { + return '拉取走 $upstream,推送走 $push'; + } + + @override + String get gitRemoteRoleUpstream => '上游(拉取)'; + + @override + String get gitErrAuthFailed => '认证失败:令牌无效、已过期或用户名不匹配'; + + @override + String get gitErrAuthFailedHint => '请到「Git 账号管理」检查令牌是否有效,并确认账号用户名与平台登录名一致。'; + + @override + String get gitErrWritePermissionDenied => '当前账号对该仓库没有写权限'; + + @override + String get gitErrWritePermissionDeniedHint => + '若这是别人的仓库(上游),请先 Fork 到你自己的账号,再把远端地址改为你的 Fork(如 https://github.com/你的用户名/仓库.git)。'; + + @override + String get gitErrRepositoryNotFound => '仓库不存在,或当前账号无权访问'; + + @override + String get gitErrRepositoryNotFoundHint => + 'GitHub 对「无权限」和「不存在」都返回 404。请确认远端地址拼写正确,且该令牌有权访问该仓库。'; + + @override + String get gitErrProxyAuthRequired => '网络代理需要认证'; + + @override + String get gitErrProxyAuthRequiredHint => + '当前网络经过需要认证的代理(HTTP 407)。请检查容器内代理配置与凭据。'; + + @override + String get gitErrRequestRejected => '服务器拒绝了本次请求'; + + @override + String get gitErrRequestRejectedHint => + '通常表示推送内容或分支引用不合法(HTTP 422),例如分支名不符合平台规则或提交信息被策略拦截。'; + + @override + String get gitErrRateLimited => '请求过于频繁,已被平台限流'; + + @override + String get gitErrRateLimitedHint => '请稍等几分钟后重试(HTTP 429)。短时间内反复重试会延长限制时间。'; + + @override + String get gitErrHttpError => '服务器返回了错误状态码'; + + @override + String get gitErrHttpErrorHint => + '请根据下方状态码排查:401 令牌无效、403 无权限、404 仓库不存在或无权访问、407 需要代理认证、429 被限流。'; + + @override + String get gitErrPasswordAuthDisabled => '该平台已禁用账号密码认证'; + + @override + String get gitErrPasswordAuthDisabledHint => + '请在「Git 账号管理」中使用个人访问令牌 (PAT) 重新添加账号。'; + + @override + String get gitErrNetworkUnreachable => '网络无法连接到远端服务器'; + + @override + String get gitErrNetworkUnreachableHint => + '请检查网络连接,以及容器内 DNS 配置(/etc/resolv.conf)是否正常。'; + + @override + String get gitErrSshPublicKeyDenied => 'SSH 公钥认证被拒绝'; + + @override + String get gitErrSshPublicKeyDeniedHint => + '请确认容器内的公钥已添加到平台的 SSH Keys 中,或改用 HTTPS + 访问令牌。'; + + @override + String get gitErrSshKeyUnusable => 'SSH 私钥无法使用(权限或格式异常)'; + + @override + String get gitErrSshKeyUnusableHint => '私钥权限需为 600。可在「Git 账号管理」中重新生成密钥对。'; + + @override + String get gitErrHostKeyUnverified => '目标服务器的主机指纹尚未确认,连接被中断'; + + @override + String get gitErrHostKeyUnverifiedHint => + '首次连接需要确认主机指纹。若刚更换过服务器密钥,请清理容器内 ~/.ssh/known_hosts 后重试。'; + + @override + String get gitErrNonFastForward => '推送被拒绝:远端存在本地尚无的提交'; + + @override + String get gitErrNonFastForwardHint => '请先执行 Pull(rebase 方式)合并远端改动,再重新推送。'; + + @override + String get gitErrStaleForcePush => '强推被拒绝:远端分支已被他人更新'; + + @override + String get gitErrStaleForcePushHint => '请先执行 Fetch 获取最新远端状态,确认差异后再强制推送。'; + + @override + String get gitErrConflictDetected => '合并/rebase 出现冲突,需要手动解决'; + + @override + String get gitErrConflictDetectedHint => + '请逐个解决冲突文件,或放弃本次操作(git rebase --abort)。'; + + @override + String get gitErrLocalChanges => '本地未提交的改动会被覆盖,操作已中止'; + + @override + String get gitErrLocalChangesHint => '请先提交改动,或将其贮藏(stash)后再执行。'; + + @override + String get gitErrNoUpstream => '当前分支尚未关联远端分支'; + + @override + String get gitErrNoUpstreamHint => '请使用「发布分支」将本地分支推送到远端并建立追踪关系。'; + + @override + String get gitErrRefLockFailed => 'Git 引用文件被占用(存在残留锁)'; + + @override + String get gitErrRefLockFailedHint => + '可能有另一个 Git 进程正在运行。稍后重试,或清理 .git 目录下的 .lock 文件。'; + + @override + String get gitErrOutOfSpace => '设备存储空间不足'; + + @override + String get gitErrOutOfSpaceHint => '请清理容器或设备空间后重试。'; + + @override + String get gitErrTimeout => '操作超时'; + + @override + String get gitErrTimeoutHint => '仓库较大或网络较慢时可能超时。可改用终端观察进度,或在网络较好时重试。'; + + @override + String get gitErrIncomplete => '操作未完成,但没有返回具体错误信息'; + + @override + String get gitErrIncompleteHint => + '通常是被超时或网络中断打断。仓库较大时建议改用终端执行 fetch 观察进度,或稍后在网络较好时重试。'; + + @override + String get gitErrUnknown => 'Git 操作失败'; + + @override + String get gitErrUnknownHint => '请展开下方原始输出查看详细信息。'; + + @override + String get gitRawOutput => '原始输出'; + + @override + String gitElapsed(String time) { + return '已用 $time'; + } + + @override + String gitElapsedMinutesSeconds(int minutes, String seconds) { + return '$minutes:$seconds'; + } + + @override + String get gitFetch => '抓取'; + + @override + String get gitFetchTooltip => '从远端抓取最新提交(不合并到本地)'; + + @override + String get gitPull => '拉取'; + + @override + String get gitPullTooltip => '拉取远端提交并以 rebase 方式合并到当前分支'; + + @override + String get gitPush => '推送'; + + @override + String get gitPushTooltip => '将本地提交推送到远端'; + + @override + String get gitPublishBranch => '发布分支'; + + @override + String get gitPublishBranchTooltip => '将本地分支推送到远端并建立追踪关系'; + + @override + String get gitSync => '同步'; + + @override + String get gitSyncTooltip => '先拉取远端改动,再推送本地提交'; + + @override + String get gitCancelOperation => '取消'; + + @override + String get gitRemoteOperationRunning => '云端操作进行中...'; + + @override + String get gitRemoteOperationCancelled => '操作已取消'; + + @override + String get gitRemoteOperationBusy => '已有云端操作正在进行,请稍候'; + + @override + String get gitFetchSuccess => '抓取完成'; + + @override + String get gitFetchNoChanges => '已是最新状态'; + + @override + String get gitPullSuccess => '拉取完成'; + + @override + String get gitPullAlreadyUpToDate => '已是最新,无需拉取'; + + @override + String get gitPushSuccess => '推送完成'; + + @override + String get gitPushUpToDate => '远端已是最新,无需推送'; + + @override + String get gitNoRemoteConfigured => '尚未配置远程仓库'; + + @override + String get gitNoRemoteDesc => '添加远程仓库地址后,即可抓取、拉取与推送代码。'; + + @override + String get gitAddRemote => '添加远程仓库'; + + @override + String get gitRemoteManagement => '远程仓库管理'; + + @override + String get gitRemoteName => '远程名称'; + + @override + String get gitRemoteNameHint => '例如 origin'; + + @override + String get gitRemoteUrl => '远程地址'; + + @override + String get gitRemoteUrlHint => + 'https://github.com/user/repo.git 或 git@github.com:user/repo.git'; + + @override + String get gitRemotePushUrl => '推送地址(可选)'; + + @override + String get gitRemotePushUrlHint => '留空则与抓取地址相同'; + + @override + String get gitRemoteNameRequired => '请输入远程名称'; + + @override + String get gitRemoteUrlRequired => '请输入远程地址'; + + @override + String gitRemoteAdded(String name) { + return '已添加远程仓库 $name'; + } + + @override + String gitRemoteRemoved(String name) { + return '已移除远程仓库 $name'; + } + + @override + String gitRemoteRenamed(String old, String newName) { + return '已将 $old 重命名为 $newName'; + } + + @override + String get gitRemoteUrlUpdated => '已更新远程地址'; + + @override + String get gitRemotePruned => '已清理远端已删除的分支'; + + @override + String gitRemoteRemoveConfirm(String name) { + return '确定要移除远程仓库 $name 吗?本地代码不会被删除。'; + } + + @override + String get gitRemoteEdit => '编辑远程仓库'; + + @override + String get gitRemoteFetchUrl => '抓取地址'; + + @override + String get gitRemoteSetPushUrl => '设置推送地址'; + + @override + String get gitRemotePrune => '清理失效分支'; + + @override + String get gitCheckConnection => '检测连接'; + + @override + String get gitCheckConnectionSuccess => '连接正常,认证可用'; + + @override + String get gitNoRemotes => '暂无远程仓库'; + + @override + String get gitFetchFailed => '抓取失败'; + + @override + String get gitPullFailed => '拉取失败'; + + @override + String get gitPushFailed => '推送失败'; + + @override + String get gitForcePush => '强制推送'; + + @override + String get gitForcePushTooltip => '覆盖远端分支(使用 --force-with-lease 安全校验)'; + + @override + String get gitForcePushWarning => '强制推送会用本地提交覆盖远端分支,可能导致他人提交丢失。'; + + @override + String get gitForcePushConfirm => '确认强制推送'; + + @override + String gitForcePushConfirmDesc(String branch) { + return '该操作将改写远端 $branch 分支的历史。仅在确认远端没有他人新提交时使用。'; + } + + @override + String get gitForcePushUseLease => '使用安全强推(--force-with-lease)'; + + @override + String get gitPullThenPush => '先拉取再推送'; + + @override + String get gitPullThenPushDesc => '远端存在本地没有的提交,先拉取合并后再推送。'; + + @override + String get gitConflictAbort => '放弃本次变基'; + + @override + String get gitConflictAbortConfirm => '确定要放弃本次变基操作并回到操作前的状态吗?'; + + @override + String get gitUncommittedChangesTitle => '存在未提交的改动'; + + @override + String get gitUncommittedChangesDesc => '拉取前需要先处理本地未提交的改动,否则可能被覆盖。'; + + @override + String get gitUncommittedStashAndPull => '贮藏并拉取'; + + @override + String get gitUncommittedCommitFirst => '先去提交'; + + @override + String get gitUncommittedCancel => '取消'; + + @override + String get gitStashAndPullSuccess => '已贮藏本地改动并完成拉取'; + + @override + String get gitViewOperationLog => '查看详情'; + + @override + String get gitHideOperationLog => '收起详情'; + + @override + String gitAheadBehind(int ahead, int behind) { + return '领先 $ahead / 落后 $behind'; + } + + @override + String get gitUpstreamGone => '上游分支已不存在'; + + @override + String gitBehindTooltip(int behind) { + return '本地落后远端 $behind 个提交'; + } + + @override + String gitAheadTooltip(int ahead) { + return '本地领先远端 $ahead 个提交'; + } + @override String get gitDiff => '差异对比'; diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 9e752c8..c9b6141 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -1294,6 +1294,325 @@ "gitSearchBranches": "搜索分支...", "gitSearchTags": "搜索标签...", "gitNoBranches": "暂无分支", + + "gitRemoteBranches": "远端分支", + "gitLocalBranches": "本地分支", + "gitNoRemoteBranches": "暂无远端分支,请先执行抓取", + "gitCheckoutRemoteBranch": "检出为本地分支", + "gitRemoteBranchCheckedOut": "该远端分支已在本地检出", + "gitCheckoutRemoteBranchSuccess": "已基于 {remote} 创建并切换到本地分支 {branch}", + "@gitCheckoutRemoteBranchSuccess": { + "placeholders": { + "remote": { + "type": "String" + }, + "branch": { + "type": "String" + } + } + }, + "gitSearchRemoteBranches": "搜索远端分支...", + + "gitRepairCheck": "仓库自检", + "gitRepairCheckRunning": "正在自检...", + "gitRepairCheckHealthy": "仓库完整,未发现对象丢失", + "gitRepairCheckHealthyHint": "对象库校验通过,可以正常提交与同步。", + "gitRepairCheckObjectLoss": "检测到对象丢失({count} 处问题)", + "@gitRepairCheckObjectLoss": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "gitRepairCheckObjectLossHint": "这类损坏会导致提交时报错 Error building trees。常见原因是容器被重建导致 .git/objects 丢失。建议先备份项目目录,再按下方提示处理。", + "gitRepairCheckDangling": "另有 {count} 个悬空对象(正常现象,无需处理)", + "@gitRepairCheckDangling": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "gitRepairCheckFailed": "自检未能完成", + "gitRepairCheckFailedHint": "可能因为仓库过大或执行超时,可稍后重试。", + "gitRepairCheckRerun": "重新自检", + "gitRepairAdviceTitle": "如何处理", + "gitRepairAdviceRemoveStale": "未提交的损坏条目:执行 git reset 让索引与最后一次提交对齐,然后重新暂存需要的文件。", + "gitRepairAdviceRestore": "已提交的历史损坏:需要从远端重新克隆,或从其他副本恢复。", + + "gitClone": "克隆远程仓库", + "gitCloneUrl": "仓库地址", + "gitCloneUrlHint": "https://github.com/user/repo.git", + "gitCloneDirName": "本地目录名", + "gitCloneDirNameHint": "留空则从地址自动推导", + "gitCloneBranch": "指定分支(可选)", + "gitCloneBranchHint": "留空则使用远端默认分支", + "gitCloneDepth": "浅克隆深度(可选)", + "gitCloneDepthHint": "如 1 表示只克隆最近 1 个提交", + "gitCloneUrlRequired": "请输入仓库地址", + "gitCloneDirRequired": "请输入本地目录名", + "gitCloneDirExists": "目录已存在,请换一个名字", + "gitCloneRunning": "正在克隆...", + "gitCloneSuccess": "克隆完成:{name}", + "@gitCloneSuccess": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "gitCloneFailed": "克隆失败", + "gitCloneCancel": "取消克隆", + + "gitPushTargetTooltip": "推送目标:{name}\n{reason}", + "@gitPushTargetTooltip": { + "placeholders": { + "name": { + "type": "String" + }, + "reason": { + "type": "String" + } + } + }, + "gitPushReasonPushRemote": "由分支配置 branch.*.pushRemote 决定", + "gitPushReasonPushDefault": "由仓库配置 remote.pushDefault 决定", + "gitPushReasonUpstream": "当前分支的上游远程", + "gitPushReasonBranchRemote": "由分支配置 branch.*.remote 决定", + "gitPushReasonFallback": "默认远程(origin 优先)", + "gitPushReasonOverridden": "你已在本次会话中手动切换", + "gitFetchTargetTooltip": "抓取目标:{name}", + "@gitFetchTargetTooltip": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "gitTogglePushTarget": "选择推送目标", + "gitSyncCloudTooltip": "同步:抓取 / 拉取 / 推送", + "gitPushTargetChanged": "推送目标已切换为 {name}", + "@gitPushTargetChanged": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "gitPushTargetDiffers": "推送目标与上游不同", + "gitPushTargetDiffersNotice": "拉取走 {upstream},推送走 {push}", + "@gitPushTargetDiffersNotice": { + "placeholders": { + "upstream": { + "type": "String" + }, + "push": { + "type": "String" + } + } + }, + "gitRemoteRoleUpstream": "上游(拉取)", + + "gitErrAuthFailed": "认证失败:令牌无效、已过期或用户名不匹配", + "gitErrAuthFailedHint": "请到「Git 账号管理」检查令牌是否有效,并确认账号用户名与平台登录名一致。", + "gitErrWritePermissionDenied": "当前账号对该仓库没有写权限", + "gitErrWritePermissionDeniedHint": "若这是别人的仓库(上游),请先 Fork 到你自己的账号,再把远端地址改为你的 Fork(如 https://github.com/你的用户名/仓库.git)。", + "gitErrRepositoryNotFound": "仓库不存在,或当前账号无权访问", + "gitErrRepositoryNotFoundHint": "GitHub 对「无权限」和「不存在」都返回 404。请确认远端地址拼写正确,且该令牌有权访问该仓库。", + "gitErrProxyAuthRequired": "网络代理需要认证", + "gitErrProxyAuthRequiredHint": "当前网络经过需要认证的代理(HTTP 407)。请检查容器内代理配置与凭据。", + "gitErrRequestRejected": "服务器拒绝了本次请求", + "gitErrRequestRejectedHint": "通常表示推送内容或分支引用不合法(HTTP 422),例如分支名不符合平台规则或提交信息被策略拦截。", + "gitErrRateLimited": "请求过于频繁,已被平台限流", + "gitErrRateLimitedHint": "请稍等几分钟后重试(HTTP 429)。短时间内反复重试会延长限制时间。", + "gitErrHttpError": "服务器返回了错误状态码", + "gitErrHttpErrorHint": "请根据下方状态码排查:401 令牌无效、403 无权限、404 仓库不存在或无权访问、407 需要代理认证、429 被限流。", + "gitErrPasswordAuthDisabled": "该平台已禁用账号密码认证", + "gitErrPasswordAuthDisabledHint": "请在「Git 账号管理」中使用个人访问令牌 (PAT) 重新添加账号。", + "gitErrNetworkUnreachable": "网络无法连接到远端服务器", + "gitErrNetworkUnreachableHint": "请检查网络连接,以及容器内 DNS 配置(/etc/resolv.conf)是否正常。", + "gitErrSshPublicKeyDenied": "SSH 公钥认证被拒绝", + "gitErrSshPublicKeyDeniedHint": "请确认容器内的公钥已添加到平台的 SSH Keys 中,或改用 HTTPS + 访问令牌。", + "gitErrSshKeyUnusable": "SSH 私钥无法使用(权限或格式异常)", + "gitErrSshKeyUnusableHint": "私钥权限需为 600。可在「Git 账号管理」中重新生成密钥对。", + "gitErrHostKeyUnverified": "目标服务器的主机指纹尚未确认,连接被中断", + "gitErrHostKeyUnverifiedHint": "首次连接需要确认主机指纹。若刚更换过服务器密钥,请清理容器内 ~/.ssh/known_hosts 后重试。", + "gitErrNonFastForward": "推送被拒绝:远端存在本地尚无的提交", + "gitErrNonFastForwardHint": "请先执行 Pull(rebase 方式)合并远端改动,再重新推送。", + "gitErrStaleForcePush": "强推被拒绝:远端分支已被他人更新", + "gitErrStaleForcePushHint": "请先执行 Fetch 获取最新远端状态,确认差异后再强制推送。", + "gitErrConflictDetected": "合并/rebase 出现冲突,需要手动解决", + "gitErrConflictDetectedHint": "请逐个解决冲突文件,或放弃本次操作(git rebase --abort)。", + "gitErrLocalChanges": "本地未提交的改动会被覆盖,操作已中止", + "gitErrLocalChangesHint": "请先提交改动,或将其贮藏(stash)后再执行。", + "gitErrNoUpstream": "当前分支尚未关联远端分支", + "gitErrNoUpstreamHint": "请使用「发布分支」将本地分支推送到远端并建立追踪关系。", + "gitErrRefLockFailed": "Git 引用文件被占用(存在残留锁)", + "gitErrRefLockFailedHint": "可能有另一个 Git 进程正在运行。稍后重试,或清理 .git 目录下的 .lock 文件。", + "gitErrOutOfSpace": "设备存储空间不足", + "gitErrOutOfSpaceHint": "请清理容器或设备空间后重试。", + "gitErrTimeout": "操作超时", + "gitErrTimeoutHint": "仓库较大或网络较慢时可能超时。可改用终端观察进度,或在网络较好时重试。", + "gitErrIncomplete": "操作未完成,但没有返回具体错误信息", + "gitErrIncompleteHint": "通常是被超时或网络中断打断。仓库较大时建议改用终端执行 fetch 观察进度,或稍后在网络较好时重试。", + "gitErrUnknown": "Git 操作失败", + "gitErrUnknownHint": "请展开下方原始输出查看详细信息。", + "gitRawOutput": "原始输出", + + "gitElapsed": "已用 {time}", + "@gitElapsed": { + "placeholders": { + "time": { + "type": "String" + } + } + }, + "gitElapsedMinutesSeconds": "{minutes}:{seconds}", + "@gitElapsedMinutesSeconds": { + "placeholders": { + "minutes": { + "type": "int" + }, + "seconds": { + "type": "String" + } + } + }, + + "gitFetch": "抓取", + "gitFetchTooltip": "从远端抓取最新提交(不合并到本地)", + "gitPull": "拉取", + "gitPullTooltip": "拉取远端提交并以 rebase 方式合并到当前分支", + "gitPush": "推送", + "gitPushTooltip": "将本地提交推送到远端", + "gitPublishBranch": "发布分支", + "gitPublishBranchTooltip": "将本地分支推送到远端并建立追踪关系", + "gitSync": "同步", + "gitSyncTooltip": "先拉取远端改动,再推送本地提交", + "gitCancelOperation": "取消", + "gitRemoteOperationRunning": "云端操作进行中...", + "gitRemoteOperationCancelled": "操作已取消", + "gitRemoteOperationBusy": "已有云端操作正在进行,请稍候", + "gitFetchSuccess": "抓取完成", + "gitFetchNoChanges": "已是最新状态", + "gitPullSuccess": "拉取完成", + "gitPullAlreadyUpToDate": "已是最新,无需拉取", + "gitPushSuccess": "推送完成", + "gitPushUpToDate": "远端已是最新,无需推送", + "gitNoRemoteConfigured": "尚未配置远程仓库", + "gitNoRemoteDesc": "添加远程仓库地址后,即可抓取、拉取与推送代码。", + "gitAddRemote": "添加远程仓库", + "gitRemoteManagement": "远程仓库管理", + "gitRemoteName": "远程名称", + "gitRemoteNameHint": "例如 origin", + "gitRemoteUrl": "远程地址", + "gitRemoteUrlHint": "https://github.com/user/repo.git 或 git@github.com:user/repo.git", + "gitRemotePushUrl": "推送地址(可选)", + "gitRemotePushUrlHint": "留空则与抓取地址相同", + "gitRemoteNameRequired": "请输入远程名称", + "gitRemoteUrlRequired": "请输入远程地址", + "gitRemoteAdded": "已添加远程仓库 {name}", + "@gitRemoteAdded": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "gitRemoteRemoved": "已移除远程仓库 {name}", + "@gitRemoteRemoved": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "gitRemoteRenamed": "已将 {old} 重命名为 {newName}", + "@gitRemoteRenamed": { + "placeholders": { + "old": { + "type": "String" + }, + "newName": { + "type": "String" + } + } + }, + "gitRemoteUrlUpdated": "已更新远程地址", + "gitRemotePruned": "已清理远端已删除的分支", + "gitRemoteRemoveConfirm": "确定要移除远程仓库 {name} 吗?本地代码不会被删除。", + "@gitRemoteRemoveConfirm": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "gitRemoteEdit": "编辑远程仓库", + "gitRemoteFetchUrl": "抓取地址", + "gitRemoteSetPushUrl": "设置推送地址", + "gitRemotePrune": "清理失效分支", + "gitCheckConnection": "检测连接", + "gitCheckConnectionSuccess": "连接正常,认证可用", + "gitNoRemotes": "暂无远程仓库", + "gitFetchFailed": "抓取失败", + "gitPullFailed": "拉取失败", + "gitPushFailed": "推送失败", + "gitForcePush": "强制推送", + "gitForcePushTooltip": "覆盖远端分支(使用 --force-with-lease 安全校验)", + "gitForcePushWarning": "强制推送会用本地提交覆盖远端分支,可能导致他人提交丢失。", + "gitForcePushConfirm": "确认强制推送", + "gitForcePushConfirmDesc": "该操作将改写远端 {branch} 分支的历史。仅在确认远端没有他人新提交时使用。", + "@gitForcePushConfirmDesc": { + "placeholders": { + "branch": { + "type": "String" + } + } + }, + "gitForcePushUseLease": "使用安全强推(--force-with-lease)", + "gitPullThenPush": "先拉取再推送", + "gitPullThenPushDesc": "远端存在本地没有的提交,先拉取合并后再推送。", + "gitConflictAbort": "放弃本次变基", + "gitConflictAbortConfirm": "确定要放弃本次变基操作并回到操作前的状态吗?", + "gitUncommittedChangesTitle": "存在未提交的改动", + "gitUncommittedChangesDesc": "拉取前需要先处理本地未提交的改动,否则可能被覆盖。", + "gitUncommittedStashAndPull": "贮藏并拉取", + "gitUncommittedCommitFirst": "先去提交", + "gitUncommittedCancel": "取消", + "gitStashAndPullSuccess": "已贮藏本地改动并完成拉取", + "gitViewOperationLog": "查看详情", + "gitHideOperationLog": "收起详情", + "gitAheadBehind": "领先 {ahead} / 落后 {behind}", + "@gitAheadBehind": { + "placeholders": { + "ahead": { + "type": "int" + }, + "behind": { + "type": "int" + } + } + }, + "gitUpstreamGone": "上游分支已不存在", + "gitBehindTooltip": "本地落后远端 {behind} 个提交", + "@gitBehindTooltip": { + "placeholders": { + "behind": { + "type": "int" + } + } + }, + "gitAheadTooltip": "本地领先远端 {ahead} 个提交", + "@gitAheadTooltip": { + "placeholders": { + "ahead": { + "type": "int" + } + } + }, + "gitDiff": "差异对比", "gitDiffOriginal": "原始版本", "gitDiffModified": "修改版本", diff --git a/lib/main.dart b/lib/main.dart index 3e7617b..61f1202 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -20,7 +20,7 @@ void main() { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setSystemUIOverlayStyle( const SystemUiOverlayStyle( - statusBarColor: Colors.transparent, + statusBarColor: Colors.transparent, ), ); runApp(const MyApp()); diff --git a/lib/models/git_model.dart b/lib/models/git_model.dart index bf10670..660fdab 100644 --- a/lib/models/git_model.dart +++ b/lib/models/git_model.dart @@ -38,6 +38,259 @@ class GitFileStatus { } } +/// 推送目标远程的解析来源 +/// +/// 用于在 UI 上解释「为什么推送会发到这个远程」,避免多远程或 fork 场景下 +/// 用户对推送去向了哪个仓库产生误解。 +enum GitRemoteSource { + /// 无可用远程 + none, + + /// 分支级配置 `branch..pushRemote` + pushRemote, + + /// 仓库级配置 `remote.pushDefault` + pushDefault, + + /// 当前分支的上游远程(`git status` 的 branch.upstream) + upstream, + + /// 分支配置 `branch..remote`(尚未建立上游追踪时) + branchRemote, + + /// 兜底:优先名为 origin 的远程,否则取列表第一个 + fallback, + + /// 用户在本会话中手动指定(优先级最高,不落盘) + manualOverride, +} + +/// 远端追踪分支(`origin/feature-x` 这类) +/// +/// 与 [GitRemote] 不同:后者是"远程仓库"(一个名字 + 地址), +/// 这里指的是远端仓库里的**某一条分支**在本地留下的追踪引用。 +class GitRemoteBranch { + /// 完整引用名(如 `origin/feature-x`) + final String name; + + /// 所属远程仓库名(如 `origin`) + final String remoteName; + + /// 远端分支名(如 `feature-x`) + final String branchName; + + /// 是否已被某个本地分支检出(`git branch -r` 中的 `*`) + final bool isCheckedOut; + + /// 同名的本地分支名 —— 即基于此远端分支创建后本地会叫这个名字 + String get localBranchName => branchName; + + const GitRemoteBranch({ + required this.name, + required this.remoteName, + required this.branchName, + this.isCheckedOut = false, + }); + + @override + bool operator ==(Object other) => + identical(this, other) || + other is GitRemoteBranch && + runtimeType == other.runtimeType && + name == other.name; + + @override + int get hashCode => name.hashCode; + + @override + String toString() => 'GitRemoteBranch($name${isCheckedOut ? ", checkedOut" : ""})'; +} + +/// 仓库完整性自检结果(`git fsck`) +class GitFsckReport { + /// 对象库是否健康(无缺失、无损坏且退出码为 0) + final bool isHealthy; + + /// 是否存在对象丢失 —— 这是会导致提交失败(Error building trees)的严重问题 + final bool hasObjectLoss; + + /// 缺失/断链的对象描述 + final List missing; + + /// 损坏的对象或无法归类的错误行 + final List corrupt; + + /// 悬空对象(正常现象,不影响使用) + final List dangling; + + final int exitCode; + + const GitFsckReport({ + required this.isHealthy, + required this.hasObjectLoss, + this.missing = const [], + this.corrupt = const [], + this.dangling = const [], + this.exitCode = 0, + }); + + /// 需要用户关注的问题总数(不含 dangling) + int get problemCount => missing.length + corrupt.length; + + @override + String toString() => + 'GitFsckReport(healthy=$isHealthy, missing=${missing.length}, ' + 'corrupt=${corrupt.length}, dangling=${dangling.length})'; +} + +/// Git 远程仓库描述符(name / fetchUrl / pushUrl) +class GitRemote { + final String name; + + /// 拉取地址(`git remote -v` 的 fetch 行) + final String fetchUrl; + + /// 推送地址:仅当与 [fetchUrl] 不同时才非空 + final String? pushUrl; + + const GitRemote({ + required this.name, + required this.fetchUrl, + this.pushUrl, + }); + + /// 推送实际使用的地址(未单独配置则回退到 fetch 地址) + String get effectivePushUrl => pushUrl ?? fetchUrl; + + /// 是否为 SSH 协议地址(`git@host:path` 或 `ssh://`) + bool get isSsh => + fetchUrl.startsWith('git@') || + fetchUrl.startsWith('ssh://') || + fetchUrl.startsWith('git+ssh://'); + + /// 是否为 HTTPS 协议地址(走 ~/.git-credentials 免密) + bool get isHttps => + fetchUrl.startsWith('https://') || fetchUrl.startsWith('http://'); + + /// 提取主机名(供账号匹配与展示) + String? get host { + final uri = Uri.tryParse(fetchUrl); + if (uri != null && uri.host.isNotEmpty) return uri.host; + // 兼容 scp 风格 `git@github.com:owner/repo.git` + final match = RegExp(r'^[^@]+@([^:]+):').firstMatch(fetchUrl); + return match?.group(1); + } + + /// 提取仓库路径(如 `owner/repo.git`) + String? get repositoryPath { + final uri = Uri.tryParse(fetchUrl); + if (uri != null && uri.path.isNotEmpty) { + return uri.path.replaceFirst(RegExp(r'^/+'), ''); + } + final match = RegExp(r'^[^@]+@[^:]+:(.+)$').firstMatch(fetchUrl); + return match?.group(1); + } + + @override + bool operator ==(Object other) => + identical(this, other) || + other is GitRemote && + runtimeType == other.runtimeType && + name == other.name && + fetchUrl == other.fetchUrl && + pushUrl == other.pushUrl; + + @override + int get hashCode => Object.hash(name, fetchUrl, pushUrl); + + @override + String toString() => 'GitRemote($name: $fetchUrl)'; +} + +/// 本地分支的上游追踪状态(ahead/behind 是云端功能 UI 的中枢信号) +class GitBranchTracking { + /// 本地分支名 + final String branch; + + /// 上游引用(如 `origin/main`);为 null 表示尚未设置上游 + final String? upstream; + + /// 领先上游的提交数 + final int ahead; + + /// 落后上游的提交数 + final int behind; + + /// 上游分支已被远端删除(`git status` 中的 `[gone]`) + final bool isGone; + + const GitBranchTracking({ + required this.branch, + this.upstream, + this.ahead = 0, + this.behind = 0, + this.isGone = false, + }); + + /// 是否已设置上游追踪分支 + bool get hasUpstream => upstream != null && upstream!.isNotEmpty; + + /// 本地与远端均已产生新提交(需要先 pull 再 push) + bool get isDiverged => ahead > 0 && behind > 0; + + /// 是否需要推送到远端 + bool get needsPush => hasUpstream && ahead > 0; + + /// 是否需要从远端拉取 + bool get needsPull => hasUpstream && behind > 0; + + /// 是否与上游完全同步 + bool get isUpToDate => hasUpstream && ahead == 0 && behind == 0; + + /// 上游对应的远程仓库名(如 `origin`) + String? get remoteName { + if (!hasUpstream) return null; + final idx = upstream!.indexOf('/'); + return idx > 0 ? upstream!.substring(0, idx) : null; + } + + /// 上游对应的分支名(如 `main`) + String? get upstreamBranch { + if (!hasUpstream) return null; + final idx = upstream!.indexOf('/'); + return idx >= 0 && idx + 1 < upstream!.length ? upstream!.substring(idx + 1) : null; + } + + /// 未设置上游时的初始状态 + factory GitBranchTracking.noUpstream(String branch) => + GitBranchTracking(branch: branch); + + @override + String toString() => + 'GitBranchTracking($branch -> ${upstream ?? "none"}, +$ahead/-$behind)'; +} + +/// 云端操作的实时进度(驱动面板内联进度条) +class GitOperationProgress { + /// 操作类型标识:fetch / pull / push / clone + final String phase; + + /// 0~100 的百分比;无法解析时为 null(UI 应展示不确定态进度条) + final int? percent; + + /// 原始输出行,供"查看详情"展开 + final String raw; + + const GitOperationProgress({ + required this.phase, + this.percent, + this.raw = '', + }); + + @override + String toString() => 'GitOperationProgress($phase, ${percent ?? "-"}%)'; +} + /// Git 仓库信息(支持根仓库及子模块/嵌套仓库) class GitRepositoryInfo { final String rootPath; @@ -45,11 +298,19 @@ class GitRepositoryInfo { final bool isRoot; final String? currentBranch; + /// 已配置的远程仓库列表 + final List remotes; + + /// 当前分支的上游追踪状态 + final GitBranchTracking? tracking; + const GitRepositoryInfo({ required this.rootPath, required this.name, this.isRoot = false, this.currentBranch, + this.remotes = const [], + this.tracking, }); GitRepositoryInfo copyWith({ @@ -57,15 +318,31 @@ class GitRepositoryInfo { String? name, bool? isRoot, String? currentBranch, + List? remotes, + GitBranchTracking? tracking, }) { return GitRepositoryInfo( rootPath: rootPath ?? this.rootPath, name: name ?? this.name, isRoot: isRoot ?? this.isRoot, currentBranch: currentBranch ?? this.currentBranch, + remotes: remotes ?? this.remotes, + tracking: tracking ?? this.tracking, ); } + /// 是否已配置任何远程仓库 + bool get hasRemote => remotes.isNotEmpty; + + /// 默认远程仓库(优先 origin,否则取第一个) + GitRemote? get defaultRemote { + if (remotes.isEmpty) return null; + for (final r in remotes) { + if (r.name == 'origin') return r; + } + return remotes.first; + } + @override bool operator ==(Object other) => identical(this, other) || diff --git a/lib/providers/git_provider.dart b/lib/providers/git_provider.dart index b9094c5..0c80178 100644 --- a/lib/providers/git_provider.dart +++ b/lib/providers/git_provider.dart @@ -1,8 +1,11 @@ import 'package:flutter/foundation.dart'; import 'package:path/path.dart' as p; import '../models/git_model.dart'; +import '../services/distro_manager.dart'; +import '../services/git_account_service.dart'; import '../services/git_service.dart'; import '../utils/git_decoration_utils.dart'; +import '../utils/git_error_mapper.dart'; /// Git 状态管理 Provider class GitProvider extends ChangeNotifier { @@ -31,6 +34,46 @@ class GitProvider extends ChangeNotifier { int _commitsLimit = 50; bool _isLoadingMoreCommits = false; + // ---------------- 云端(远程仓库)状态 ---------------- + + /// 当前仓库已配置的远程仓库列表 + List _remotes = []; + + /// 当前分支的上游追踪状态(ahead/behind) + GitBranchTracking? _tracking; + + /// 远端追踪分支列表(`origin/xxx`) + List _remoteBranches = []; + + /// 最近一次仓库自检结果 + GitFsckReport? _fsckReport; + + bool _isFsckRunning = false; + + /// 克隆进行中的进度 + GitOperationProgress? _cloneProgress; + + bool _isCloning = false; + + bool _isFetching = false; + bool _isPulling = false; + bool _isPushing = false; + + /// 最近一次云端操作的实时进度(驱动内联进度条) + GitOperationProgress? _remoteProgress; + + /// 最近一次云端操作的原始输出,供"查看详情"展开 + String _remoteLog = ''; + + /// 最近一次云端操作的结构化错误 + GitErrorInfo? _lastRemoteError; + + /// 进行中的云端操作取消令牌 + HeadlessCancelToken? _remoteCancelToken; + + /// 最近一次 fetch 完成时间(用于决定是否提示用户刷新) + DateTime? _lastFetchAt; + // UI 内存状态缓存(保留折叠状态、输入框草稿与滚动位置) bool _stagedExpanded = true; bool _unstagedExpanded = true; @@ -63,6 +106,155 @@ class GitProvider extends ChangeNotifier { bool get isLoadingMoreCommits => _isLoadingMoreCommits; bool get hasMoreCommits => _totalCommitsCount > 0 ? _commits.length < _totalCommitsCount : false; + // ---------------- 云端状态 Getters ---------------- + + List get remotes => List.unmodifiable(_remotes); + GitBranchTracking? get tracking => _tracking; + + /// 远端追踪分支(用于分支选择器分区展示与检出) + List get remoteBranches => List.unmodifiable(_remoteBranches); + GitFsckReport? get fsckReport => _fsckReport; + bool get isFsckRunning => _isFsckRunning; + bool get isCloning => _isCloning; + GitOperationProgress? get cloneProgress => _cloneProgress; + bool get isFetching => _isFetching; + bool get isPulling => _isPulling; + bool get isPushing => _isPushing; + GitOperationProgress? get remoteProgress => _remoteProgress; + String get remoteLog => _remoteLog; + GitErrorInfo? get lastRemoteError => _lastRemoteError; + DateTime? get lastFetchAt => _lastFetchAt; + + /// 是否有任何云端操作正在进行(用于禁用并发按钮) + bool get isRemoteBusy => _isFetching || _isPulling || _isPushing; + + /// 是否已配置远程仓库 + bool get hasRemote => _remotes.isNotEmpty; + + /// 默认远程仓库(优先 origin) + GitRemote? get defaultRemote { + if (_remotes.isEmpty) return null; + for (final r in _remotes) { + if (r.name == 'origin') return r; + } + return _remotes.first; + } + + // ---------------- 远程目标解析 ---------------- + // + // 「上游」与「推送目标」是两个概念:单人项目里通常都是 origin,但 fork 协作 + // 场景必须分开(从 upstream 拉、往自己的 fork 推)。这里遵循 git 自身的优先级, + // 使用户在命令行里配过的 pushRemote / remote.pushDefault 同样在面板生效。 + + /// 缓存的分支级推送远程(`branch..pushRemote`) + String? _branchPushRemote; + + /// 缓存的全局推送默认远程(`remote.pushDefault`) + String? _remotePushDefault; + + /// 缓存的分支级抓取远程(`branch..remote`) + String? _branchRemote; + + /// 解析推送目标:pushRemote → remote.pushDefault → 上游远程 → origin/第一个 + ({GitRemote? remote, GitRemoteSource source}) get pushTarget => + _resolvePushTarget(); + + /// 本会话内用户手动指定的推送目标(覆盖 git 配置,不落盘) + /// + /// 做成会话级覆盖而不是写 git config:切换仓库即失效, + /// 避免一次临时选择被永久写进仓库配置。 + String? _pushTargetOverride; + + bool get hasPushTargetOverride => _pushTargetOverride != null; + + /// 手动指定推送目标;传 null 恢复按 git 配置自动解析 + void setPushTargetOverride(String? remoteName) { + if (_pushTargetOverride == remoteName) return; + _pushTargetOverride = remoteName; + notifyListeners(); + } + + ({GitRemote? remote, GitRemoteSource source}) _resolvePushTarget() { + if (_remotes.isEmpty) { + return (remote: null, source: GitRemoteSource.none); + } + + // 用户在本会话中的显式选择优先级最高 + if (_pushTargetOverride != null) { + final override = _remoteByName(_pushTargetOverride); + if (override != null) { + return (remote: override, source: GitRemoteSource.manualOverride); + } + // 兜底:正常情况下覆盖会在远程列表变化时被即时清除, + // 这里再拦一次,避免静默回落到别的远程却不告诉用户。 + _pushTargetOverride = null; + } + + final upstreamName = _tracking?.remoteName; + final upstream = _remoteByName(upstreamName); + // 分支尚未建立追踪时,其「上游」等价于 git 的 branch..remote + final branchRemote = _remoteByName(_branchRemote); + + // 1. branch..pushRemote + final pushRemote = _remoteByName(_branchPushRemote); + if (pushRemote != null) { + return (remote: pushRemote, source: GitRemoteSource.pushRemote); + } + // 2. remote.pushDefault + final pushDefault = _remoteByName(_remotePushDefault); + if (pushDefault != null) { + return (remote: pushDefault, source: GitRemoteSource.pushDefault); + } + // 3. 上游 / 分支配置的远程 + if (upstream != null) { + return (remote: upstream, source: GitRemoteSource.upstream); + } + if (branchRemote != null) { + return (remote: branchRemote, source: GitRemoteSource.branchRemote); + } + // 4. origin / 第一个 + return (remote: defaultRemote, source: GitRemoteSource.fallback); + } + + /// 解析抓取目标:`branch..remote` → 上游远程 → origin/第一个 + /// + /// 必须优先于 defaultRemote:fork 场景下分支追踪的是 upstream, + /// 若抓取固定走 origin,则 upstream/* 永不更新,ahead/behind 会一直算错。 + GitRemote? get fetchTarget { + if (_remotes.isEmpty) return null; + return _remoteByName(_branchRemote) ?? + _remoteByName(_tracking?.remoteName) ?? + defaultRemote; + } + + /// 解析拉取目标:上游远程 → origin/第一个 + GitRemote? get pullTarget { + if (_remotes.isEmpty) return null; + return _remoteByName(_tracking?.remoteName) ?? defaultRemote; + } + + GitRemote? _remoteByName(String? name) { + if (name == null || name.isEmpty) return null; + for (final r in _remotes) { + if (r.name == name) return r; + } + return null; + } + + /// 待推送的提交数(无上游时为 0,UI 应改为展示"发布分支") + int get aheadCount => _tracking?.ahead ?? 0; + + /// 待拉取的提交数 + int get behindCount => _tracking?.behind ?? 0; + + /// 当前分支是否需要建立上游追踪关系 + bool get needsPublishBranch { + final branch = _currentBranch; + if (branch == null || branch.isEmpty) return false; + if (_tracking == null) return false; + return !_tracking!.hasUpstream || _tracking!.isGone; + } + bool get stagedExpanded => _stagedExpanded; bool get unstagedExpanded => _unstagedExpanded; bool get graphExpanded => _graphExpanded; @@ -131,6 +323,7 @@ class GitProvider extends ChangeNotifier { _commits = []; _stashCount = 0; _errorMessage = null; + _clearRemoteState(); if (_rootPath != null) { refresh(); @@ -143,6 +336,8 @@ class GitProvider extends ChangeNotifier { /// 响应底层运行容器被销毁重建:立即失效环境缓存,清空内存仓库与分支状态,恢复未安装引导 void onContainerReset() { _gitService.invalidateEnvStatus(); + // 容器 rootfs 被重建后 ~/.git-credentials 一并丢失,需重新灌注 + GitAccountService.instance.invalidateCredentialSync(); _gitInstalled = false; _gitVersion = null; _repositories = []; @@ -156,9 +351,49 @@ class GitProvider extends ChangeNotifier { _stashCount = 0; _errorMessage = '底层容器已重置,需重新安装 Git 工具链'; _isLoading = false; + _clearRemoteState(); notifyListeners(); } + /// 清空云端相关状态(切换项目 / 容器重置 / 切换仓库时调用) + void _clearRemoteState() { + _remotes = []; + _tracking = null; + _remoteBranches = []; + _fsckReport = null; + _isFsckRunning = false; + _cloneProgress = null; + _isCloning = false; + _isFetching = false; + _isPulling = false; + _isPushing = false; + _remoteProgress = null; + _remoteLog = ''; + _lastRemoteError = null; + _lastFetchAt = null; + _remoteCancelToken = null; + _branchPushRemote = null; + _remotePushDefault = null; + _branchRemote = null; + _pushTargetOverride = null; + } + + /// 读取与远程目标解析相关的 git 配置 + /// + /// 这些值决定 push/fetch 走哪个远程;必须与仓库同步刷新, + /// 否则用户在命令行改过 pushRemote 后面板不会跟随。 + Future _loadRemoteTargetConfig() async { + if (_currentRepoPath == null) return; + final branch = _currentBranch ?? ''; + try { + _branchPushRemote = await _gitService.getBranchPushRemote(_currentRepoPath!, branch); + _remotePushDefault = await _gitService.getRemotePushDefault(_currentRepoPath!); + _branchRemote = await _gitService.getBranchRemote(_currentRepoPath!, branch); + } catch (e) { + debugPrint('[GitProvider] 读取远程目标配置异常: $e'); + } + } + int _refreshSeq = 0; /// 刷新 Git 状态与仓库信息 @@ -176,6 +411,7 @@ class GitProvider extends ChangeNotifier { _commits = []; _stashCount = 0; _isLoading = false; + _clearRemoteState(); notifyListeners(); return; } @@ -220,6 +456,7 @@ class GitProvider extends ChangeNotifier { _changedFiles = []; _rebuildStatusMaps(); _currentBranch = null; + _clearRemoteState(); } } catch (e) { if (seq == _refreshSeq) { @@ -411,6 +648,9 @@ class GitProvider extends ChangeNotifier { if (res.success) { _currentBranch = branchName; _isCurrentRefTag = false; + // 推送目标是按分支解析的:换了分支就必须重新解析, + // 否则在 main 上选的远程会被带到 feature 分支上(可能推错仓库)。 + _pushTargetOverride = null; await _loadCurrentRepoDetails(); notifyListeners(); } @@ -422,6 +662,7 @@ class GitProvider extends ChangeNotifier { if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); final res = await _gitService.createBranch(_currentRepoPath!, branchName, checkout: checkout); if (res.success) { + if (checkout) _pushTargetOverride = null; await _loadCurrentRepoDetails(); notifyListeners(); } @@ -512,6 +753,8 @@ class GitProvider extends ChangeNotifier { if (res.success) { _currentBranch = tagName; _isCurrentRefTag = true; + // 标签检出后处于 detached HEAD,同样需要重新解析推送目标 + _pushTargetOverride = null; await _loadCurrentRepoDetails(); notifyListeners(); } @@ -574,16 +817,505 @@ class GitProvider extends ChangeNotifier { } _stashCount = await _gitService.getStashCount(_currentRepoPath!); + // 加载远程仓库列表与上游追踪状态(ahead/behind) + _remotes = await _gitService.getRemotes(_currentRepoPath!); + _tracking = await _gitService.getBranchTracking(_currentRepoPath!); + _remoteBranches = await _gitService.getRemoteBranches(_currentRepoPath!); + // 远程目标解析依赖 branch..* 与 remote.pushDefault + await _loadRemoteTargetConfig(); + // 同步更新 repositories 列表中当前项的分支信息 final idx = _repositories.indexWhere((r) => r.rootPath == _currentRepoPath); if (idx != -1) { - _repositories[idx] = _repositories[idx].copyWith(currentBranch: _currentBranch); + _repositories[idx] = _repositories[idx].copyWith( + currentBranch: _currentBranch, + remotes: _remotes, + tracking: _tracking, + ); } } catch (e) { debugPrint('[GitProvider] 加载仓库详情异常: $e'); } } + // ========================================================================== + // 云端(远程仓库)操作 + // ========================================================================== + + /// 仅刷新远端相关状态(不重跑提交历史等重活),用于网络操作完成后的即时反馈 + Future _loadRemoteStateOnly() async { + if (_currentRepoPath == null) return; + try { + _remotes = await _gitService.getRemotes(_currentRepoPath!); + _tracking = await _gitService.getBranchTracking(_currentRepoPath!); + // fetch/push 都可能带来新的远端分支,必须一并刷新 + _remoteBranches = await _gitService.getRemoteBranches(_currentRepoPath!); + // 首次 push --set-upstream 会写入 branch..remote,需重新读取 + await _loadRemoteTargetConfig(); + } catch (e) { + debugPrint('[GitProvider] 刷新远端状态异常: $e'); + } + } + + /// 把一次云端命令的执行结果转换为结构化错误并记录原始输出 + void _recordRemoteResult(GitRemoteCommandResult res) { + _remoteLog = res.combinedOutput.trim(); + if (res.success || res.cancelled) { + _lastRemoteError = null; + return; + } + _lastRemoteError = GitErrorMapper.describe(res.stderr, stdout: res.stdout); + } + + void _beginRemoteOperation() { + _remoteProgress = null; + _remoteLog = ''; + _lastRemoteError = null; + _remoteCancelToken = HeadlessCancelToken(); + } + + /// 云端网络操作前的准备:确保容器内凭据文件是最新的 + /// + /// 容器重建会连同 rootfs 一起丢掉 ~/.git-credentials,若不重写就会出现 + /// "凭据明明配好了却报认证失败" 的迷惑现象。 + Future _prepareRemoteOperation() async { + try { + await GitAccountService.instance.ensureContainerCredentials(); + } catch (e) { + debugPrint('[GitProvider] 凭据灌注异常: $e'); + } + } + + void _endRemoteOperation() { + _remoteCancelToken = null; + _remoteProgress = null; + } + + void _onProgress(GitOperationProgress progress) { + _remoteProgress = progress; + notifyListeners(); + } + + /// 请求取消当前进行中的云端操作 + void cancelRemoteOperation() { + _remoteCancelToken?.cancel(); + notifyListeners(); + } + + /// 抓取远端更新 + Future fetchRemote({String? remote}) async { + if (_currentRepoPath == null) { + return GitRemoteCommandResult.error('未选择仓库'); + } + if (isRemoteBusy) { + return GitRemoteCommandResult.error('已有云端操作正在进行,请稍候'); + } + + _isFetching = true; + _beginRemoteOperation(); + await _prepareRemoteOperation(); + notifyListeners(); + + try { + final res = await _gitService.fetch( + _currentRepoPath!, + rootPath: _rootPath, + // 修复:原先直接取 defaultRemote,fork 场景下会永远抓 origin + // 而漏掉上游,导致 upstream/* 过期、ahead/behind 长期算错。 + remote: remote ?? fetchTarget?.name, + onProgress: _onProgress, + cancelToken: _remoteCancelToken, + ); + _recordRemoteResult(res); + if (res.success) _lastFetchAt = DateTime.now(); + // fetch 会改变 ahead/behind,必须即时刷新远端状态 + await _loadRemoteStateOnly(); + return res; + } finally { + _isFetching = false; + _endRemoteOperation(); + notifyListeners(); + } + } + + /// 拉取远端改动(rebase 方式) + /// + /// [remote]/[branch] 缺省时使用当前分支的上游。 + Future pull({ + String? remote, + String? branch, + }) async { + if (_currentRepoPath == null) { + return GitRemoteCommandResult.error('未选择仓库'); + } + if (isRemoteBusy) { + return GitRemoteCommandResult.error('已有云端操作正在进行,请稍候'); + } + + final targetRemote = remote ?? pullTarget?.name; + final targetBranch = branch ?? _tracking?.upstreamBranch; + + _isPulling = true; + _beginRemoteOperation(); + await _prepareRemoteOperation(); + notifyListeners(); + + try { + final res = await _gitService.pullRebase( + _currentRepoPath!, + rootPath: _rootPath, + remote: targetRemote, + branch: targetBranch, + onProgress: _onProgress, + cancelToken: _remoteCancelToken, + ); + _recordRemoteResult(res); + if (res.success) { + // pull 会改动工作区与提交历史,需完整刷新 + await _loadCurrentRepoDetails(); + notifyListeners(); + } else { + await _loadRemoteStateOnly(); + } + return res; + } finally { + _isPulling = false; + _endRemoteOperation(); + notifyListeners(); + } + } + + /// 推送当前分支到远端 + /// + /// [setUpstream] 用于首次发布分支;[forceWithLease] 为唯一允许的强制方式。 + Future push({ + String? remote, + String? branch, + bool? setUpstream, + bool forceWithLease = false, + }) async { + if (_currentRepoPath == null) { + return GitRemoteCommandResult.error('未选择仓库'); + } + if (isRemoteBusy) { + return GitRemoteCommandResult.error('已有云端操作正在进行,请稍候'); + } + + // 推送目标遵循 git 自身优先级:pushRemote → pushDefault → 上游 → origin + final targetRemote = remote ?? pushTarget.remote?.name; + final targetBranch = branch ?? _currentBranch; + final shouldSetUpstream = setUpstream ?? needsPublishBranch; + + _isPushing = true; + _beginRemoteOperation(); + await _prepareRemoteOperation(); + notifyListeners(); + + try { + final res = await _gitService.push( + _currentRepoPath!, + rootPath: _rootPath, + remote: targetRemote, + branch: targetBranch, + setUpstream: shouldSetUpstream, + forceWithLease: forceWithLease, + onProgress: _onProgress, + cancelToken: _remoteCancelToken, + ); + _recordRemoteResult(res); + if (res.success) { + await _loadRemoteStateOnly(); + } + return res; + } finally { + _isPushing = false; + _endRemoteOperation(); + notifyListeners(); + } + } + + /// 推送被拒后的一键修复:先 pull(rebase) 再 push + Future<({bool success, GitRemoteCommandResult? pullResult, GitRemoteCommandResult? pushResult})> + pullThenPush() async { + if (_currentRepoPath == null) { + return (success: false, pullResult: null, pushResult: null); + } + + final pullRes = await pull(); + if (!pullRes.success) { + return (success: false, pullResult: pullRes, pushResult: null); + } + + final pushRes = await push(); + return (success: pushRes.success, pullResult: pullRes, pushResult: pushRes); + } + + // ------------------------------ 远端仓库管理 ------------------------------ + + /// 重新加载远程仓库列表 + Future reloadRemotes() async { + if (_currentRepoPath == null) return; + _remotes = await _gitService.getRemotes(_currentRepoPath!); + // 远程集合变化可能使会话级选择失效(被删除/改名), + // 这里即时清除而不是等到读取时才发现,避免状态长期不一致。 + if (_pushTargetOverride != null && _remoteByName(_pushTargetOverride) == null) { + _pushTargetOverride = null; + } + notifyListeners(); + } + + /// 添加远程仓库 + Future addRemote( + String name, + String url, { + String? pushUrl, + }) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.addRemote( + _currentRepoPath!, + name, + url, + pushUrl: pushUrl, + ); + if (res.success) await reloadRemotes(); + return res; + } + + /// 移除远程仓库 + Future removeRemote(String name) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.removeRemote(_currentRepoPath!, name); + if (res.success) { + await reloadRemotes(); + // 移除远程仓库会影响上游追踪关系 + _tracking = await _gitService.getBranchTracking(_currentRepoPath!); + notifyListeners(); + } + return res; + } + + /// 重命名远程仓库 + Future renameRemote(String oldName, String newName) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.renameRemote(_currentRepoPath!, oldName, newName); + if (res.success) { + await reloadRemotes(); + _tracking = await _gitService.getBranchTracking(_currentRepoPath!); + notifyListeners(); + } + return res; + } + + /// 修改远程仓库地址 + Future setRemoteUrl( + String name, + String url, { + bool push = false, + }) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.setRemoteUrl( + _currentRepoPath!, + name, + url, + push: push, + ); + if (res.success) await reloadRemotes(); + return res; + } + + /// 清理远端已删除的追踪分支 + Future pruneRemote(String name) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.pruneRemote(_currentRepoPath!, name); + if (res.success) await reloadRemotes(); + return res; + } + + /// 自检:验证远端地址的连通性与认证是否可用 + Future checkRemoteAuth(String url) async { + if (_currentRepoPath == null) { + return GitRemoteCommandResult.error('未选择仓库'); + } + _beginRemoteOperation(); + await _prepareRemoteOperation(); + notifyListeners(); + try { + final res = await _gitService.checkRemoteAuth( + _currentRepoPath!, + url, + rootPath: _rootPath, + cancelToken: _remoteCancelToken, + ); + _recordRemoteResult(res); + return res; + } finally { + _endRemoteOperation(); + notifyListeners(); + } + } + + /// 清除最近一次云端错误提示 + void clearRemoteError() { + _lastRemoteError = null; + _remoteLog = ''; + notifyListeners(); + } + + // ---------------------------- 远端分支检出 ---------------------------- + + /// 基于远端分支检出(或切换到已有的)本地分支 + /// + /// 本地已有同名分支时直接切换;否则以远端分支为起点创建并建立追踪关系。 + Future checkoutRemoteBranch( + GitRemoteBranch branch, { + bool forceCreate = false, + }) async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.checkoutRemoteBranch( + _currentRepoPath!, + branch.remoteName, + branch.branchName, + forceCreate: forceCreate, + ); + if (res.success) { + _pushTargetOverride = null; + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + // ---------------------------- 仓库自检 ---------------------------- + + /// 执行仓库完整性自检 + Future runFsck() async { + if (_currentRepoPath == null) return null; + if (_isFsckRunning) return _fsckReport; + + _isFsckRunning = true; + notifyListeners(); + try { + _fsckReport = await _gitService.fsck(_currentRepoPath!); + return _fsckReport; + } catch (e) { + debugPrint('[GitProvider] 仓库自检异常: $e'); + return null; + } finally { + _isFsckRunning = false; + notifyListeners(); + } + } + + /// 清除自检结果 + void clearFsckReport() { + _fsckReport = null; + notifyListeners(); + } + + // ---------------------------- 克隆 ---------------------------- + + /// 克隆远端仓库到指定项目的内部目录 + /// + /// [parentDir] 为克隆父目录(通常是项目根),克隆完成后目标目录为 + /// `parentDir/`。 + Future cloneRepository({ + required String parentDir, + required String url, + required String targetDirName, + String? branch, + int? depth, + HeadlessCancelToken? cancelToken, + }) async { + if (_isCloning) { + return GitRemoteCommandResult.error('已有克隆任务正在进行'); + } + + _isCloning = true; + _cloneProgress = null; + _lastRemoteError = null; + _remoteLog = ''; + _remoteCancelToken = cancelToken ?? HeadlessCancelToken(); + notifyListeners(); + + try { + await _prepareRemoteOperation(); + final res = await _gitService.clone( + parentDir, + url, + targetDirName, + rootPath: parentDir, + branch: branch, + depth: depth, + onProgress: _onCloneProgress, + cancelToken: _remoteCancelToken, + ); + _remoteLog = res.combinedOutput.trim(); + if (!res.success && !res.cancelled) { + _lastRemoteError = GitErrorMapper.describe(res.stderr, stdout: res.stdout); + } + return res; + } finally { + _isCloning = false; + _cloneProgress = null; + _remoteCancelToken = null; + notifyListeners(); + } + } + + void _onCloneProgress(GitOperationProgress progress) { + _cloneProgress = progress; + notifyListeners(); + } + + /// 取消进行中的克隆 + void cancelClone() { + if (!_isCloning) return; + _remoteCancelToken?.cancel(); + notifyListeners(); + } + + /// 放弃进行中的 rebase(冲突后的退出路径) + Future abortRebase() async { + if (_currentRepoPath == null) return GitCommandResult.error('未选择仓库'); + final res = await _gitService.abortRebase(_currentRepoPath!); + if (res.success) { + await _loadCurrentRepoDetails(); + notifyListeners(); + } + return res; + } + + /// 仓库是否正处于 rebase 中间状态 + bool get isRebaseInProgress => + _currentRepoPath != null && _gitService.isRebaseInProgress(_currentRepoPath!); + + /// 贮藏本地改动后拉取(不自动 pop,避免冲突被静默带入工作区) + /// + /// 拉取成功后本地改动仍在 stash 栈中,由用户在需要时手动恢复, + /// 这样"贮藏"这个动作始终对用户可见、可回退。 + Future<({bool success, GitRemoteCommandResult? pullResult, GitCommandResult? stashResult})> + stashAndPull() async { + if (_currentRepoPath == null) { + return (success: false, pullResult: null, stashResult: null); + } + + final stashRes = await _gitService.stash( + _currentRepoPath!, + message: 'Auto-stash before pull', + ); + if (!stashRes.success) { + return (success: false, pullResult: null, stashResult: stashRes); + } + await _loadCurrentRepoDetails(); + + final pullRes = await pull(); + return ( + success: pullRes.success, + pullResult: pullRes, + stashResult: stashRes, + ); + } + /// 预先计算文件和目录的 Git 状态映射,将文件树每帧查询时间复杂度从 O(N*M) 降至 O(1) void _rebuildStatusMaps() { final fileMap = {}; @@ -651,6 +1383,15 @@ class GitProvider extends ChangeNotifier { bool? showTagsInSelector, String? commitMessage, double? scrollOffset, + List? remotes, + GitBranchTracking? tracking, + bool? isFetching, + bool? isPulling, + bool? isPushing, + GitOperationProgress? remoteProgress, + String? remoteLog, + GitErrorInfo? lastRemoteError, + DateTime? lastFetchAt, }) { if (rootPath != null) _rootPath = rootPath; if (repositories != null) _repositories = repositories; @@ -682,6 +1423,15 @@ class GitProvider extends ChangeNotifier { if (showTagsInSelector != null) _showTagsInSelector = showTagsInSelector; if (commitMessage != null) _commitMessage = commitMessage; if (scrollOffset != null) _scrollOffset = scrollOffset; + if (remotes != null) _remotes = remotes; + if (tracking != null) _tracking = tracking; + if (isFetching != null) _isFetching = isFetching; + if (isPulling != null) _isPulling = isPulling; + if (isPushing != null) _isPushing = isPushing; + if (remoteProgress != null) _remoteProgress = remoteProgress; + if (remoteLog != null) _remoteLog = remoteLog; + if (lastRemoteError != null) _lastRemoteError = lastRemoteError; + if (lastFetchAt != null) _lastFetchAt = lastFetchAt; notifyListeners(); } } diff --git a/lib/services/git_account_service.dart b/lib/services/git_account_service.dart index 17e2fdf..dc61cce 100644 --- a/lib/services/git_account_service.dart +++ b/lib/services/git_account_service.dart @@ -103,12 +103,41 @@ class GitAccountService extends ChangeNotifier { final jsonList = _accounts.map((a) => a.toJson()).toList(); await file.writeAsString(const JsonEncoder.withIndent(' ').convert(jsonList)); notifyListeners(); + // 账号发生变更,需要强制重新灌注容器凭据 + _credentialsSyncedThisSession = false; await syncContainerCredentials(); + _credentialsSyncedThisSession = true; + } + + /// 确保容器内的 ~/.git-credentials 与本机保存的账号一致(每次 App 会话至多做一次) + /// + /// 云端网络操作(fetch/pull/push)执行前调用:容器被重建后凭据文件会随 rootfs + /// 一起丢失,若不重写,git 会立刻因缺少凭据而报认证失败。 + /// 不需要每次操作都同步,因此按会话缓存;账号增删改时由 [_saveToDisk] 强制刷新。 + static bool _credentialsSyncedThisSession = false; + + Future ensureContainerCredentials() async { + if (_credentialsSyncedThisSession) return; + try { + await loadAccounts(); + await syncContainerCredentials(); + _credentialsSyncedThisSession = true; + } catch (e) { + debugPrint('[GitAccountService] 确保容器凭据异常: $e'); + } + } + + /// 容器重建后需要重新灌注凭据 + void invalidateCredentialSync() { + _credentialsSyncedThisSession = false; } /// 将所有已保存的账号凭据同步写入容器的 ~/.git-credentials,使容器内终端与 UI 操作均免密生效 Future syncContainerCredentials() async { try { + // 仅 Android 的内置容器需要落盘凭据;宿主/桌面环境不走这条路径 + if (!Platform.isAndroid) return; + final engine = InternalEngineService.instance; if (!await engine.isEngineInstalled()) return; @@ -125,7 +154,10 @@ class GitAccountService extends ChangeNotifier { } } credFile.parent.createSync(recursive: true); - await credFile.writeAsString(lines.join('\n')); + // 末尾补换行:git 的 store helper 按行解析,缺少结尾换行虽可容错, + // 但会让 `cat` / `sed` 等排查手段把提示符粘在最后一行,容易误判。 + final content = lines.isEmpty ? '' : '${lines.join('\n')}\n'; + await credFile.writeAsString(content); // 确保全局开启 credential.helper store await DistroManager().runHeadlessCommand( diff --git a/lib/services/git_service.dart b/lib/services/git_service.dart index c67b53d..e0ad864 100644 --- a/lib/services/git_service.dart +++ b/lib/services/git_service.dart @@ -21,6 +21,56 @@ class GitEnvironmentStatus { }); } +/// 云端(网络)Git 操作的执行结果,附带完整原始输出供 UI 展开详情 +class GitRemoteCommandResult { + final bool success; + final int exitCode; + final String stdout; + final String stderr; + + /// 命令是否因用户取消而中止 + final bool cancelled; + + const GitRemoteCommandResult({ + required this.success, + required this.exitCode, + required this.stdout, + required this.stderr, + this.cancelled = false, + }); + + factory GitRemoteCommandResult.error(String message, {int exitCode = -1}) { + return GitRemoteCommandResult( + success: false, + exitCode: exitCode, + stdout: '', + stderr: message, + ); + } + + factory GitRemoteCommandResult.cancelled() => const GitRemoteCommandResult( + success: false, + exitCode: -1, + stdout: '', + stderr: '', + cancelled: true, + ); + + /// 合并后的输出,供错误映射使用 + String get combinedOutput => '$stderr\n$stdout'; +} + +/// 需要实时输出回调与取消能力的命令执行器签名(可注入以便测试) +typedef GitStreamRunner = Future Function({ + required String executable, + required List arguments, + required String workspacePath, + required String? containerWorkDir, + void Function(String chunk)? onOutput, + HeadlessCancelToken? cancelToken, + Duration timeout, +}); + /// Git 核心服务层(单例模式,封装底层命令行交互与文件系统快速探测) class GitService { static final GitService instance = GitService._internal(); @@ -31,6 +81,14 @@ class GitService { Future Function(String executable, List arguments, {String? workingDirectory})? processRunner; + /// 允许在测试环境下注入云端命令的流式执行器(跳过真实 PRoot 容器) + @visibleForTesting + GitStreamRunner? streamRunner; + + /// 允许在测试环境下覆写宿主路径 → 容器内路径的映射 + @visibleForTesting + String Function(String hostPath)? containerPathMapper; + /// 自定义 Git 可执行程序路径(默认从系统 PATH 查找 'git') String gitExecutable = 'git'; @@ -45,6 +103,8 @@ class GitService { /// 重置测试环境状态与进程注入 void resetForTesting() { processRunner = null; + streamRunner = null; + containerPathMapper = null; _cachedEnvStatus = null; } @@ -1116,4 +1176,819 @@ class GitService { runInShell: Platform.isWindows, ); } + + // ========================================================================== + // 云端(远程仓库)操作 + // + // 设计要点: + // 1. 容器启动配置使用 `/usr/bin/env -i` 完全隔离环境变量,因此从 Dart 侧 + // 传给 proot 进程的 environment 无法抵达容器内的 git。所有环境相关设置 + // (GIT_TERMINAL_PROMPT / GIT_SSH_COMMAND 等)必须内联进 guest 命令串。 + // 2. 由于没有 PTY,git 需要凭据时会尝试读取终端并长时间挂起。 + // GIT_TERMINAL_PROMPT=0 让其在缺少凭据时立即失败并给出可识别的报错。 + // 3. 非 TTY 下 git 默认关闭进度输出,网络命令必须显式传 --progress。 + // ========================================================================== + + /// 容器内 SSH 客户端参数:仅使用指定私钥、禁用交互,并自动接受首次出现的主机指纹 + /// + /// `BatchMode=yes` 保证密钥不被接受时立即失败而不是挂起等待密码输入; + /// `StrictHostKeyChecking=accept-new` 避免首次推送必然撞上 "Host key verification failed"。 + static const String containerSshCommand = + 'ssh -o StrictHostKeyChecking=accept-new -o BatchMode=yes ' + '-o IdentitiesOnly=yes -o ConnectTimeout=20 -i /root/.ssh/id_ed25519'; + + /// 宿主仓库路径 → 容器内路径(工程根挂载到 /workspace) + /// + /// 直接跑在宿主平台的测试环境里没有 /workspace 这层映射,此时原样返回。 + @visibleForTesting + String mapToContainerPath(String repoPath, String? rootPath) { + if (containerPathMapper != null) { + return containerPathMapper!(repoPath); + } + if (!Platform.isAndroid || rootPath == null || rootPath.trim().isEmpty) { + return repoPath; + } + final normalizedRepo = p.normalize(repoPath); + final normalizedRoot = p.normalize(rootPath); + if (normalizedRepo == normalizedRoot) return '/workspace'; + // 嵌套仓库(子模块)→ /workspace/<相对路径> + if (p.isWithin(normalizedRoot, normalizedRepo)) { + final relative = p.relative(normalizedRepo, from: normalizedRoot); + return '/workspace/$relative'.replaceAll(r'\', '/'); + } + return '/workspace'; + } + + /// 组装容器内实际执行的 git 命令串:注入禁交互环境与 SSH 参数 + @visibleForTesting + String buildGuestGitCommand(List args) { + final body = args.map(_escapeShellArg).join(' '); + // 注意:GIT_SSH_COMMAND 必须带引号,避免其中的 ssh 参数被当作独立命令 + return 'GIT_TERMINAL_PROMPT=0 ' + 'GIT_SSH_COMMAND="$containerSshCommand" ' + 'git -c safe.directory=* -c credential.interactive=false -c core.askPass= $body'; + } + + /// 从 git 进度输出行解析阶段名与百分比 + /// + /// 形如 `Receiving objects: 45% (450/1000), 1.2 MiB | 300 KiB/s`。 + /// 无法解析出百分比时返回 null,由 UI 展示不确定态进度。 + @visibleForTesting + int? parseProgressPercent(String line) { + final match = RegExp(r'(\d{1,3})%').firstMatch(line); + if (match == null) return null; + final value = int.tryParse(match.group(1)!); + if (value == null) return null; + return value.clamp(0, 100); + } + + /// 判断输出行是否为值得展示的进度行 + @visibleForTesting + bool isProgressLine(String line) { + final t = line.trim(); + if (t.isEmpty) return false; + if (t.startsWith('remote:')) return false; + // 形如 `Receiving objects: ...` / `Writing objects: ...` / `Counting objects: ...` + if (RegExp(r'^[A-Z][A-Za-z ]+:\s').hasMatch(t)) return true; + if (t.startsWith('From ') || t.startsWith('To ')) return true; + if (t.contains('->') && (t.contains('new branch') || t.contains('new tag'))) return true; + return false; + } + + /// 云端网络命令的默认超时 + /// + /// 大仓库(如 llama.cpp 这类上万提交的项目)在 Android + PRoot 下抓取/推送 + /// 的 packfile 很容易超过 5 分钟;超时会被 sigkill,表现为"进度走到一半就没了"。 + /// 因此放宽到 15 分钟 —— UI 侧始终提供取消按钮,用户不必干等。 + static const Duration remoteNetworkTimeout = Duration(minutes: 15); + + /// 执行一条云端 git 命令(带进度回调与取消能力) + Future runRemoteGitCommand( + String repoPath, + List args, { + String? rootPath, + Duration timeout = remoteNetworkTimeout, + void Function(GitOperationProgress progress)? onProgress, + HeadlessCancelToken? cancelToken, + }) async { + final env = await checkGitInstalled(); + if (!env.isInstalled) { + return GitRemoteCommandResult.error( + env.errorMessage ?? '未检测到 Git 命令行工具,请先在内置容器中安装 git', + ); + } + + final containerCmd = buildGuestGitCommand(args); + final containerWorkDir = mapToContainerPath(repoPath, rootPath); + + void emit(String chunk) { + if (onProgress == null) return; + for (final line in chunk.split('\n')) { + if (!isProgressLine(line)) continue; + onProgress(GitOperationProgress( + phase: _phaseOf(args), + percent: parseProgressPercent(line), + raw: line.trim(), + )); + } + } + + try { + final ProcessResult? res; + if (streamRunner != null) { + res = await streamRunner!( + executable: containerCmd, + arguments: const [], + workspacePath: repoPath, + containerWorkDir: containerWorkDir, + onOutput: emit, + cancelToken: cancelToken, + timeout: timeout, + ); + } else { + final runner = _defaultStreamRunner; + res = await runner( + executable: containerCmd, + arguments: const [], + workspacePath: repoPath, + containerWorkDir: containerWorkDir, + onOutput: emit, + cancelToken: cancelToken, + timeout: timeout, + ); + } + + // 取消:可能是取消令牌在流程中被触发,也可能是命令自身因超时被杀 + if (cancelToken?.isCancelled ?? false) { + return GitRemoteCommandResult.cancelled(); + } + if (res == null) { + return GitRemoteCommandResult.error('云端命令执行失败:容器引擎无响应'); + } + + return GitRemoteCommandResult( + success: res.exitCode == 0, + exitCode: res.exitCode, + stdout: res.stdout.toString(), + stderr: res.stderr.toString(), + ); + } catch (e) { + return GitRemoteCommandResult.error('云端命令异常: $e'); + } + } + + /// 从参数推断当前操作阶段(驱动 UI 文案) + String _phaseOf(List args) { + if (args.isEmpty) return 'git'; + if (args.contains('fetch')) return 'fetch'; + if (args.contains('pull')) return 'pull'; + if (args.contains('push')) return 'push'; + if (args.contains('clone')) return 'clone'; + if (args.contains('ls-remote')) return 'auth'; + if (args.contains('remote')) return 'remote'; + return args.first; + } + + /// 默认流式执行器:把命令投递到 PRoot 容器(或宿主回退)执行 + /// + /// 注意 [arguments] 为空,最终命令已内联在 [executable] 中, + /// 因为 runHeadlessCommand 只接受单一命令串。 + Future _defaultStreamRunnerImpl({ + required String executable, + required List arguments, + required String workspacePath, + required String? containerWorkDir, + void Function(String chunk)? onOutput, + HeadlessCancelToken? cancelToken, + Duration timeout = remoteNetworkTimeout, + }) async { + final fullCommand = arguments.isEmpty + ? executable + : '$executable ${arguments.map(_escapeShellArg).join(' ')}'; + + if (Platform.isAndroid) { + final engine = InternalEngineService.instance; + if (await engine.isEngineInstalled()) { + final rootfs = await engine.getRootfsDir(); + final res = await DistroManager().runHeadlessCommand( + systemName: DistroRepository.defaultSystemName, + customRootDir: rootfs, + workspacePath: workspacePath, + command: fullCommand, + timeout: timeout, + cancelToken: cancelToken, + onStdout: onOutput, + ); + if (res != null) return res; + } + } + + // 宿主回退(桌面调试场景),环境变量已内联在命令串前缀中 + if (cancelToken != null) { + return DistroManager().runHeadlessCommand( + systemName: 'host', + command: fullCommand, + timeout: timeout, + cancelToken: cancelToken, + onStdout: onOutput, + ); + } + return Process.run( + Platform.isWindows ? 'cmd' : '/bin/sh', + Platform.isWindows ? ['/c', fullCommand] : ['-c', fullCommand], + workingDirectory: workspacePath, + ); + } + + /// 默认流式执行器实例(延迟绑定,便于测试替换) + GitStreamRunner get _defaultStreamRunner => _defaultStreamRunnerImpl; + + // ------------------------------ 远端仓库管理 ------------------------------ + + /// 列出所有远端仓库 (`git remote -v`) + Future> getRemotes(String repoPath) async { + final res = await runGitCommand(['remote', '-v'], workingDir: repoPath); + if (!res.success) return []; + return parseRemotes(res.stdout); + } + + /// 解析 `git remote -v` 输出 + @visibleForTesting + List parseRemotes(String stdout) { + // 保持出现顺序:fetch 行确立顺序,push 行补充 pushUrl + final order = []; + final fetchUrls = {}; + final pushUrls = {}; + + for (final line in LineSplitter.split(stdout)) { + final trimmed = line.trim(); + if (trimmed.isEmpty) continue; + // 形如 `origin\thttps://github.com/a/b.git (fetch)` + final match = RegExp(r'^(\S+)\s+(\S+)\s+\((fetch|push)\)$').firstMatch(trimmed); + if (match == null) continue; + final name = match.group(1)!; + final url = match.group(2)!; + final kind = match.group(3)!; + if (!order.contains(name)) order.add(name); + if (kind == 'fetch') { + fetchUrls[name] = url; + } else { + pushUrls[name] = url; + } + } + + final remotes = []; + for (final name in order) { + final fetchUrl = fetchUrls[name] ?? pushUrls[name]; + if (fetchUrl == null) continue; + final pushUrl = pushUrls[name]; + remotes.add(GitRemote( + name: name, + fetchUrl: fetchUrl, + // 仅在与 fetch 地址不同时才保留,避免 UI 重复展示 + pushUrl: (pushUrl != null && pushUrl != fetchUrl) ? pushUrl : null, + )); + } + return remotes; + } + + /// 添加远端仓库 (`git remote add `) + Future addRemote( + String repoPath, + String name, + String url, { + String? pushUrl, + }) async { + final cleanName = name.trim(); + final cleanUrl = url.trim(); + if (cleanName.isEmpty) return GitCommandResult.error('远端名称不能为空'); + if (cleanUrl.isEmpty) return GitCommandResult.error('远端地址不能为空'); + + final res = await runGitCommand( + ['remote', 'add', cleanName, cleanUrl], + workingDir: repoPath, + ); + if (!res.success) return res; + + if (pushUrl != null && pushUrl.trim().isNotEmpty && pushUrl.trim() != cleanUrl) { + return runGitCommand( + ['remote', 'set-url', '--push', cleanName, pushUrl.trim()], + workingDir: repoPath, + ); + } + return res; + } + + /// 移除远端仓库 (`git remote remove `) + Future removeRemote(String repoPath, String name) async { + return runGitCommand(['remote', 'remove', name.trim()], workingDir: repoPath); + } + + /// 重命名远端仓库 (`git remote rename `) + Future renameRemote( + String repoPath, + String oldName, + String newName, + ) async { + final cleanNew = newName.trim(); + if (cleanNew.isEmpty) return GitCommandResult.error('新的远端名称不能为空'); + if (oldName.trim() == cleanNew) { + return GitCommandResult.error('新名称与原名相同'); + } + return runGitCommand( + ['remote', 'rename', oldName.trim(), cleanNew], + workingDir: repoPath, + ); + } + + /// 修改远端地址 (`git remote set-url [--push] `) + Future setRemoteUrl( + String repoPath, + String name, + String url, { + bool push = false, + }) async { + final cleanUrl = url.trim(); + if (cleanUrl.isEmpty) return GitCommandResult.error('远端地址不能为空'); + final args = ['remote', 'set-url']; + if (push) args.add('--push'); + args.addAll([name.trim(), cleanUrl]); + return runGitCommand(args, workingDir: repoPath); + } + + /// 清理远端已删除的追踪分支 (`git remote prune `) + Future pruneRemote(String repoPath, String name) async { + return runGitCommand(['remote', 'prune', name.trim()], workingDir: repoPath); + } + + // ------------------------------ 网络同步操作 ------------------------------ + + /// 抓取远端更新 (`git fetch --progress [--prune] `) + /// + /// 默认开启 `--prune`,与 VS Code / GitHub Desktop 行为一致,避免远端已删除的 + /// 分支长期残留。不传 `--tags`,避免意外拉入大量标签。 + Future fetch( + String repoPath, { + String? rootPath, + String? remote, + bool prune = true, + void Function(GitOperationProgress progress)? onProgress, + HeadlessCancelToken? cancelToken, + Duration timeout = remoteNetworkTimeout, + }) async { + final args = ['fetch', '--progress']; + if (prune) args.add('--prune'); + if (remote != null && remote.trim().isNotEmpty) args.add(remote.trim()); + return runRemoteGitCommand( + repoPath, + args, + rootPath: rootPath, + timeout: timeout, + onProgress: onProgress, + cancelToken: cancelToken, + ); + } + + /// 拉取并变基 (`git pull --progress --rebase `) + /// + /// 采用 rebase 以保持历史线性。调用方需在外层处理未提交改动(提交或贮藏)。 + Future pullRebase( + String repoPath, { + String? rootPath, + String? remote, + String? branch, + bool autostash = false, + void Function(GitOperationProgress progress)? onProgress, + HeadlessCancelToken? cancelToken, + Duration timeout = remoteNetworkTimeout, + }) async { + final args = ['pull', '--progress', '--rebase']; + if (autostash) args.add('--autostash'); + if (remote != null && remote.trim().isNotEmpty) args.add(remote.trim()); + if (branch != null && branch.trim().isNotEmpty) args.add(branch.trim()); + return runRemoteGitCommand( + repoPath, + args, + rootPath: rootPath, + timeout: timeout, + onProgress: onProgress, + cancelToken: cancelToken, + ); + } + + /// 推送到远端 (`git push --progress [--set-upstream] [--force-with-lease] ...`) + /// + /// 强制推送一律使用 `--force-with-lease`:当远端已被他人更新时会被拒绝, + /// 而不是静默覆盖别人的提交。 + Future push( + String repoPath, { + String? rootPath, + String? remote, + String? branch, + bool setUpstream = false, + bool forceWithLease = false, + void Function(GitOperationProgress progress)? onProgress, + HeadlessCancelToken? cancelToken, + Duration timeout = remoteNetworkTimeout, + }) async { + final args = ['push', '--progress']; + if (forceWithLease) args.add('--force-with-lease'); + if (setUpstream) args.add('--set-upstream'); + if (remote != null && remote.trim().isNotEmpty) args.add(remote.trim()); + if (branch != null && branch.trim().isNotEmpty) args.add(branch.trim()); + return runRemoteGitCommand( + repoPath, + args, + rootPath: rootPath, + timeout: timeout, + onProgress: onProgress, + cancelToken: cancelToken, + ); + } + + /// 放弃进行中的 rebase (`git rebase --abort`) + /// + /// 冲突后必须给用户一条明确的退出路径,否则仓库会卡在 rebase 中间状态。 + Future abortRebase(String repoPath) async { + return runGitCommand(['rebase', '--abort'], workingDir: repoPath); + } + + /// 是否正处于 rebase 中间状态(存在 .git/rebase-merge 或 .git/rebase-apply) + bool isRebaseInProgress(String repoPath) { + try { + return Directory(p.join(repoPath, '.git', 'rebase-merge')).existsSync() || + Directory(p.join(repoPath, '.git', 'rebase-apply')).existsSync(); + } catch (_) { + return false; + } + } + + /// 验证远端连通性与认证是否可用 (`git ls-remote HEAD`) + /// 比"推送失败后再猜错误码"友好得多,用于账号管理页的自检按钮。 + Future checkRemoteAuth( + String repoPath, + String url, { + String? rootPath, + HeadlessCancelToken? cancelToken, + Duration timeout = const Duration(seconds: 45), + }) async { + final cleanUrl = url.trim(); + if (cleanUrl.isEmpty) { + return GitRemoteCommandResult.error('远端地址不能为空'); + } + return runRemoteGitCommand( + repoPath, + ['ls-remote', '--exit-code', cleanUrl, 'HEAD'], + rootPath: rootPath, + timeout: timeout, + cancelToken: cancelToken, + ); + } + + // ---------------------------- 远程目标解析 ---------------------------- + + /// 读取某个配置键的值;未设置时返回 null + /// + /// `git config ` 在键不存在时以非 0 退出,这是正常情况而非错误。 + Future getConfigValue(String repoPath, String key) async { + final res = await runGitCommand(['config', key], workingDir: repoPath); + if (!res.success) return null; + final value = res.stdout.trim(); + return value.isEmpty ? null : value; + } + + /// 读取某分支的推送远程 (`branch..pushRemote`) + Future getBranchPushRemote(String repoPath, String branch) async { + if (branch.trim().isEmpty) return null; + return getConfigValue(repoPath, 'branch.${branch.trim()}.pushRemote'); + } + + /// 读取全局推送默认远程 (`remote.pushDefault`) + Future getRemotePushDefault(String repoPath) async { + return getConfigValue(repoPath, 'remote.pushDefault'); + } + + /// 读取某分支的抓取/上游远程 (`branch..remote`) + Future getBranchRemote(String repoPath, String branch) async { + if (branch.trim().isEmpty) return null; + return getConfigValue(repoPath, 'branch.${branch.trim()}.remote'); + } + + // ---------------------------- 远端分支 ---------------------------- + + /// 列出所有远端追踪分支 (`git branch -r`) + /// + /// `git fetch` 之后如果界面上看不到远端分支,用户会以为"抓取没生效"。 + /// 这里连同「已被哪个本地分支检出」一起解析出来,供分支选择器分区展示 + /// 并支持基于远端分支创建本地分支。 + /// + /// 使用固定分隔符 `|` 而非制表符:制表符与 `%(HEAD)` 的前导空格混在一起后 + /// 无法可靠切列(`' *\tname'` 里到底有几个前导空格由 git 决定)。 + Future> getRemoteBranches(String repoPath) async { + final res = await runGitCommand( + ['branch', '-r', '--format=%(HEAD)|%(refname:short)'], + workingDir: repoPath, + ); + if (!res.success) return []; + return parseRemoteBranches(res.stdout); + } + + /// 解析 `git branch -r --format=%(HEAD)|%(refname:short)` 输出 + @visibleForTesting + List parseRemoteBranches(String stdout) { + final branches = []; + for (final rawLine in LineSplitter.split(stdout)) { + final line = rawLine.trim(); + if (line.isEmpty) continue; + + // 第一段是 HEAD 标记('*' 表示已被某个本地分支检出) + final marker = line.split('|').first.trim(); + final name = _lastRefSegment(line); + if (name.isEmpty) continue; + // 跳过 `origin/HEAD -> origin/main` 这类符号引用行 + if (name.endsWith('/HEAD')) continue; + // `refs/remotes/origin/main` 这种完整引用先去掉 refs/remotes/ 前缀 + final cleaned = name.startsWith('refs/remotes/') + ? name.substring('refs/remotes/'.length) + : name; + + final slash = cleaned.indexOf('/'); + if (slash <= 0) continue; + + branches.add(GitRemoteBranch( + name: cleaned, + remoteName: cleaned.substring(0, slash), + branchName: cleaned.substring(slash + 1), + isCheckedOut: marker.startsWith('*'), + )); + } + return branches; + } + + /// 取 `%(HEAD)|%(refname:short)` 一行中最靠右的一段作为引用名 + /// + /// 兼容 `(HEAD detached at x)`、`origin/HEAD -> origin/main` 这类 + /// 左侧带额外说明的输出。 + String _lastRefSegment(String line) { + final segments = line + .split(RegExp(r'[|\t]')) + .map((s) => s.trim()) + .where((s) => s.isNotEmpty) + .toList(); + if (segments.isEmpty) return ''; + return segments.last; + } + + /// 基于远端分支创建并检出一个同名本地分支 + /// + /// 若同名本地分支已存在则直接切换过去(`git checkout ` 会自动 + /// 建立追踪关系),否则用 `git checkout -b /` + /// 以远端分支为起点创建。 + Future checkoutRemoteBranch( + String repoPath, + String remoteName, + String branchName, { + bool forceCreate = false, + }) async { + final local = branchName.trim(); + if (local.isEmpty) return GitCommandResult.error('分支名称不能为空'); + + if (!forceCreate) { + final existing = await getLocalBranches(repoPath); + if (existing.contains(local)) { + return runGitCommand(['checkout', local], workingDir: repoPath); + } + } + return runGitCommand( + ['checkout', '-b', local, '--track', '${remoteName.trim()}/$local'], + workingDir: repoPath, + ); + } + + // ---------------------------- 仓库自检 ---------------------------- + + /// 仓库完整性自检 (`git fsck --no-progress`) + /// + /// 目的:`.git/objects` 中的对象在 PRoot 容器重建等场景下可能丢失, + /// 若不做检查,用户只会在某次提交时撞上 "invalid object ... building trees", + /// 且完全不知道原因。这里把问题提前暴露出来。 + /// + /// 只读,不修改任何内容(不自动 `fsck --lost-found`,避免留下 .git/lost-found)。 + Future fsck( + String repoPath, { + Duration timeout = const Duration(minutes: 2), + HeadlessCancelToken? cancelToken, + }) async { + final res = await runGitCommand( + ['fsck', '--no-progress'], + workingDir: repoPath, + timeout: timeout, + ); + // git fsck 发现问题时以非 0 退出,但输出仍是有效报告,因此照常解析 + return parseFsckReport(res.stdout, res.stderr, exitCode: res.exitCode); + } + + /// 解析 `git fsck` 输出 + @visibleForTesting + GitFsckReport parseFsckReport( + String stdout, + String stderr, { + required int exitCode, + }) { + final missing = []; + final corrupt = []; + final dangling = []; + + /// 例行输出不是问题,绝不能被归类为损坏 —— 否则干净的仓库会被告知"已损坏" + bool isNoise(String t) { + if (t.startsWith('Checking ') || t.startsWith('checking ')) return true; + if (t.startsWith('notice:')) return true; + if (t.startsWith('fatal:')) return true; + // 进度行 `Checking object directories: 100% (256/256), done.` + if (t.contains('%') && t.endsWith('done.')) return true; + return false; + } + + void classify(String line) { + final t = line.trim(); + if (t.isEmpty) return; + if (isNoise(t)) return; + + // 只有明确的 missing/broken/无法读取才算对象库受损 + if (t.startsWith('missing ') || + t.startsWith('broken link') || + t.startsWith('unable to read') || + t.startsWith('invalid ')) { + missing.add(t); + return; + } + if (t.startsWith('error:')) { + corrupt.add(t); + return; + } + if (t.startsWith('dangling ') || t.startsWith('unreachable ')) { + dangling.add(t); + return; + } + // `broken link from ...` 的续行形如 ` to blob `, + // 属于同一个问题的组成部分,归入 missing 而不是"无法归类" + if (t.startsWith('to ')) { + missing.add(t); + return; + } + corrupt.add(t); + } + + for (final line in LineSplitter.split(stdout)) { + classify(line); + } + for (final line in LineSplitter.split(stderr)) { + classify(line); + } + + return GitFsckReport( + // 有 missing/corrupt 即视为对象库受损;dangling 只是提示,不影响使用 + isHealthy: missing.isEmpty && corrupt.isEmpty && exitCode == 0, + hasObjectLoss: missing.isNotEmpty || corrupt.isNotEmpty, + missing: List.unmodifiable(missing), + corrupt: List.unmodifiable(corrupt), + dangling: List.unmodifiable(dangling), + exitCode: exitCode, + ); + } + + // ---------------------------- 克隆 ---------------------------- + + /// 克隆远端仓库到工作区内的某个子目录 + /// + /// 实现说明:容器里宿主工程目录被挂载为 `/workspace`,且不支持额外挂载点, + /// 因此把克隆父目录(项目根)作为 workspacePath,在容器内克隆到 + /// `/workspace/<目录名>` —— 其写回宿主的正是期望位置。 + Future clone( + String parentDir, + String url, + String targetDirName, { + String? rootPath, + String? branch, + int? depth, + void Function(GitOperationProgress progress)? onProgress, + HeadlessCancelToken? cancelToken, + Duration timeout = const Duration(minutes: 30), + }) async { + final cleanUrl = url.trim(); + final cleanName = targetDirName.trim(); + if (cleanUrl.isEmpty) { + return GitRemoteCommandResult.error('仓库地址不能为空'); + } + if (cleanName.isEmpty) { + return GitRemoteCommandResult.error('目标目录名不能为空'); + } + + final args = ['clone', '--progress']; + if (depth != null && depth > 0) args.addAll(['--depth', '$depth']); + if (branch != null && branch.trim().isNotEmpty) { + args.addAll(['--branch', branch.trim()]); + } + args.addAll([cleanUrl, cleanName]); + + return runRemoteGitCommand( + parentDir, + args, + rootPath: rootPath, + timeout: timeout, + onProgress: onProgress, + cancelToken: cancelToken, + ); + } + + // ---------------------------- 上游追踪与领先/落后 ---------------------------- + + /// 读取当前分支的上游追踪状态 (`git status -sb --porcelain=v2 --branch`) + /// + /// 一次进程调用同时拿到分支名、上游、ahead/behind,避免为领先/落后单独开进程。 + Future getBranchTracking(String repoPath) async { + final res = await runGitCommand( + ['status', '-sb', '--porcelain=v2', '--branch'], + workingDir: repoPath, + ); + if (!res.success) { + final branch = await getCurrentBranch(repoPath); + return GitBranchTracking.noUpstream(branch); + } + return parseBranchTracking(res.stdout, fallbackBranch: null); + } + + /// 解析 `git status --porcelain=v2 --branch` 输出中的追踪信息 + /// + /// 兼容两种格式: + /// - porcelain v2: `# branch.head main` / `# branch.upstream origin/main` / `# branch.ab +1 -2` + /// - porcelain v1 (`-sb` 简写): `## main...origin/main [ahead 1, behind 2]` / `## main...origin/main [gone]` + @visibleForTesting + GitBranchTracking parseBranchTracking(String stdout, {String? fallbackBranch}) { + String? branch = fallbackBranch; + String? upstream; + int ahead = 0; + int behind = 0; + bool gone = false; + + for (final line in LineSplitter.split(stdout)) { + final t = line.trim(); + if (t.isEmpty) continue; + + if (t.startsWith('# branch.head ')) { + final value = t.substring('# branch.head '.length).trim(); + // detached HEAD 会返回 (detached) + if (value.isNotEmpty && value != '(detached)') branch = value; + continue; + } + if (t.startsWith('# branch.upstream ')) { + final value = t.substring('# branch.upstream '.length).trim(); + if (value.isNotEmpty) upstream = value; + continue; + } + if (t.startsWith('# branch.ab ')) { + final m = RegExp(r'\+(\d+)\s+-(\d+)').firstMatch(t); + if (m != null) { + ahead = int.tryParse(m.group(1)!) ?? 0; + behind = int.tryParse(m.group(2)!) ?? 0; + } + continue; + } + + // 兼容 porcelain v1 的 `## ...` 行 + if (t.startsWith('## ')) { + final body = t.substring(3).trim(); + // 去掉 [ahead 1, behind 2] / [gone] 尾巴 + final bracketIdx = body.indexOf(' ['); + final namePart = bracketIdx >= 0 ? body.substring(0, bracketIdx) : body; + final bracketPart = bracketIdx >= 0 ? body.substring(bracketIdx + 1) : ''; + + if (namePart.contains('...')) { + final parts = namePart.split('...'); + branch ??= parts[0].trim(); + final up = parts.length > 1 ? parts[1].trim() : ''; + if (up.isNotEmpty) upstream = up; + } else { + branch ??= namePart.trim(); + } + + if (bracketPart.contains('gone')) { + gone = true; + } + final m = RegExp(r'ahead (\d+)').firstMatch(bracketPart); + if (m != null) ahead = int.tryParse(m.group(1)!) ?? 0; + final mb = RegExp(r'behind (\d+)').firstMatch(bracketPart); + if (mb != null) behind = int.tryParse(mb.group(1)!) ?? 0; + continue; + } + } + + return GitBranchTracking( + branch: branch ?? 'main', + upstream: upstream, + ahead: ahead, + behind: behind, + isGone: gone, + ); + } } diff --git a/lib/utils/app_theme.dart b/lib/utils/app_theme.dart index 85e12b2..b7343fc 100644 --- a/lib/utils/app_theme.dart +++ b/lib/utils/app_theme.dart @@ -28,5 +28,10 @@ ThemeData buildAppTheme({ ), fontFamily: fontFamily, fontFamilyFallback: fontFamilyFallback, + // 窄屏(320~360dp)下给对话框留出边距,避免内容顶满屏幕两侧造成溢出。 + // 这里刻意用固定值而非按屏宽判断:ThemeData 是纯函数,便于单测且无副作用。 + dialogTheme: const DialogThemeData( + insetPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 24), + ), ); } diff --git a/lib/utils/git_error_mapper.dart b/lib/utils/git_error_mapper.dart new file mode 100644 index 0000000..5c3811d --- /dev/null +++ b/lib/utils/git_error_mapper.dart @@ -0,0 +1,512 @@ +import '../l10n/app_localizations.dart'; + +/// Git 云端操作错误分类 +/// +/// 用于把底层 git 的英文 stderr 归类为可操作的错误类型,并驱动 +/// 「一键修复」(如 push 被拒 → 先 Pull)与「去修账号」的按钮显隐。 +/// +/// 本类**不产生任何面向用户的文案**:所有 message / suggestion 均由 UI 层 +/// 通过 [AppLocalizations] 按 [kind] 取词,从而保持与项目其余部分一致的 +/// 中英双语能力(见 [GitErrorMapper.describe])。 +enum GitOperationErrorKind { + /// 非 Git 错误(tarball/success 等) + none, + + /// 令牌无效或已过期(HTTP 401) + authFailed, + + /// 账号对该仓库没有写权限(HTTP 403,典型为推送别人的上游仓库) + writePermissionDenied, + + /// 目标仓库不存在,或当前账号无权访问(HTTP 404) + repositoryNotFound, + + /// 需要代理认证(HTTP 407) + proxyAuthRequired, + + /// 请求被服务器拒绝,通常是推送内容或引用不合法(HTTP 422) + requestRejected, + + /// 触发平台速率限制(HTTP 429) + rateLimited, + + /// 其他被服务端拒绝的 HTTP 状态码 + httpError, + + /// 使用账号密码而非 PAT 访问 GitHub 等平台 + passwordAuthDisabled, + + /// 域名无法解析 / 网络不可达 + networkUnreachable, + + /// SSH 公钥未被平台接受 + sshPublicKeyDenied, + + /// SSH 私钥文件权限或缺失 + sshKeyUnusable, + + /// 首次连接未知主机,主机指纹未确认 + hostKeyUnverified, + + /// 推送被拒(远端有新提交,non-fast-forward) + nonFastForward, + + /// force-with-lease 校验失败(远端已被他人更新) + staleForcePush, + + /// rebase/merge 冲突 + conflictDetected, + + /// 本地有未提交改动,阻止了操作 + localChangesWouldBeOverwritten, + + /// 未设置上游追踪分支 + noUpstreamConfigured, + + /// 无法获取本地/远端引用锁(.git 被占用) + refLockFailed, + + /// 磁盘空间不足 + outOfSpace, + + /// 命令超时 + timeout, + + /// 操作未完成,且输出里没有任何真实错误信息 + operationIncomplete, + + /// 其他未归类错误 + unknown, +} + +/// 错误可供用户执行的修复动作 +enum GitErrorFixAction { + /// 先拉取(rebase)再推送 + pullThenPush, + + /// 重新抓取远端状态后重试 + fetchAndRetry, + + /// 放弃本次变基 + abortRebase, + + /// 前往 Git 账号管理 + openAccountManagement, + + /// 提示用户先 Fork(在提示文案中说明,无需按钮动作) + none, +} + +/// 单条 Git 错误的**结构化**描述(不含任何本地化文案) +class GitErrorInfo { + final GitOperationErrorKind kind; + + /// 兜底情况下从原始输出中提取的一条真实错误行(英文原文,直接展示) + final String? rawDetail; + + /// 建议用户执行的修复动作(由 UI 渲染成按钮) + final GitErrorFixAction fixAction; + + const GitErrorInfo({ + required this.kind, + this.rawDetail, + this.fixAction = GitErrorFixAction.none, + }); + + /// 是否应提供「去修账号」入口 + bool get needsAccountFix => + fixAction == GitErrorFixAction.openAccountManagement; + + /// 是否可通过「先 Pull 再 Push」自动修复 + bool get canPullThenPush => fixAction == GitErrorFixAction.pullThenPush; + + /// 是否可通过重新 fetch 后重试修复 + bool get canRefreshThenRetry => fixAction == GitErrorFixAction.fetchAndRetry; + + /// 该错误是否值得给出修复动作按钮 + bool get hasFixAction => fixAction != GitErrorFixAction.none; + + @override + String toString() => 'GitErrorInfo($kind, fix=${fixAction.name})'; +} + +/// 将 git stderr/stdout 归类为可操作的错误类型 +class GitErrorMapper { + GitErrorMapper._(); + + /// 需要检查冲突的关键字(统一小写,与转小写后的输出比对) + static const List conflictMarkers = [ + 'conflict', + 'automatic merge failed', + 'could not apply', + 'failed to merge', + 'fix conflicts', + 'needs merge', + ]; + + /// 解析命令输出,返回最贴合的错误分类 + /// + /// [stderr] 优先;[stdout] 在 stderr 为空时兜底(git 部分提示走 stdout)。 + /// 返回结果不含本地化文案,由 UI 层按 [GitErrorInfo.kind] 取词。 + static GitErrorInfo describe(String stderr, {String stdout = ''}) { + final raw = stderr.trim().isNotEmpty ? stderr : stdout; + final text = raw.toLowerCase(); + + if (text.trim().isEmpty) { + return const GitErrorInfo(kind: GitOperationErrorKind.operationIncomplete); + } + + // ---- 1. 强推租约失败(必须先于通用 non-fast-forward 判断)---- + if (text.contains('stale info') || + (text.contains('force-with-lease') && text.contains('rejected'))) { + return const GitErrorInfo( + kind: GitOperationErrorKind.staleForcePush, + fixAction: GitErrorFixAction.fetchAndRetry, + ); + } + + // ---- 2. 认证与权限相关(按 HTTP 状态码细分,避免归因错误)---- + + // 2a. 平台已禁用密码认证 + // 典型文案:`remote: Support for password authentication was removed on August 13, 2021.` + if (text.contains('support for password authentication was removed') || + text.contains('password authentication was removed') || + text.contains('password authentication is not')) { + return const GitErrorInfo( + kind: GitOperationErrorKind.passwordAuthDisabled, + fixAction: GitErrorFixAction.openAccountManagement, + ); + } + + // 2b. HTTP 401:凭证本身无效 + if (text.contains('401') || + text.contains('authentication failed') || + text.contains('invalid username or password') || + text.contains('could not read username') || + text.contains('permission denied, please try again') || + (text.contains('token') && text.contains('expired'))) { + return const GitErrorInfo( + kind: GitOperationErrorKind.authFailed, + fixAction: GitErrorFixAction.openAccountManagement, + ); + } + + // 2c. HTTP 403 / 明确的无写权限拒绝 + // 最常见场景:origin 直接指向别人的上游仓库(如 ggml-org/llama.cpp)。 + // 读取公开仓库不需要认证,因此拦截发生在推送时——此时令牌通常是好的。 + if (text.contains('403') || + (text.contains('permission to') && text.contains('denied')) || + text.contains('write access') || + text.contains('you do not have permission') || + text.contains('protected branch')) { + return const GitErrorInfo( + kind: GitOperationErrorKind.writePermissionDenied, + fixAction: GitErrorFixAction.openAccountManagement, + ); + } + + // 2d. HTTP 407:代理需要认证 + if (text.contains('407') || text.contains('proxy authentication required')) { + return const GitErrorInfo(kind: GitOperationErrorKind.proxyAuthRequired); + } + + // 2e. HTTP 429:速率限制 + if (text.contains('429') || text.contains('rate limit')) { + return const GitErrorInfo(kind: GitOperationErrorKind.rateLimited); + } + + // 2f. HTTP 422:推送内容被服务器拒绝 + if (text.contains('422')) { + return const GitErrorInfo(kind: GitOperationErrorKind.requestRejected); + } + + // 2h. 仓库不存在 / 无权访问(HTTP 404 或 GitHub 文案) + if (text.contains('repository not found') || + text.contains('does not appear to be a git repository') || + text.contains('404')) { + return const GitErrorInfo( + kind: GitOperationErrorKind.repositoryNotFound, + fixAction: GitErrorFixAction.openAccountManagement, + ); + } + + // 2i. 其他 HTTP 状态码(兜底,必须放在所有具体状态码判断之后) + // 保留具体码值,不做统一归并,便于按状态码精确排查。 + final httpMatch = RegExp(r'returned error:\s*(\d{3})').firstMatch(text); + if (httpMatch != null) { + return GitErrorInfo( + kind: GitOperationErrorKind.httpError, + rawDetail: httpMatch.group(1), + ); + } + + // ---- 3. SSH 主机指纹未确认 ---- + if (text.contains('host key verification failed') || + text.contains('remote host identification has changed')) { + return const GitErrorInfo(kind: GitOperationErrorKind.hostKeyUnverified); + } + + // ---- 4. SSH 密钥类 ---- + if (text.contains('permission denied (publickey)') || + text.contains('no supported authentication methods')) { + return const GitErrorInfo( + kind: GitOperationErrorKind.sshPublicKeyDenied, + fixAction: GitErrorFixAction.openAccountManagement, + ); + } + if (text.contains('bad permissions') || + text.contains('unprotected private key file') || + text.contains('load key') || + text.contains('error in libcrypto')) { + return const GitErrorInfo( + kind: GitOperationErrorKind.sshKeyUnusable, + fixAction: GitErrorFixAction.openAccountManagement, + ); + } + + // ---- 5. 网络类 ---- + if (text.contains('could not resolve host') || + text.contains('name or service not known') || + text.contains('network is unreachable') || + text.contains('connection timed out') || + text.contains('connection refused') || + text.contains('failed to connect') || + text.contains('could not resolve proxy') || + text.contains('operation timed out') || + text.contains('ssl certificate problem') || + text.contains('gnutls_handshake')) { + return const GitErrorInfo(kind: GitOperationErrorKind.networkUnreachable); + } + + // ---- 6. 冲突(rebase/merge 中途)---- + // `could not apply` 是 rebase 冲突的标志性输出。 + if (conflictMarkers.any(text.contains) || + text.contains('merge conflict') || + text.contains('needs merge')) { + return const GitErrorInfo( + kind: GitOperationErrorKind.conflictDetected, + fixAction: GitErrorFixAction.abortRebase, + ); + } + + // ---- 7. 推送被拒(non-fast-forward)---- + if (text.contains('non-fast-forward') || + text.contains('failed to push some refs') || + text.contains('updates were rejected') || + text.contains('fetch first') || + text.contains('tip of your current branch is behind')) { + return const GitErrorInfo( + kind: GitOperationErrorKind.nonFastForward, + fixAction: GitErrorFixAction.pullThenPush, + ); + } + + // ---- 8. 未设置上游 ---- + if (text.contains('has no upstream branch') || + text.contains('no upstream configured') || + text.contains('set-upstream')) { + return const GitErrorInfo( + kind: GitOperationErrorKind.noUpstreamConfigured, + ); + } + + // ---- 9. 本地改动会被覆盖 ---- + if (text.contains('would be overwritten') || + text.contains('your local changes') || + text.contains('commit your changes or stash them') || + text.contains('cannot pull with rebase')) { + return const GitErrorInfo( + kind: GitOperationErrorKind.localChangesWouldBeOverwritten, + ); + } + + // ---- 10. 引用锁 ---- + if ((text.contains('unable to create') && text.contains('.lock')) || + text.contains('index.lock') || + text.contains('another git process')) { + return const GitErrorInfo(kind: GitOperationErrorKind.refLockFailed); + } + + // ---- 11. 磁盘空间 ---- + if (text.contains('no space left on device') || text.contains('disk full')) { + return const GitErrorInfo(kind: GitOperationErrorKind.outOfSpace); + } + + // ---- 12. 超时 ---- + if (text.contains('超时') || + text.contains('timed out') || + text.contains('timeout')) { + return const GitErrorInfo(kind: GitOperationErrorKind.timeout); + } + + // ---- 兜底:输出里没有任何可识别的错误 ---- + // 典型情况:fetch/push 只留下了 "Enumerating objects: N, done." 这类进度行, + // 说明命令是被超时或连接中断打断的,而不是 git 主动报错。 + // 绝不能把进度行当作错误原因展示给用户——那会把排查方向彻底带偏。 + final meaningful = firstMeaningfulLine(raw); + if (meaningful == null) { + return const GitErrorInfo(kind: GitOperationErrorKind.operationIncomplete); + } + + return GitErrorInfo( + kind: GitOperationErrorKind.unknown, + rawDetail: meaningful, + ); + } + + /// 便捷判断:命令输出是否代表冲突 + static bool isConflict(String stderr, {String stdout = ''}) { + final text = '${stderr.toLowerCase()}\n${stdout.toLowerCase()}'; + return conflictMarkers.any(text.contains); + } + + /// git 进度输出的阶段名前缀(白名单) + /// + /// 必须用白名单:如果把 `^[A-Za-z]+:\s` 当作通用模式,`fatal:` / `error:` + /// 也会被误判成进度行,从而把真正的错误信息丢掉。 + static const List _progressPhases = [ + 'enumerating objects', + 'counting objects', + 'compressing objects', + 'receiving objects', + 'resolving deltas', + 'writing objects', + 'updating files', + ]; + + /// 进度类行(不含真正的错误信息),例如: + /// `remote: Enumerating objects: 2233, done.` + /// `Receiving objects: 45% (450/1000)` + /// `Resolving deltas: 100% (7/7), done.` + static bool _isProgressLine(String line) { + final t = line.trim().toLowerCase(); + if (t.isEmpty) return false; + for (final phase in _progressPhases) { + if (t.startsWith(phase)) return true; + } + return false; + } + + /// 从多行输出中挑出第一条真正的错误信息;若全是进度噪音则返回 null + static String? firstMeaningfulLine(String raw) { + for (final line in raw.split('\n')) { + final t = line.trim(); + if (t.isEmpty) continue; + // 去掉 `remote: ` 前缀后再判断,因为 GitHub 的进度与错误都带这个前缀 + final body = t.startsWith('remote:') ? t.substring('remote:'.length).trim() : t; + if (body.isEmpty) continue; + if (_isProgressLine(body)) continue; + return body.length > 300 ? '${body.substring(0, 300)}…' : body; + } + return null; + } +} + +/// 错误类型 → 本地化文案的映射 +/// +/// 放在 UI 可达的扩展里,使 [GitErrorMapper] 本身保持纯逻辑、无 l10n 依赖。 +extension GitOperationErrorKindL10n on GitOperationErrorKind { + /// 面向用户的简短说明 + String message(AppLocalizations l10n) { + switch (this) { + case GitOperationErrorKind.none: + return l10n.gitErrUnknown; + case GitOperationErrorKind.authFailed: + return l10n.gitErrAuthFailed; + case GitOperationErrorKind.writePermissionDenied: + return l10n.gitErrWritePermissionDenied; + case GitOperationErrorKind.repositoryNotFound: + return l10n.gitErrRepositoryNotFound; + case GitOperationErrorKind.proxyAuthRequired: + return l10n.gitErrProxyAuthRequired; + case GitOperationErrorKind.requestRejected: + return l10n.gitErrRequestRejected; + case GitOperationErrorKind.rateLimited: + return l10n.gitErrRateLimited; + case GitOperationErrorKind.httpError: + return l10n.gitErrHttpError; + case GitOperationErrorKind.passwordAuthDisabled: + return l10n.gitErrPasswordAuthDisabled; + case GitOperationErrorKind.networkUnreachable: + return l10n.gitErrNetworkUnreachable; + case GitOperationErrorKind.sshPublicKeyDenied: + return l10n.gitErrSshPublicKeyDenied; + case GitOperationErrorKind.sshKeyUnusable: + return l10n.gitErrSshKeyUnusable; + case GitOperationErrorKind.hostKeyUnverified: + return l10n.gitErrHostKeyUnverified; + case GitOperationErrorKind.nonFastForward: + return l10n.gitErrNonFastForward; + case GitOperationErrorKind.staleForcePush: + return l10n.gitErrStaleForcePush; + case GitOperationErrorKind.conflictDetected: + return l10n.gitErrConflictDetected; + case GitOperationErrorKind.localChangesWouldBeOverwritten: + return l10n.gitErrLocalChanges; + case GitOperationErrorKind.noUpstreamConfigured: + return l10n.gitErrNoUpstream; + case GitOperationErrorKind.refLockFailed: + return l10n.gitErrRefLockFailed; + case GitOperationErrorKind.outOfSpace: + return l10n.gitErrOutOfSpace; + case GitOperationErrorKind.timeout: + return l10n.gitErrTimeout; + case GitOperationErrorKind.operationIncomplete: + return l10n.gitErrIncomplete; + case GitOperationErrorKind.unknown: + return l10n.gitErrUnknown; + } + } + + /// 建议的下一步操作 + String suggestion(AppLocalizations l10n) { + switch (this) { + case GitOperationErrorKind.none: + return ''; + case GitOperationErrorKind.authFailed: + return l10n.gitErrAuthFailedHint; + case GitOperationErrorKind.writePermissionDenied: + return l10n.gitErrWritePermissionDeniedHint; + case GitOperationErrorKind.repositoryNotFound: + return l10n.gitErrRepositoryNotFoundHint; + case GitOperationErrorKind.proxyAuthRequired: + return l10n.gitErrProxyAuthRequiredHint; + case GitOperationErrorKind.requestRejected: + return l10n.gitErrRequestRejectedHint; + case GitOperationErrorKind.rateLimited: + return l10n.gitErrRateLimitedHint; + case GitOperationErrorKind.httpError: + return l10n.gitErrHttpErrorHint; + case GitOperationErrorKind.passwordAuthDisabled: + return l10n.gitErrPasswordAuthDisabledHint; + case GitOperationErrorKind.networkUnreachable: + return l10n.gitErrNetworkUnreachableHint; + case GitOperationErrorKind.sshPublicKeyDenied: + return l10n.gitErrSshPublicKeyDeniedHint; + case GitOperationErrorKind.sshKeyUnusable: + return l10n.gitErrSshKeyUnusableHint; + case GitOperationErrorKind.hostKeyUnverified: + return l10n.gitErrHostKeyUnverifiedHint; + case GitOperationErrorKind.nonFastForward: + return l10n.gitErrNonFastForwardHint; + case GitOperationErrorKind.staleForcePush: + return l10n.gitErrStaleForcePushHint; + case GitOperationErrorKind.conflictDetected: + return l10n.gitErrConflictDetectedHint; + case GitOperationErrorKind.localChangesWouldBeOverwritten: + return l10n.gitErrLocalChangesHint; + case GitOperationErrorKind.noUpstreamConfigured: + return l10n.gitErrNoUpstreamHint; + case GitOperationErrorKind.refLockFailed: + return l10n.gitErrRefLockFailedHint; + case GitOperationErrorKind.outOfSpace: + return l10n.gitErrOutOfSpaceHint; + case GitOperationErrorKind.timeout: + return l10n.gitErrTimeoutHint; + case GitOperationErrorKind.operationIncomplete: + return l10n.gitErrIncompleteHint; + case GitOperationErrorKind.unknown: + return l10n.gitErrUnknownHint; + } + } +} diff --git a/lib/widgets/git/git_panel_widget.dart b/lib/widgets/git/git_panel_widget.dart index 0eedde8..6299b0b 100644 --- a/lib/widgets/git/git_panel_widget.dart +++ b/lib/widgets/git/git_panel_widget.dart @@ -1,16 +1,22 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:path/path.dart' as p; import 'package:provider/provider.dart'; import '../../l10n/app_localizations.dart'; import '../../models/git_model.dart'; +import '../../models/project_history.dart'; import '../../providers/git_provider.dart'; +import '../../providers/project_provider.dart'; import '../../providers/tab_provider.dart'; import '../../utils/dialog_utils.dart'; import '../../utils/file_icon_utils.dart'; import 'git_diff_page.dart'; import 'git_graph_painter.dart'; +import 'git_remote_management_sheet.dart'; +import 'git_repair_panel.dart'; +import 'git_sync_bar.dart'; import '../../views/git_account_management_view.dart'; /// Git 版本控制侧边栏面板组件 @@ -239,51 +245,11 @@ class _GitPanelWidgetState extends State { const SizedBox(width: 4), - // 顶部操作按钮组 - Row( - mainAxisSize: MainAxisSize.min, - children: [ - // Git 账号管理入口 - SizedBox( - width: 24, - height: 24, - child: IconButton( - icon: const Icon(Icons.manage_accounts_outlined, size: 18), - tooltip: l10n.gitAccountManagement, - padding: EdgeInsets.zero, - constraints: const BoxConstraints(), - onPressed: () { - Navigator.push( - context, - MaterialPageRoute(builder: (_) => const GitAccountManagementView()), - ); - }, - ), - ), - - // 刷新按钮 - if (gitProvider.hasProject && gitProvider.gitInstalled) ...[ - const SizedBox(width: 4), - SizedBox( - width: 24, - height: 24, - child: IconButton( - icon: const Icon(Icons.refresh, size: 18), - tooltip: l10n.gitRefresh, - padding: EdgeInsets.zero, - constraints: const BoxConstraints(), - onPressed: gitProvider.isLoading ? null : () => gitProvider.refresh(), - ), - ), - ], - - // 更多操作 (撤销上次提交、Stash 贮藏等) - if (gitProvider.hasProject && gitProvider.gitInstalled && gitProvider.hasRepository) ...[ - const SizedBox(width: 4), - _buildMoreActionsMenu(context, theme, l10n, gitProvider), - ], - ], - ), + // 顶部操作更多菜单(撤销/Stash/远程管理/自检/克隆/账号等)。 + // 不要求已打开仓库:克隆正是用来把第一个项目拉下来的入口, + // 各菜单项自身会按 hasRepository 决定是否可用。 + if (gitProvider.gitInstalled) + _buildMoreActionsMenu(context, theme, l10n, gitProvider), ], ), @@ -300,6 +266,12 @@ class _GitPanelWidgetState extends State { ], ), ], + + // 第三行:云端同步工具条(抓取 / 拉取 / 推送 / 远程管理) + if (gitProvider.hasRepository && gitProvider.gitInstalled) ...[ + const SizedBox(height: 6), + const GitSyncBar(), + ], ], ), ), @@ -433,6 +405,23 @@ class _GitPanelWidgetState extends State { } } }, + onCheckoutRemoteBranch: (remoteBranch) async { + final res = await gitProvider.checkoutRemoteBranch(remoteBranch); + if (context.mounted) { + if (res.success) { + DialogUtils.showToast( + context, + l10n.gitCheckoutRemoteBranchSuccess( + remoteBranch.remoteName, + remoteBranch.localBranchName, + ), + type: ToastType.success, + ); + } else if (res.stderr.isNotEmpty) { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + }, ); }, ); @@ -559,60 +548,212 @@ class _GitPanelWidgetState extends State { tooltip: l10n.gitMoreActions, padding: EdgeInsets.zero, onSelected: (action) async { - switch (action) { - case 'undo_commit': - _handleUndoLastCommit(context, l10n, gitProvider); - break; - case 'stash': - _handleStash(context, l10n, gitProvider); - break; - case 'stash_pop': - _handleStashPop(context, l10n, gitProvider); - break; - } - }, - itemBuilder: (ctx) => [ - PopupMenuItem( - value: 'undo_commit', - enabled: gitProvider.commits.isNotEmpty, - child: Row( - children: [ - const Icon(Icons.undo, size: 16), - const SizedBox(width: 8), - Text(l10n.gitUndoLastCommit, style: const TextStyle(fontSize: 13)), - ], - ), - ), - PopupMenuItem( - value: 'stash', - enabled: gitProvider.changedFiles.isNotEmpty, - child: Row( - children: [ - const Icon(Icons.archive_outlined, size: 16), - const SizedBox(width: 8), - Text(l10n.gitStashChanges, style: const TextStyle(fontSize: 13)), - ], - ), - ), - PopupMenuItem( - value: 'stash_pop', - enabled: gitProvider.stashCount > 0, - child: Row( - children: [ - const Icon(Icons.unarchive_outlined, size: 16), - const SizedBox(width: 8), - Text( - '${l10n.gitStashPop}${gitProvider.stashCount > 0 ? ' (${gitProvider.stashCount})' : ''}', - style: const TextStyle(fontSize: 13), + switch (action) { + case 'undo_commit': + _handleUndoLastCommit(context, l10n, gitProvider); + break; + case 'stash': + _handleStash(context, l10n, gitProvider); + break; + case 'stash_pop': + _handleStashPop(context, l10n, gitProvider); + break; + case 'refresh': + gitProvider.refresh(); + break; + case 'account_management': + Navigator.push( + context, + MaterialPageRoute(builder: (_) => const GitAccountManagementView()), + ); + break; + case 'remote_management': + GitRemoteManagementSheet.show(context); + break; + case 'repair_check': + GitRepairPanel.show(context); + break; + case 'clone': + _handleClone(context, l10n); + break; + case 'force_push': + _handleForcePush(context, l10n, gitProvider); + break; + } + }, + itemBuilder: (ctx) => [ + if (gitProvider.hasRepository) ...[ + PopupMenuItem( + value: 'undo_commit', + enabled: gitProvider.commits.isNotEmpty, + child: Row( + children: [ + const Icon(Icons.undo, size: 16), + const SizedBox(width: 8), + Text(l10n.gitUndoLastCommit, style: const TextStyle(fontSize: 13)), + ], ), - ], + ), + PopupMenuItem( + value: 'stash', + enabled: gitProvider.changedFiles.isNotEmpty, + child: Row( + children: [ + const Icon(Icons.archive_outlined, size: 16), + const SizedBox(width: 8), + Text(l10n.gitStashChanges, style: const TextStyle(fontSize: 13)), + ], + ), + ), + PopupMenuItem( + value: 'stash_pop', + enabled: gitProvider.stashCount > 0, + child: Row( + children: [ + const Icon(Icons.unarchive_outlined, size: 16), + const SizedBox(width: 8), + Text( + '${l10n.gitStashPop}${gitProvider.stashCount > 0 ? ' (${gitProvider.stashCount})' : ''}', + style: const TextStyle(fontSize: 13), + ), + ], + ), + ), + const PopupMenuDivider(), + ], + PopupMenuItem( + value: 'remote_management', + enabled: gitProvider.hasRepository && !gitProvider.isRemoteBusy, + child: Row( + children: [ + const Icon(Icons.dns_outlined, size: 16), + const SizedBox(width: 8), + Text(l10n.gitRemoteManagement, style: const TextStyle(fontSize: 13)), + ], + ), ), - ), - ], - ), + PopupMenuItem( + value: 'repair_check', + enabled: gitProvider.hasRepository && !gitProvider.isFsckRunning, + child: Row( + children: [ + const Icon(Icons.health_and_safety_outlined, size: 16), + const SizedBox(width: 8), + Text(l10n.gitRepairCheck, style: const TextStyle(fontSize: 13)), + ], + ), + ), + // 克隆不依赖当前仓库:没有打开仓库时也能用来拉一个新项目下来 + PopupMenuItem( + value: 'clone', + enabled: !gitProvider.isCloning, + child: Row( + children: [ + const Icon(Icons.download_outlined, size: 16), + const SizedBox(width: 8), + Text(l10n.gitClone, style: const TextStyle(fontSize: 13)), + ], + ), + ), + if (gitProvider.hasRepository) ...[ + const PopupMenuDivider(), + PopupMenuItem( + value: 'force_push', + enabled: gitProvider.currentBranch != null && !gitProvider.isRemoteBusy, + child: Row( + children: [ + Icon(Icons.warning_amber_rounded, size: 16, color: theme.colorScheme.error), + const SizedBox(width: 8), + Text( + l10n.gitForcePush, + style: TextStyle(fontSize: 13, color: theme.colorScheme.error), + ), + ], + ), + ), + ], + const PopupMenuDivider(), + PopupMenuItem( + value: 'refresh', + enabled: !gitProvider.isLoading, + child: Row( + children: [ + const Icon(Icons.refresh, size: 16), + const SizedBox(width: 8), + Text(l10n.gitRefresh, style: const TextStyle(fontSize: 13)), + ], + ), + ), + PopupMenuItem( + value: 'account_management', + child: Row( + children: [ + const Icon(Icons.manage_accounts_outlined, size: 16), + const SizedBox(width: 8), + Text(l10n.gitAccountManagement, style: const TextStyle(fontSize: 13)), + ], + ), + ), + ], + ), ); } + /// 强制推送:必须经过显式二次确认,且底层一律使用 --force-with-lease + /// + /// 之所以不复用普通确认弹窗,是因为强推会改写远端历史;这里把远端分支名 + /// 直接写进弹窗正文,让用户明确知道自己在覆盖哪一条分支。 + Future _handleForcePush( + BuildContext context, + AppLocalizations l10n, + GitProvider gitProvider, + ) async { + final branch = gitProvider.currentBranch; + if (branch == null || branch.isEmpty) return; + + if (!gitProvider.hasRemote) { + DialogUtils.showToast(context, l10n.gitNoRemoteConfigured, type: ToastType.warning); + return; + } + + final confirmed = await DialogUtils.showDestructiveConfirmDialog( + context, + title: l10n.gitForcePushConfirm, + message: '${l10n.gitForcePushWarning}\n\n${l10n.gitForcePushConfirmDesc(branch)}', + confirmText: l10n.gitForcePush, + icon: Icons.warning_amber_rounded, + ); + if (!confirmed || !context.mounted) return; + + final res = await gitProvider.push(forceWithLease: true); + if (!context.mounted) return; + if (res.cancelled) { + DialogUtils.showToast(context, l10n.gitRemoteOperationCancelled, type: ToastType.info); + return; + } + if (res.success) { + DialogUtils.showToast(context, l10n.gitPushSuccess, type: ToastType.success); + } + // 失败时错误面板已给出结构化原因与修复入口,此处不再重复弹 toast + } + + /// 克隆远端仓库到项目目录,成功后直接切过去打开 + Future _handleClone(BuildContext context, AppLocalizations l10n) async { + final projectProvider = context.read(); + final targetPath = await GitCloneDialog.show(context); + if (targetPath == null) return; + + await projectProvider.switchProject( + ProjectHistory(rootPath: targetPath, lastOpenedFilePath: null), + ); + if (!context.mounted) return; + DialogUtils.showToast( + context, + l10n.gitCloneSuccess(p.basename(targetPath)), + type: ToastType.success, + ); + } + /// 创建新分支对话框 Future _showCreateBranchDialog( BuildContext context, @@ -2626,6 +2767,9 @@ class _BranchOrTagSelectorMenuDialog extends StatefulWidget { final ValueChanged onSwitchBranch; final ValueChanged onSwitchTag; + /// 基于远端分支检出本地分支 + final ValueChanged onCheckoutRemoteBranch; + const _BranchOrTagSelectorMenuDialog({ required this.offset, required this.size, @@ -2637,6 +2781,7 @@ class _BranchOrTagSelectorMenuDialog extends StatefulWidget { required this.onModeChanged, required this.onSwitchBranch, required this.onSwitchTag, + required this.onCheckoutRemoteBranch, }); @override @@ -2676,6 +2821,13 @@ class _BranchOrTagSelectorMenuDialogState extends State<_BranchOrTagSelectorMenu final filteredTags = query.isEmpty ? tags : tags.where((t) => t.toLowerCase().contains(query)).toList(); + // 远端分支:fetch 之后必须可见,否则用户会以为"抓取没生效" + final remoteBranches = widget.gitProvider.remoteBranches; + final filteredRemote = query.isEmpty + ? remoteBranches + : remoteBranches + .where((b) => b.name.toLowerCase().contains(query)) + .toList(); return Stack( children: [ @@ -2834,7 +2986,7 @@ class _BranchOrTagSelectorMenuDialogState extends State<_BranchOrTagSelectorMenu // 下方列表(按需虚拟化构建) _showTags ? _buildTagList(context, colorScheme, filteredTags) - : _buildBranchList(context, colorScheme, filteredBranches), + : _buildBranchSection(context, colorScheme, filteredBranches, filteredRemote), ], ), ), @@ -2845,7 +2997,158 @@ class _BranchOrTagSelectorMenuDialogState extends State<_BranchOrTagSelectorMenu ); } - Widget _buildBranchList(BuildContext dialogCtx, ColorScheme colorScheme, List branches) { + /// 分支列表 = 本地分支 + 远端分支两个分区 + /// + /// 分区标题只在对应分区非空时出现,避免只有一个分区时多一行噪音。 + Widget _buildBranchSection( + BuildContext dialogCtx, + ColorScheme colorScheme, + List localBranches, + List remoteBranches, + ) { + final showLocalHeader = localBranches.isNotEmpty && remoteBranches.isNotEmpty; + final rows = []; + + if (showLocalHeader) { + rows.add(_buildGroupHeader(colorScheme, widget.l10n.gitLocalBranches)); + } + if (localBranches.isNotEmpty) { + rows.add(_buildBranchList(dialogCtx, colorScheme, localBranches, shrinkWrap: true)); + } else if (remoteBranches.isEmpty) { + rows.add(_buildEmptyHint(colorScheme, widget.l10n.gitNoBranches)); + } + + if (remoteBranches.isNotEmpty) { + rows.add(_buildGroupHeader(colorScheme, widget.l10n.gitRemoteBranches)); + rows.add(_buildRemoteBranchList(dialogCtx, colorScheme, remoteBranches)); + } + + return Flexible(child: SingleChildScrollView(child: Column(children: rows))); + } + + Widget _buildGroupHeader(ColorScheme colorScheme, String title) { + return Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 4), + child: Row( + children: [ + Text( + title, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(width: 6), + Expanded( + child: Divider( + height: 1, + thickness: 0.8, + color: colorScheme.outlineVariant.withValues(alpha: 0.5), + ), + ), + ], + ), + ); + } + + Widget _buildEmptyHint(ColorScheme colorScheme, String text) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + child: Center( + child: Text( + text, + style: TextStyle( + fontSize: 12, + fontStyle: FontStyle.italic, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + ), + ), + ), + ); + } + + /// 远端分支列表:点击即基于它检出本地分支 + Widget _buildRemoteBranchList( + BuildContext dialogCtx, + ColorScheme colorScheme, + List branches, + ) { + const double itemHeight = 40.0; + final double listHeight = (branches.length * itemHeight).clamp(40.0, 240.0); + + return SizedBox( + height: listHeight, + child: ListView.builder( + itemExtent: itemHeight, + itemCount: branches.length, + padding: const EdgeInsets.symmetric(vertical: 2), + itemBuilder: (ctx, index) { + final b = branches[index]; + return InkWell( + key: ValueKey('git_remote_branch_${b.name}'), + onTap: () { + Navigator.of(dialogCtx).pop(); + widget.onCheckoutRemoteBranch(b); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + children: [ + Icon( + Icons.cloud_outlined, + size: 15, + color: b.isCheckedOut + ? colorScheme.primary + : colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + b.name, + style: TextStyle( + fontSize: 12.5, + fontFamily: 'JetBrains Mono', + fontWeight: + b.isCheckedOut ? FontWeight.bold : FontWeight.normal, + color: b.isCheckedOut + ? colorScheme.primary + : colorScheme.onSurface, + ), + overflow: TextOverflow.ellipsis, + ), + Text( + b.isCheckedOut + ? widget.l10n.gitRemoteBranchCheckedOut + : widget.l10n.gitCheckoutRemoteBranch, + style: TextStyle( + fontSize: 10, + color: colorScheme.onSurfaceVariant, + ), + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + ], + ), + ), + ); + }, + ), + ); + } + + Widget _buildBranchList( + BuildContext dialogCtx, + ColorScheme colorScheme, + List branches, { + bool shrinkWrap = false, + }) { if (branches.isEmpty) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), @@ -2870,6 +3173,8 @@ class _BranchOrTagSelectorMenuDialogState extends State<_BranchOrTagSelectorMenu child: ListView.builder( itemExtent: itemHeight, itemCount: branches.length, + shrinkWrap: shrinkWrap, + physics: shrinkWrap ? const NeverScrollableScrollPhysics() : null, padding: const EdgeInsets.symmetric(vertical: 2), itemBuilder: (ctx, index) { final b = branches[index]; diff --git a/lib/widgets/git/git_remote_management_sheet.dart b/lib/widgets/git/git_remote_management_sheet.dart new file mode 100644 index 0000000..0cc46b5 --- /dev/null +++ b/lib/widgets/git/git_remote_management_sheet.dart @@ -0,0 +1,483 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../models/git_model.dart'; +import '../../providers/git_provider.dart'; +import '../../utils/dialog_utils.dart'; +import '../../utils/git_error_mapper.dart'; + +/// 远程仓库管理面板(底部弹出) +/// +/// 支持列出 / 添加 / 编辑地址 / 重命名 / 移除 / 清理失效分支 / 连接自检。 +/// 所有操作都经由 [GitProvider],与同步工具条共用同一套错误处理。 +class GitRemoteManagementSheet extends StatelessWidget { + const GitRemoteManagementSheet({super.key}); + + static Future show(BuildContext context) { + return showModalBottomSheet( + context: context, + isScrollControlled: true, + showDragHandle: true, + builder: (_) => const GitRemoteManagementSheet(), + ); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final provider = context.watch(); + final remotes = provider.remotes; + + return SafeArea( + child: Padding( + padding: EdgeInsets.only( + left: 12, + right: 12, + bottom: 12 + MediaQuery.of(context).viewInsets.bottom, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: Text( + l10n.gitRemoteManagement, + style: Theme.of(context).textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ), + TextButton.icon( + key: const ValueKey('git_remote_add_button'), + onPressed: () => _showAddDialog(context, l10n, provider), + icon: const Icon(Icons.add, size: 16), + label: Text(l10n.gitAddRemote), + ), + ], + ), + const SizedBox(height: 4), + if (remotes.isEmpty) + _buildEmptyState(context, l10n) + else + Flexible( + child: ListView.separated( + shrinkWrap: true, + itemCount: remotes.length, + separatorBuilder: (_, _) => const Divider(height: 1), + itemBuilder: (ctx, index) => _buildRemoteTile( + ctx, + l10n, + provider, + remotes[index], + ), + ), + ), + ], + ), + ), + ); + } + + Widget _buildEmptyState(BuildContext context, AppLocalizations l10n) { + final theme = Theme.of(context); + return Padding( + padding: const EdgeInsets.symmetric(vertical: 28, horizontal: 12), + child: Column( + children: [ + Icon( + Icons.cloud_off_outlined, + size: 34, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.6), + ), + const SizedBox(height: 10), + Text( + l10n.gitNoRemoteConfigured, + style: theme.textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600), + ), + const SizedBox(height: 4), + Text( + l10n.gitNoRemoteDesc, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ); + } + + Widget _buildRemoteTile( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, + GitRemote remote, + ) { + final theme = Theme.of(context); + + return ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), + leading: Icon( + remote.isSsh ? Icons.vpn_key_outlined : Icons.language_outlined, + size: 20, + color: theme.colorScheme.primary, + ), + title: Text( + remote.name, + style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 13.5), + ), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + remote.fetchUrl, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11.5), + ), + // 仅当推送地址与抓取地址不同才展示,避免视觉噪音 + if (remote.pushUrl != null) + Text( + 'push: ${remote.pushUrl}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + trailing: PopupMenuButton( + tooltip: l10n.gitRemoteEdit, + onSelected: (action) => + _handleAction(context, l10n, provider, remote, action), + itemBuilder: (_) => [ + PopupMenuItem(value: 'test', child: Text(l10n.gitCheckConnection)), + PopupMenuItem(value: 'edit', child: Text(l10n.gitRemoteEdit)), + PopupMenuItem(value: 'rename', child: Text(l10n.gitRemoteName)), + PopupMenuItem(value: 'prune', child: Text(l10n.gitRemotePrune)), + if (remote.host != null) + PopupMenuItem(value: 'open', child: Text(l10n.gitRemoteFetchUrl)), + const PopupMenuDivider(), + PopupMenuItem( + value: 'remove', + child: Text( + l10n.delete, + style: TextStyle(color: theme.colorScheme.error), + ), + ), + ], + ), + ); + } + + Future _handleAction( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, + GitRemote remote, + String action, + ) async { + switch (action) { + case 'test': + await _testConnection(context, l10n, provider, remote); + break; + case 'edit': + await _showEditDialog(context, l10n, provider, remote); + break; + case 'rename': + await _showRenameDialog(context, l10n, provider, remote); + break; + case 'prune': + final res = await provider.pruneRemote(remote.name); + if (!context.mounted) return; + DialogUtils.showToast( + context, + res.success ? l10n.gitRemotePruned : res.stderr, + type: res.success ? ToastType.success : ToastType.error, + ); + break; + case 'open': + final url = _webUrlFor(remote); + if (url != null) { + await launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication); + } + break; + case 'remove': + await _confirmRemove(context, l10n, provider, remote); + break; + } + } + + /// 把 git 地址转换为可在浏览器打开的网页地址 + String? _webUrlFor(GitRemote remote) { + final host = remote.host; + final path = remote.repositoryPath; + if (host == null || path == null) return null; + final cleanPath = path.replaceAll(RegExp(r'\.git$'), ''); + if (remote.isSsh) { + return 'https://$host/$cleanPath'; + } + final uri = Uri.tryParse(remote.fetchUrl); + if (uri == null) return null; + return '${uri.scheme}://$host/$cleanPath'; + } + + /// 连接与认证自检:比让用户"推一次试试"友好得多 + Future _testConnection( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, + GitRemote remote, + ) async { + final res = await provider.checkRemoteAuth(remote.fetchUrl); + if (!context.mounted) return; + final error = provider.lastRemoteError; + if (res.success) { + DialogUtils.showToast(context, l10n.gitCheckConnectionSuccess, type: ToastType.success); + } else if (error != null) { + // 与同步条一致:按错误类型取 l10n 文案,附上 git 原始错误行(若有) + final detail = error.rawDetail; + final text = detail == null || detail.isEmpty + ? error.kind.message(l10n) + : '${error.kind.message(l10n)}\n$detail'; + DialogUtils.showToast(context, text, type: ToastType.error); + } + } + + Future _confirmRemove( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, + GitRemote remote, + ) async { + final confirmed = await DialogUtils.showDestructiveConfirmDialog( + context, + title: '${l10n.delete} ${remote.name}', + message: l10n.gitRemoteRemoveConfirm(remote.name), + icon: Icons.cloud_off_outlined, + ); + if (!confirmed || !context.mounted) return; + + final res = await provider.removeRemote(remote.name); + if (!context.mounted) return; + DialogUtils.showToast( + context, + res.success ? l10n.gitRemoteRemoved(remote.name) : res.stderr, + type: res.success ? ToastType.success : ToastType.error, + ); + } + + Future _showAddDialog( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, + ) async { + final result = await showDialog<({String name, String url, String pushUrl})>( + context: context, + builder: (_) => _RemoteEditDialog( + title: l10n.gitAddRemote, + initialName: provider.remotes.isEmpty ? 'origin' : '', + ), + ); + if (result == null || !context.mounted) return; + + final res = await provider.addRemote( + result.name, + result.url, + pushUrl: result.pushUrl.isEmpty ? null : result.pushUrl, + ); + if (!context.mounted) return; + DialogUtils.showToast( + context, + res.success ? l10n.gitRemoteAdded(result.name) : res.stderr, + type: res.success ? ToastType.success : ToastType.error, + ); + } + + Future _showEditDialog( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, + GitRemote remote, + ) async { + final result = await showDialog<({String name, String url, String pushUrl})>( + context: context, + builder: (_) => _RemoteEditDialog( + title: l10n.gitRemoteEdit, + initialName: remote.name, + initialUrl: remote.fetchUrl, + initialPushUrl: remote.pushUrl ?? '', + lockName: true, + ), + ); + if (result == null || !context.mounted) return; + + final res = await provider.setRemoteUrl(remote.name, result.url); + if (!res.success) { + if (!context.mounted) return; + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + return; + } + + if (result.pushUrl.isNotEmpty && result.pushUrl != remote.pushUrl) { + await provider.setRemoteUrl(remote.name, result.pushUrl, push: true); + } + if (!context.mounted) return; + DialogUtils.showToast(context, l10n.gitRemoteUrlUpdated, type: ToastType.success); + } + + Future _showRenameDialog( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, + GitRemote remote, + ) async { + final newName = await DialogUtils.showInputDialog( + context, + title: l10n.gitRemoteName, + hintText: l10n.gitRemoteNameHint, + initialValue: remote.name, + ); + if (newName == null || newName.trim().isEmpty || !context.mounted) return; + + final res = await provider.renameRemote(remote.name, newName.trim()); + if (!context.mounted) return; + DialogUtils.showToast( + context, + res.success + ? l10n.gitRemoteRenamed(remote.name, newName.trim()) + : res.stderr, + type: res.success ? ToastType.success : ToastType.error, + ); + } +} + +/// 添加 / 编辑远程仓库对话框 +class _RemoteEditDialog extends StatefulWidget { + const _RemoteEditDialog({ + required this.title, + this.initialName = '', + this.initialUrl = '', + this.initialPushUrl = '', + this.lockName = false, + }); + + final String title; + final String initialName; + final String initialUrl; + final String initialPushUrl; + final bool lockName; + + @override + State<_RemoteEditDialog> createState() => _RemoteEditDialogState(); +} + +class _RemoteEditDialogState extends State<_RemoteEditDialog> { + late final TextEditingController _nameController; + late final TextEditingController _urlController; + late final TextEditingController _pushUrlController; + String? _nameError; + String? _urlError; + + @override + void initState() { + super.initState(); + _nameController = TextEditingController(text: widget.initialName); + _urlController = TextEditingController(text: widget.initialUrl); + _pushUrlController = TextEditingController(text: widget.initialPushUrl); + } + + @override + void dispose() { + _nameController.dispose(); + _urlController.dispose(); + _pushUrlController.dispose(); + super.dispose(); + } + + void _submit(AppLocalizations l10n) { + final name = _nameController.text.trim(); + final url = _urlController.text.trim(); + final pushUrl = _pushUrlController.text.trim(); + + setState(() { + _nameError = name.isEmpty ? l10n.gitRemoteNameRequired : null; + _urlError = url.isEmpty ? l10n.gitRemoteUrlRequired : null; + }); + + if (name.isEmpty || url.isEmpty) return; + + Navigator.of(context).pop((name: name, url: url, pushUrl: pushUrl)); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + + return AlertDialog( + title: Text(widget.title), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + key: const ValueKey('git_remote_name_field'), + controller: _nameController, + enabled: !widget.lockName, + decoration: InputDecoration( + labelText: l10n.gitRemoteName, + hintText: l10n.gitRemoteNameHint, + errorText: _nameError, + ), + textInputAction: TextInputAction.next, + ), + const SizedBox(height: 10), + TextField( + key: const ValueKey('git_remote_url_field'), + controller: _urlController, + decoration: InputDecoration( + labelText: l10n.gitRemoteUrl, + hintText: l10n.gitRemoteUrlHint, + errorText: _urlError, + ), + keyboardType: TextInputType.url, + maxLines: 2, + minLines: 1, + ), + const SizedBox(height: 10), + TextField( + key: const ValueKey('git_remote_push_url_field'), + controller: _pushUrlController, + decoration: InputDecoration( + labelText: l10n.gitRemotePushUrl, + hintText: l10n.gitRemotePushUrlHint, + ), + keyboardType: TextInputType.url, + maxLines: 2, + minLines: 1, + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(l10n.cancel), + ), + FilledButton( + key: const ValueKey('git_remote_confirm_button'), + onPressed: () => _submit(l10n), + child: Text(l10n.confirm), + ), + ], + ); + } +} diff --git a/lib/widgets/git/git_repair_panel.dart b/lib/widgets/git/git_repair_panel.dart new file mode 100644 index 0000000..e55af9e --- /dev/null +++ b/lib/widgets/git/git_repair_panel.dart @@ -0,0 +1,501 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../models/git_model.dart'; +import '../../providers/git_provider.dart'; +import '../../services/internal_project_service.dart'; +import '../../utils/dialog_utils.dart'; +import '../../utils/git_error_mapper.dart'; + +/// 仓库完整性自检面板(底部弹出) +/// +/// 起因:`.git/objects` 中的对象在 PRoot 容器重建等场景下会丢失,而用户 +/// 只会在某次提交时撞上 `invalid object ... Error building trees`,完全 +/// 不知道原因。这个面板把问题提前暴露,并给出可执行的处置建议。 +class GitRepairPanel extends StatefulWidget { + const GitRepairPanel({super.key}); + + static Future show(BuildContext context) { + return showModalBottomSheet( + context: context, + isScrollControlled: true, + showDragHandle: true, + builder: (_) => const GitRepairPanel(), + ); + } + + @override + State createState() => _GitRepairPanelState(); +} + +class _GitRepairPanelState extends State { + @override + void initState() { + super.initState(); + // 打开即自动跑一次;面板本身不产生副作用(fsck 只读) + WidgetsBinding.instance.addPostFrameCallback((_) { + final provider = context.read(); + if (provider.fsckReport == null && !provider.isFsckRunning) { + provider.runFsck(); + } + }); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; + final provider = context.watch(); + final report = provider.fsckReport; + + return SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: Text( + l10n.gitRepairCheck, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ), + TextButton.icon( + key: const ValueKey('git_fsck_rerun_button'), + onPressed: provider.isFsckRunning ? null : provider.runFsck, + icon: const Icon(Icons.refresh, size: 16), + label: Text(l10n.gitRepairCheckRerun), + ), + ], + ), + const SizedBox(height: 8), + if (provider.isFsckRunning) + _buildRunning(theme, l10n) + else if (report == null) + _buildRunning(theme, l10n) + else + _buildReport(theme, l10n, report), + ], + ), + ), + ); + } + + Widget _buildRunning(ThemeData theme, AppLocalizations l10n) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 24), + child: Column( + children: [ + const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator(strokeWidth: 2), + ), + const SizedBox(height: 10), + Text( + l10n.gitRepairCheckRunning, + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ); + } + + Widget _buildReport( + ThemeData theme, + AppLocalizations l10n, + GitFsckReport report, + ) { + final colorScheme = theme.colorScheme; + + // 三种结局:健康 / 对象丢失 / 未能完成 + final Color bg; + final Color fg; + final IconData icon; + final String title; + final String hint; + + if (report.isHealthy) { + bg = colorScheme.primaryContainer.withValues(alpha: 0.5); + fg = colorScheme.onPrimaryContainer; + icon = Icons.verified_outlined; + title = l10n.gitRepairCheckHealthy; + hint = l10n.gitRepairCheckHealthyHint; + } else if (report.hasObjectLoss) { + bg = colorScheme.errorContainer.withValues(alpha: 0.5); + fg = colorScheme.onErrorContainer; + icon = Icons.report_problem_outlined; + title = l10n.gitRepairCheckObjectLoss(report.problemCount); + hint = l10n.gitRepairCheckObjectLossHint; + } else { + bg = colorScheme.tertiaryContainer.withValues(alpha: 0.5); + fg = colorScheme.onTertiaryContainer; + icon = Icons.help_outline; + title = l10n.gitRepairCheckFailed; + hint = l10n.gitRepairCheckFailedHint; + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, size: 18, color: fg), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + title, + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.bold, + color: fg, + ), + ), + const SizedBox(height: 3), + Text( + hint, + style: TextStyle(fontSize: 11, color: fg), + ), + ], + ), + ), + ], + ), + ), + // 悬空对象是正常现象,只在存在时用一行说明,避免制造焦虑 + if (report.dangling.isNotEmpty) ...[ + const SizedBox(height: 6), + Text( + l10n.gitRepairCheckDangling(report.dangling.length), + style: TextStyle( + fontSize: 10.5, + color: colorScheme.onSurfaceVariant, + ), + ), + ], + // 具体问题明细(最多展示若干条,避免超长) + if (report.problemCount > 0) ...[ + const SizedBox(height: 10), + Container( + constraints: const BoxConstraints(maxHeight: 140), + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.4), + borderRadius: BorderRadius.circular(6), + ), + child: SingleChildScrollView( + child: SelectableText( + [...report.missing, ...report.corrupt].take(30).join('\n'), + style: const TextStyle( + fontSize: 10, + fontFamily: 'JetBrains Mono', + ), + ), + ), + ), + const SizedBox(height: 10), + Text( + l10n.gitRepairAdviceTitle, + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.bold, + color: colorScheme.onSurface, + ), + ), + const SizedBox(height: 4), + _buildAdvice(l10n.gitRepairAdviceRemoveStale, colorScheme), + const SizedBox(height: 3), + _buildAdvice(l10n.gitRepairAdviceRestore, colorScheme), + ], + ], + ); + } + + Widget _buildAdvice(String text, ColorScheme colorScheme) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 4), + child: Icon(Icons.circle, size: 4, color: colorScheme.onSurfaceVariant), + ), + const SizedBox(width: 6), + Expanded( + child: Text( + text, + style: TextStyle( + fontSize: 11, + color: colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ); + } +} + +/// 克隆远端仓库对话框 +class GitCloneDialog extends StatefulWidget { + const GitCloneDialog({super.key}); + + /// 返回克隆成功后的目标目录路径;取消或失败返回 null + static Future show(BuildContext context) { + return showDialog( + context: context, + builder: (_) => const GitCloneDialog(), + ); + } + + @override + State createState() => _GitCloneDialogState(); +} + +class _GitCloneDialogState extends State { + final _urlCtrl = TextEditingController(); + final _dirCtrl = TextEditingController(); + final _branchCtrl = TextEditingController(); + final _depthCtrl = TextEditingController(); + + String? _urlError; + String? _dirError; + bool _cloning = false; + GitOperationProgress? _progress; + + @override + void dispose() { + _urlCtrl.dispose(); + _dirCtrl.dispose(); + _branchCtrl.dispose(); + _depthCtrl.dispose(); + super.dispose(); + } + + /// 从仓库地址推导默认目录名:`.../llama.cpp.git` → `llama.cpp` + String _deriveDirName(String url) { + var path = url.trim(); + // scp 风格 git@host:owner/repo.git + final scpMatch = RegExp(r'^[^@]+@[^:]+:(.+)$').firstMatch(path); + if (scpMatch != null) path = scpMatch.group(1)!; + final segments = path.split('/').where((s) => s.isNotEmpty).toList(); + if (segments.isEmpty) return ''; + return segments.last.replaceAll(RegExp(r'\.git$'), ''); + } + + Future _submit(AppLocalizations strings) async { + final url = _urlCtrl.text.trim(); + final dirName = _dirCtrl.text.trim().isEmpty + ? _deriveDirName(url) + : _dirCtrl.text.trim(); + + setState(() { + _urlError = url.isEmpty ? strings.gitCloneUrlRequired : null; + _dirError = dirName.isEmpty ? strings.gitCloneDirRequired : null; + }); + if (url.isEmpty || dirName.isEmpty) return; + + final projectsDir = await InternalProjectService.instance.getProjectsDirectory(); + if (!mounted) return; + final targetDir = Directory(p.join(projectsDir.path, dirName)); + if (targetDir.existsSync()) { + setState(() => _dirError = strings.gitCloneDirExists); + return; + } + + final depthText = _depthCtrl.text.trim(); + final depth = depthText.isEmpty ? null : int.tryParse(depthText); + + setState(() { + _cloning = true; + _progress = null; + }); + + // 在 async gap 之前取出 provider,避免跨越 await 使用 BuildContext + final provider = context.read(); + + // 克隆期间订阅进度;Provider 会持续 notifyListeners + void listener() { + if (!mounted) return; + final progress = provider.cloneProgress; + if (progress != _progress) setState(() => _progress = progress); + } + + provider.addListener(listener); + try { + final res = await provider.cloneRepository( + parentDir: projectsDir.path, + url: url, + targetDirName: dirName, + branch: _branchCtrl.text.trim().isEmpty ? null : _branchCtrl.text.trim(), + depth: depth, + ); + if (!mounted) return; + + if (res.success) { + Navigator.of(context).pop(targetDir.path); + } else if (res.cancelled) { + // 取消:清理可能残留的半成品目录,避免留下不可用的项目 + try { + if (targetDir.existsSync()) targetDir.deleteSync(recursive: true); + } catch (_) {} + if (!mounted) return; + Navigator.of(context).pop(); + } else { + setState(() => _cloning = false); + DialogUtils.showToast( + context, + provider.lastRemoteError?.kind.message(strings) ?? + strings.gitCloneFailed, + type: ToastType.error, + ); + } + } finally { + provider.removeListener(listener); + } + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final theme = Theme.of(context); + + return AlertDialog( + title: Text(l10n.gitClone), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + key: const ValueKey('git_clone_url_field'), + controller: _urlCtrl, + enabled: !_cloning, + decoration: InputDecoration( + labelText: l10n.gitCloneUrl, + hintText: l10n.gitCloneUrlHint, + errorText: _urlError, + ), + keyboardType: TextInputType.url, + maxLines: 2, + minLines: 1, + textInputAction: TextInputAction.next, + ), + const SizedBox(height: 10), + TextField( + key: const ValueKey('git_clone_dir_field'), + controller: _dirCtrl, + enabled: !_cloning, + decoration: InputDecoration( + labelText: l10n.gitCloneDirName, + hintText: l10n.gitCloneDirNameHint, + errorText: _dirError, + ), + textInputAction: TextInputAction.next, + ), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: TextField( + controller: _branchCtrl, + enabled: !_cloning, + decoration: InputDecoration( + labelText: l10n.gitCloneBranch, + hintText: l10n.gitCloneBranchHint, + isDense: true, + ), + ), + ), + const SizedBox(width: 10), + SizedBox( + width: 110, + child: TextField( + controller: _depthCtrl, + enabled: !_cloning, + decoration: InputDecoration( + labelText: l10n.gitCloneDepth, + hintText: l10n.gitCloneDepthHint, + isDense: true, + ), + keyboardType: TextInputType.number, + ), + ), + ], + ), + if (_cloning) ...[ + const SizedBox(height: 14), + Row( + children: [ + const SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator(strokeWidth: 1.8), + ), + const SizedBox(width: 8), + Expanded( + child: Text( + _progress?.raw.isNotEmpty == true + ? '${l10n.gitCloneRunning} ${_progress!.raw}' + : l10n.gitCloneRunning, + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.onSurfaceVariant, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + const SizedBox(height: 6), + ClipRRect( + borderRadius: BorderRadius.circular(3), + child: LinearProgressIndicator( + value: _progress?.percent != null + ? _progress!.percent! / 100.0 + : null, + minHeight: 4, + ), + ), + ], + ], + ), + ), + actions: [ + TextButton( + onPressed: _cloning + ? () => context.read().cancelClone() + : () => Navigator.of(context).pop(), + child: Text(_cloning ? l10n.gitCloneCancel : l10n.cancel), + ), + FilledButton( + key: const ValueKey('git_clone_confirm_button'), + onPressed: _cloning ? null : () => _submit(l10n), + child: Text(l10n.gitClone), + ), + ], + ); + } +} diff --git a/lib/widgets/git/git_sync_bar.dart b/lib/widgets/git/git_sync_bar.dart new file mode 100644 index 0000000..d88d6db --- /dev/null +++ b/lib/widgets/git/git_sync_bar.dart @@ -0,0 +1,1052 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../models/git_model.dart'; +import '../../providers/git_provider.dart'; +import '../../utils/dialog_utils.dart'; +import '../../utils/git_error_mapper.dart'; +import '../../views/git_account_management_view.dart'; +import 'git_remote_management_sheet.dart'; + +/// Git 云端同步工具条 +/// +/// 承载 Fetch / Pull / Push / 发布分支 四个动作,并内联展示: +/// - 进行中的操作进度、已用时间与取消按钮 +/// - 结构化错误提示与「一键修复」(先拉取再推送 / 放弃变基 / 去修账号) +/// - 可折叠的原始输出,便于排查 +/// +/// 计数(领先/落后)完全来自 `GitProvider.tracking`,即 ahead/behind 是 +/// 决定按钮文案的唯一信号,避免出现与真实状态不一致的按钮。 +class GitSyncBar extends StatefulWidget { + const GitSyncBar({super.key}); + + @override + State createState() => _GitSyncBarState(); +} + +class _GitSyncBarState extends State { + /// 云端操作开始时间,用于展示"已用时间" + DateTime? _startedAt; + + /// 每秒刷新一次已用时间;仅在操作进行中存在 + Timer? _elapsedTicker; + + bool _showRawLog = false; + + @override + void dispose() { + _elapsedTicker?.cancel(); + super.dispose(); + } + + void _syncTicker(bool busy) { + if (busy && _elapsedTicker == null) { + _startedAt = DateTime.now(); + _elapsedTicker = Timer.periodic(const Duration(seconds: 1), (_) { + if (mounted) setState(() {}); + }); + } else if (!busy && _elapsedTicker != null) { + _elapsedTicker!.cancel(); + _elapsedTicker = null; + _startedAt = null; + } + } + + /// 操作已进行的时长文案(大仓库长时间无百分比时,用户靠它判断是否卡死) + String? _elapsedText(AppLocalizations l10n) { + final started = _startedAt; + if (started == null) return null; + final elapsed = DateTime.now().difference(started); + final seconds = (elapsed.inSeconds % 60).toString().padLeft(2, '0'); + return l10n.gitElapsed( + l10n.gitElapsedMinutesSeconds(elapsed.inMinutes, seconds), + ); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; + final gitProvider = context.watch(); + + // 无仓库或 Git 未安装时不展示同步能力 + if (!gitProvider.hasProject || + !gitProvider.gitInstalled || + gitProvider.currentRepo == null) { + return const SizedBox.shrink(); + } + + _syncTicker(gitProvider.isRemoteBusy); + + // 尚未配置任何远程仓库:给出引导而不是一排点了必然失败的按钮 + if (!gitProvider.hasRemote && + !(gitProvider.tracking?.hasUpstream ?? false)) { + return _buildNoRemoteGuide(context, theme, l10n, gitProvider); + } + + final pushTarget = gitProvider.pushTarget; + final pushName = pushTarget.remote?.name ?? ''; + final upstreamName = gitProvider.tracking?.remoteName; + final differs = + pushName.isNotEmpty && upstreamName != null && pushName != upstreamName; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + // 与上方「分支」行完全一致的结构:左侧占满的选择条 + 右侧 32×32 图标按钮。 + // 这样三行(分支 / 远程 / 进度)视觉对齐,宽度也天然不会溢出。 + Row( + children: [ + Expanded( + child: _buildRemoteSelectorBar( + context, + theme, + l10n, + gitProvider, + differsFromUpstream: differs, + ), + ), + const SizedBox(width: 6), + _buildSyncButton(context, theme, l10n, gitProvider), + ], + ), + // 推送目标与上游不一致时的提示:单独占一行。 + // 绝不能塞进上面的选择条 —— 那是第三个抢宽度的元素,会把远程名挤到溢出。 + if (differs) ...[ + const SizedBox(height: 4), + _buildPushTargetNotice( + theme, + l10n, + // differs 为真已保证 upstreamName 非空 + upstreamName: upstreamName, + pushName: pushName, + ), + ], + if (gitProvider.remoteProgress != null || gitProvider.isRemoteBusy) ...[ + const SizedBox(height: 6), + _buildProgressRow(context, theme, l10n, gitProvider), + ], + if (gitProvider.lastRemoteError != null) ...[ + const SizedBox(height: 6), + _buildErrorPanel(context, theme, l10n, gitProvider), + ], + ], + ); + } + + /// fork 场景提示:拉取与推送指向不同远程,必须让用户看清 + /// + /// 注意 l10n 的签名是 `(upstream, push)`,两个都是 String, + /// 传反了编译器不会报错但文案会与事实相反 —— 已由测试锁住。 + Widget _buildPushTargetNotice( + ThemeData theme, + AppLocalizations l10n, { + required String upstreamName, + required String pushName, + }) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: theme.colorScheme.tertiaryContainer.withValues(alpha: 0.5), + borderRadius: BorderRadius.circular(6), + ), + child: Row( + children: [ + Icon( + Icons.info_outline, + size: 13, + color: theme.colorScheme.onTertiaryContainer, + ), + const SizedBox(width: 5), + Expanded( + child: Text( + l10n.gitPushTargetDiffersNotice(upstreamName, pushName), + style: TextStyle( + fontSize: 10.5, + color: theme.colorScheme.onTertiaryContainer, + ), + maxLines: 2, + ), + ), + ], + ), + ); + } + + /// 远程仓库选择条(样式与「分支」条保持一致,点击切换推送目标) + Widget _buildRemoteSelectorBar( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider provider, { + required bool differsFromUpstream, + }) { + final pushName = provider.pushTarget.remote?.name ?? ''; + final canPick = provider.remotes.length > 1; + final busy = provider.isRemoteBusy; + + final reason = _pushReason(l10n, provider.pushTarget.source); + final tooltip = differsFromUpstream + ? '${l10n.gitPushTargetTooltip(pushName, reason)}\n${l10n.gitPushTargetDiffers}' + : l10n.gitPushTargetTooltip(pushName, reason); + + return Material( + color: Colors.transparent, + child: InkWell( + key: const ValueKey('git_remote_selector_bar'), + borderRadius: BorderRadius.circular(6), + onTap: (!canPick || busy) + ? null + : () => _showPushTargetPicker(context, l10n, provider), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: theme.colorScheme.surface.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(6), + border: Border.all( + // 与上游不一致时(fork:拉 upstream、推 origin)用强调边框提示 + color: differsFromUpstream + ? theme.colorScheme.tertiary.withValues(alpha: 0.7) + : theme.colorScheme.outlineVariant.withValues(alpha: 0.4), + width: 0.8, + ), + ), + child: Tooltip( + message: tooltip, + child: Row( + children: [ + Icon( + Icons.cloud_outlined, + size: 14, + color: differsFromUpstream + ? theme.colorScheme.tertiary + : theme.colorScheme.primary, + ), + const SizedBox(width: 6), + Expanded( + child: Text( + pushName, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: differsFromUpstream + ? theme.colorScheme.tertiary + : theme.colorScheme.onSurface, + fontFamily: 'JetBrains Mono', + ), + overflow: TextOverflow.ellipsis, + ), + ), + if (canPick) + Icon( + Icons.arrow_drop_down, + size: 18, + color: theme.colorScheme.onSurfaceVariant, + ), + ], + ), + ), + ), + ), + ); + } + + /// 云同步按钮:与「分支」行右侧的更多按钮同尺寸、同形状,纯图标不带文字 + Widget _buildSyncButton( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider provider, + ) { + final colorScheme = theme.colorScheme; + final busy = provider.isRemoteBusy; + final ahead = provider.aheadCount; + final behind = provider.behindCount; + final needsPublish = provider.needsPublishBranch; + + // 图标反映"当前该做什么";计数交给菜单与下行进度,按钮本身保持纯图标 + final IconData icon; + if (busy) { + icon = Icons.sync; + } else if (behind > 0) { + icon = Icons.arrow_downward_rounded; + } else if (ahead > 0) { + icon = Icons.arrow_upward_rounded; + } else { + icon = Icons.cloud_outlined; + } + + return SizedBox( + width: 32, + height: 32, + child: PopupMenuButton<_SyncAction>( + key: const ValueKey('git_sync_cloud_button'), + icon: busy + ? SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator( + strokeWidth: 1.8, + color: colorScheme.primary, + ), + ) + : Icon( + icon, + size: 18, + color: (behind > 0 || ahead > 0) + ? colorScheme.primary + : colorScheme.onSurfaceVariant, + ), + tooltip: l10n.gitSyncCloudTooltip, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 32, minHeight: 32), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + enabled: !busy, + onSelected: (action) { + switch (action) { + case _SyncAction.fetch: + _runFetch(context, l10n, provider); + break; + case _SyncAction.pull: + _runPull(context, l10n, provider); + break; + case _SyncAction.push: + _runPush(context, l10n, provider); + break; + case _SyncAction.publish: + _runPush(context, l10n, provider, setUpstream: true); + break; + } + }, + itemBuilder: (_) => [ + PopupMenuItem( + value: _SyncAction.fetch, + child: _buildMenuItem( + icon: Icons.cloud_download_outlined, + label: l10n.gitFetch, + trailing: null, + ), + ), + PopupMenuItem( + value: _SyncAction.pull, + child: _buildMenuItem( + icon: Icons.arrow_downward_rounded, + label: l10n.gitPull, + trailing: behind > 0 ? '$behind' : null, + ), + ), + if (needsPublish) + PopupMenuItem( + value: _SyncAction.publish, + child: _buildMenuItem( + icon: Icons.cloud_upload_outlined, + label: l10n.gitPublishBranch, + trailing: null, + ), + ) + else + PopupMenuItem( + value: _SyncAction.push, + child: _buildMenuItem( + icon: Icons.arrow_upward_rounded, + label: l10n.gitPush, + trailing: ahead > 0 ? '$ahead' : null, + ), + ), + ], + ), + ); + } + + /// 云按钮菜单项:图标 + 文案 + 可选计数 + Widget _buildMenuItem({ + required IconData icon, + required String label, + required String? trailing, + }) { + return Row( + children: [ + Icon(icon, size: 16), + const SizedBox(width: 10), + Expanded(child: Text(label, style: const TextStyle(fontSize: 13))), + if (trailing != null) + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), + decoration: BoxDecoration( + color: Colors.grey.withValues(alpha: 0.25), + borderRadius: BorderRadius.circular(8), + ), + child: Text( + trailing, + style: const TextStyle(fontSize: 11, fontWeight: FontWeight.bold), + ), + ), + ], + ); + } + + // ---------------------------- 无远程仓库引导 ---------------------------- + + /// 未配置远程仓库时的引导视图 + /// + /// 此时前进/后退按钮都没有意义(既无上游也无地址),因此整条同步条 + /// 退化为一个明确的「添加远程仓库」入口,避免用户点了才发现失败。 + Widget _buildNoRemoteGuide( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider provider, + ) { + return Container( + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.4), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: theme.colorScheme.outlineVariant.withValues(alpha: 0.4), + width: 0.8, + ), + ), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + child: Row( + children: [ + Icon( + Icons.cloud_off_outlined, + size: 15, + color: theme.colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 6), + Expanded( + child: Text( + l10n.gitNoRemoteConfigured, + style: TextStyle( + fontSize: 11.5, + color: theme.colorScheme.onSurfaceVariant, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 6), + TextButton.icon( + key: const ValueKey('git_sync_add_remote_guide_button'), + onPressed: provider.isRemoteBusy + ? null + : () => GitRemoteManagementSheet.show(context), + icon: const Icon(Icons.add, size: 14), + label: Text( + l10n.gitAddRemote, + style: const TextStyle(fontSize: 11), + ), + style: TextButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 8), + minimumSize: const Size(0, 28), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ), + ], + ), + ); + } + + // ---------------------------- 推送目标徽标 ---------------------------- + // ---------------------------- 进度与取消 ---------------------------- + + Widget _buildProgressRow( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider provider, + ) { + final progress = provider.remoteProgress; + final elapsed = _elapsedText(l10n); + + // 大仓库长时间只输出无百分比的阶段(如 Enumerating objects)时, + // 已用时间能让用户判断是在正常传输还是已经卡死。 + final String primaryText; + if (progress != null && progress.raw.isNotEmpty) { + primaryText = '${_phaseLabel(l10n, progress.phase)} · ${progress.raw}'; + } else if (provider.isRemoteBusy) { + primaryText = l10n.gitRemoteOperationRunning; + } else { + primaryText = _phaseLabel(l10n, null); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Expanded( + child: Text( + elapsed == null ? primaryText : '$primaryText · $elapsed', + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.onSurfaceVariant, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 6), + // 取消按钮:长耗时推送不必干等 + TextButton( + key: const ValueKey('git_sync_cancel_button'), + onPressed: provider.isRemoteBusy + ? () => provider.cancelRemoteOperation() + : null, + style: TextButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 8), + minimumSize: const Size(0, 28), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + child: Text( + l10n.gitCancelOperation, + style: const TextStyle(fontSize: 11), + ), + ), + ], + ), + const SizedBox(height: 2), + ClipRRect( + borderRadius: BorderRadius.circular(3), + child: LinearProgressIndicator( + // 无百分比时为不确定态:git 的进度行并非每行都带百分比 + value: progress?.percent != null + ? progress!.percent! / 100.0 + : null, + minHeight: 4, + backgroundColor: theme.colorScheme.surfaceContainerHighest, + ), + ), + ], + ); + } + + String _phaseLabel(AppLocalizations l10n, String? phase) { + return switch (phase) { + 'fetch' => l10n.gitFetch, + 'pull' => l10n.gitPull, + 'push' => l10n.gitPush, + 'auth' => l10n.gitCheckConnection, + 'remote' => l10n.gitRemoteManagement, + _ => l10n.gitSync, + }; + } + + /// 推送目标的解析原因文案(解释"为什么推到这个远程") + String _pushReason(AppLocalizations l10n, GitRemoteSource source) { + return switch (source) { + GitRemoteSource.pushRemote => l10n.gitPushReasonPushRemote, + GitRemoteSource.pushDefault => l10n.gitPushReasonPushDefault, + GitRemoteSource.upstream => l10n.gitPushReasonUpstream, + GitRemoteSource.branchRemote => l10n.gitPushReasonBranchRemote, + GitRemoteSource.fallback => l10n.gitPushReasonFallback, + GitRemoteSource.manualOverride => l10n.gitPushReasonOverridden, + GitRemoteSource.none => l10n.gitPushReasonFallback, + }; + } + + /// 点击远程徽标切换推送目标(多远程时的显式选择) + Future _showPushTargetPicker( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, + ) async { + final current = provider.pushTarget.remote?.name; + final selected = await showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (sheetContext) { + final theme = Theme.of(sheetContext); + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Text( + l10n.gitTogglePushTarget, + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ), + for (final r in provider.remotes) + ListTile( + key: ValueKey('git_push_target_${r.name}'), + dense: true, + leading: Icon( + r.name == current + ? Icons.radio_button_checked + : Icons.radio_button_unchecked, + size: 18, + color: r.name == current ? theme.colorScheme.primary : null, + ), + title: Text( + r.name, + style: const TextStyle( + fontSize: 13.5, + fontFamily: 'JetBrains Mono', + ), + ), + // 地址与角色分两行:拼在一行会让 URL 把「上游(拉取)」 + // 挤到完全看不见,而角色恰恰是 fork 场景下最关键的判断依据。 + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + r.fetchUrl, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11), + ), + if (r.name == provider.tracking?.remoteName) ...[ + const SizedBox(height: 3), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, + vertical: 1, + ), + decoration: BoxDecoration( + color: theme.colorScheme.tertiaryContainer, + borderRadius: BorderRadius.circular(4), + ), + child: Text( + l10n.gitRemoteRoleUpstream, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + color: theme.colorScheme.onTertiaryContainer, + ), + ), + ), + ], + ], + ), + onTap: () => Navigator.of(sheetContext).pop(r.name), + ), + const SizedBox(height: 8), + ], + ), + ); + }, + ); + + if (selected == null || !context.mounted) return; + provider.setPushTargetOverride(selected); + DialogUtils.showToast( + context, + l10n.gitPushTargetChanged(selected), + type: ToastType.info, + ); + } + + // ---------------------------- 错误面板与一键修复 ---------------------------- + + Widget _buildErrorPanel( + BuildContext context, + ThemeData theme, + AppLocalizations l10n, + GitProvider provider, + ) { + final error = provider.lastRemoteError!; + final colorScheme = theme.colorScheme; + final detail = error.rawDetail; + final fixAction = error.fixAction; + + return Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: colorScheme.errorContainer.withValues(alpha: 0.5), + borderRadius: BorderRadius.circular(6), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.error_outline, size: 15, color: colorScheme.error), + const SizedBox(width: 5), + Expanded( + child: Text( + // 错误说明按类型取词,保持与项目其余部分一致的中英双语 + error.kind.message(l10n), + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w600, + color: colorScheme.onErrorContainer, + ), + ), + ), + InkWell( + onTap: () { + setState(() => _showRawLog = false); + provider.clearRemoteError(); + }, + child: Icon( + Icons.close, + size: 14, + color: colorScheme.onErrorContainer.withValues(alpha: 0.7), + ), + ), + ], + ), + const SizedBox(height: 4), + Text( + error.kind.suggestion(l10n), + style: TextStyle( + fontSize: 11, + color: colorScheme.onErrorContainer.withValues(alpha: 0.85), + ), + ), + // 兜底场景保留 git 的原始错误行(英文原文,不做翻译,便于精确检索) + if (detail != null && detail.isNotEmpty) ...[ + const SizedBox(height: 4), + Text( + detail, + style: TextStyle( + fontSize: 10.5, + fontFamily: 'JetBrains Mono', + color: colorScheme.onErrorContainer.withValues(alpha: 0.75), + ), + ), + ], + const SizedBox(height: 6), + Wrap( + spacing: 6, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + // 原始输出折叠入口:出错时完整输出是排查的第一手材料 + if (provider.remoteLog.isNotEmpty) + InkWell( + key: const ValueKey('git_error_toggle_raw_log'), + onTap: () => setState(() => _showRawLog = !_showRawLog), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + _showRawLog ? Icons.expand_less : Icons.expand_more, + size: 14, + color: colorScheme.onErrorContainer, + ), + const SizedBox(width: 2), + Text( + _showRawLog + ? l10n.gitHideOperationLog + : l10n.gitViewOperationLog, + style: TextStyle( + fontSize: 11, + decoration: TextDecoration.underline, + color: colorScheme.onErrorContainer, + ), + ), + ], + ), + ), + // 不同错误给不同出口 + if (fixAction == GitErrorFixAction.pullThenPush) + _FixAction( + key: const ValueKey('git_error_fix_pull_then_push'), + label: l10n.gitPullThenPush, + icon: Icons.sync, + onPressed: () => _runPullThenPush(context, l10n, provider), + ), + if (fixAction == GitErrorFixAction.fetchAndRetry) + _FixAction( + key: const ValueKey('git_error_fix_fetch_retry'), + label: l10n.gitFetch, + icon: Icons.refresh, + onPressed: () => _runFetch(context, l10n, provider), + ), + if (fixAction == GitErrorFixAction.abortRebase) + _FixAction( + key: const ValueKey('git_error_fix_abort_rebase'), + label: l10n.gitConflictAbort, + icon: Icons.undo, + onPressed: () => _runAbortRebase(context, l10n, provider), + ), + if (fixAction == GitErrorFixAction.openAccountManagement) + _FixAction( + key: const ValueKey('git_error_fix_accounts'), + label: l10n.gitAccountManagement, + icon: Icons.manage_accounts_outlined, + onPressed: () => _openAccountManagement(context), + ), + ], + ), + if (_showRawLog && provider.remoteLog.isNotEmpty) ...[ + const SizedBox(height: 6), + Container( + width: double.infinity, + constraints: const BoxConstraints(maxHeight: 160), + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: colorScheme.surface.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(4), + ), + child: SingleChildScrollView( + child: SelectableText( + provider.remoteLog, + style: const TextStyle( + fontSize: 10, + fontFamily: 'JetBrains Mono', + ), + ), + ), + ), + ], + ], + ), + ); + } + + // ---------------------------- 动作实现 ---------------------------- + + Future _runFetch( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, + ) async { + final res = await provider.fetchRemote(); + if (!context.mounted) return; + if (res.cancelled) { + DialogUtils.showToast( + context, + l10n.gitRemoteOperationCancelled, + type: ToastType.info, + ); + return; + } + if (res.success) { + DialogUtils.showToast( + context, + l10n.gitFetchSuccess, + type: ToastType.success, + ); + } + // 失败时不在 toast 里重复错误:错误面板已给出结构化说明与修复入口 + } + + /// 拉取:有未提交改动时先让用户决定(提交 / 贮藏 / 取消),绝不静默 stash + Future _runPull( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, + ) async { + if (provider.totalChangedCount > 0) { + final choice = await _showUncommittedChangesDialog(context, l10n); + if (choice == null || choice == _PullWithChanges.cancel) return; + if (choice == _PullWithChanges.commitFirst) return; + + final res = await provider.stashAndPull(); + if (!context.mounted) return; + if (res.success) { + DialogUtils.showToast( + context, + l10n.gitStashAndPullSuccess, + type: ToastType.success, + ); + } + return; + } + + final res = await provider.pull(); + if (!context.mounted) return; + if (res.cancelled) { + DialogUtils.showToast( + context, + l10n.gitRemoteOperationCancelled, + type: ToastType.info, + ); + return; + } + if (res.success) { + // `Already up to date.` 是正常结果,不该报错也不该渲染成"有更新" + final upToDate = res.stdout.toLowerCase().contains('up to date'); + DialogUtils.showToast( + context, + upToDate ? l10n.gitPullAlreadyUpToDate : l10n.gitPullSuccess, + type: upToDate ? ToastType.info : ToastType.success, + ); + } + } + + Future _runPush( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, { + bool setUpstream = false, + }) async { + final res = await provider.push(setUpstream: setUpstream); + if (!context.mounted) return; + if (res.cancelled) { + DialogUtils.showToast( + context, + l10n.gitRemoteOperationCancelled, + type: ToastType.info, + ); + return; + } + if (res.success) { + final upToDate = + res.stdout.toLowerCase().contains('up-to-date') || + res.stderr.toLowerCase().contains('up-to-date'); + DialogUtils.showToast( + context, + upToDate ? l10n.gitPushUpToDate : l10n.gitPushSuccess, + type: upToDate ? ToastType.info : ToastType.success, + ); + } + } + + Future _runPullThenPush( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, + ) async { + final res = await provider.pullThenPush(); + if (!context.mounted) return; + if (res.success) { + DialogUtils.showToast( + context, + l10n.gitPushSuccess, + type: ToastType.success, + ); + } + } + + Future _runAbortRebase( + BuildContext context, + AppLocalizations l10n, + GitProvider provider, + ) async { + final confirmed = await DialogUtils.showDestructiveConfirmDialog( + context, + title: l10n.gitConflictAbort, + message: l10n.gitConflictAbortConfirm, + confirmText: l10n.gitConflictAbort, + ); + if (!confirmed || !context.mounted) return; + + final res = await provider.abortRebase(); + if (!context.mounted) return; + if (res.success) { + DialogUtils.showToast( + context, + l10n.gitRemoteOperationCancelled, + type: ToastType.info, + ); + } else { + DialogUtils.showToast(context, res.stderr, type: ToastType.error); + } + } + + void _openAccountManagement(BuildContext context) { + // 账号管理页面已存在于设置中,这里通过既有入口跳转 + Navigator.of(context).push( + MaterialPageRoute(builder: (_) => const _AccountManagementLauncher()), + ); + } + + /// 未提交改动时的三选一(提交 / 贮藏并拉取 / 取消) + Future<_PullWithChanges?> _showUncommittedChangesDialog( + BuildContext context, + AppLocalizations l10n, + ) { + return showDialog<_PullWithChanges>( + context: context, + builder: (dialogContext) { + final theme = Theme.of(dialogContext); + return AlertDialog( + icon: Icon( + Icons.warning_amber_rounded, + color: theme.colorScheme.tertiary, + ), + title: Text(l10n.gitUncommittedChangesTitle), + content: Text(l10n.gitUncommittedChangesDesc), + actions: [ + TextButton( + onPressed: () => + Navigator.of(dialogContext).pop(_PullWithChanges.cancel), + child: Text(l10n.gitUncommittedCancel), + ), + TextButton( + onPressed: () => + Navigator.of(dialogContext).pop(_PullWithChanges.commitFirst), + child: Text(l10n.gitUncommittedCommitFirst), + ), + FilledButton( + onPressed: () => Navigator.of( + dialogContext, + ).pop(_PullWithChanges.stashAndPull), + child: Text(l10n.gitUncommittedStashAndPull), + ), + ], + ); + }, + ); + } +} + +/// 未提交改动时用户的选择 +enum _PullWithChanges { stashAndPull, commitFirst, cancel } + +/// 云按钮菜单中的动作类型 +/// +/// 用枚举而不是字符串:PopupMenuButton 的 value 若拼写错误会静默失效, +/// 枚举可以让编译器兜住。 +enum _SyncAction { fetch, pull, push, publish } + +/// 错误面板内的修复动作按钮 +class _FixAction extends StatelessWidget { + const _FixAction({ + super.key, + required this.label, + required this.icon, + required this.onPressed, + }); + + final String label; + final IconData icon; + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return OutlinedButton.icon( + onPressed: onPressed, + icon: Icon(icon, size: 13), + label: Text(label, style: const TextStyle(fontSize: 11)), + style: OutlinedButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 8), + minimumSize: const Size(0, 30), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + foregroundColor: theme.colorScheme.onErrorContainer, + side: BorderSide( + color: theme.colorScheme.onErrorContainer.withValues(alpha: 0.35), + width: 0.8, + ), + ), + ); + } +} + +/// 账号管理跳转:复用设置页已有的 GitAccountManagementView +class _AccountManagementLauncher extends StatelessWidget { + const _AccountManagementLauncher(); + + @override + Widget build(BuildContext context) { + return const GitAccountManagementView(); + } +} diff --git a/test/git_remote_test.dart b/test/git_remote_test.dart new file mode 100644 index 0000000..9103536 --- /dev/null +++ b/test/git_remote_test.dart @@ -0,0 +1,964 @@ +import 'dart:io'; + +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/git_model.dart'; +import 'package:code_editor/services/distro_manager.dart'; +import 'package:code_editor/services/git_service.dart'; +import 'package:code_editor/utils/git_error_mapper.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// 记录每一次流式执行的调用参数,便于断言生成的 git 参数是否正确 +class _StreamCall { + final String executable; + final String? containerWorkDir; + _StreamCall(this.executable, this.containerWorkDir); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory tempDir; + + /// 已捕获的流式调用 + late List<_StreamCall> calls; + + setUp(() { + tempDir = Directory.systemTemp.createTempSync('git_remote_test_'); + calls = []; + GitService.instance.resetForTesting(); + // 让环境探测直接通过,避免依赖真实 git 安装 + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + }); + + tearDown(() { + GitService.instance.resetForTesting(); + if (tempDir.existsSync()) { + try { + tempDir.deleteSync(recursive: true); + } catch (_) {} + } + }); + + /// 安装一个假的流式执行器,返回指定结果 + void fakeStream({ + int exitCode = 0, + String stdout = '', + String stderr = '', + List? stdoutChunks, + }) { + GitService.instance.streamRunner = ({ + required String executable, + required List arguments, + required String workspacePath, + required String? containerWorkDir, + void Function(String chunk)? onOutput, + HeadlessCancelToken? cancelToken, + Duration timeout = const Duration(minutes: 5), + }) async { + calls.add(_StreamCall(executable, containerWorkDir)); + if (stdoutChunks != null && onOutput != null) { + for (final chunk in stdoutChunks) { + onOutput(chunk); + } + } + return ProcessResult(1, exitCode, stdout, stderr); + }; + } + + group('路径映射', () { + test('mapToContainerPath 在非 Android 或未注入映射时原样返回', () { + final service = GitService.instance; + // 单元测试跑在宿主机上,没有 /workspace 这层挂载 + expect(service.mapToContainerPath('/tmp/proj', '/tmp/proj'), equals('/tmp/proj')); + }); + + test('mapToContainerPath 可通过注入覆写并支持嵌套仓库', () { + final service = GitService.instance; + service.containerPathMapper = (hostPath) { + if (hostPath == '/root/proj') return '/workspace'; + if (hostPath == '/root/proj/packages/core') return '/workspace/packages/core'; + return '/workspace'; + }; + + expect(service.mapToContainerPath('/root/proj', '/root/proj'), equals('/workspace')); + expect( + service.mapToContainerPath('/root/proj/packages/core', '/root/proj'), + equals('/workspace/packages/core'), + ); + }); + }); + + group('guest 命令组装', () { + test('注入 GIT_TERMINAL_PROMPT 与禁交互配置,防止无 TTY 时挂起', () { + final cmd = GitService.instance.buildGuestGitCommand(['fetch', '--progress', 'origin']); + + expect(cmd, contains('GIT_TERMINAL_PROMPT=0')); + expect(cmd, contains('credential.interactive=false')); + expect(cmd, contains('core.askPass=')); + expect(cmd, contains('safe.directory=*')); + expect(cmd, contains('fetch --progress origin')); + }); + + test('注入 SSH BatchMode 与 accept-new 主机指纹策略', () { + final cmd = GitService.instance.buildGuestGitCommand(['push', 'origin', 'main']); + + expect(cmd, contains('GIT_SSH_COMMAND=')); + expect(cmd, contains('BatchMode=yes')); + expect(cmd, contains('StrictHostKeyChecking=accept-new')); + expect(cmd, contains('IdentitiesOnly=yes')); + expect(cmd, contains('/root/.ssh/id_ed25519')); + }); + + test('包含特殊字符的参数被安全转义(不破坏命令结构)', () { + final cmd = GitService.instance.buildGuestGitCommand( + ['remote', 'add', 'my remote', 'https://example.com/a b.git'], + ); + // 含空格 → 单引号包裹 + expect(cmd, contains("'my remote'")); + expect(cmd, contains("'https://example.com/a b.git'")); + }); + }); + + group('进度解析', () { + test('parseProgressPercent 解析常见 git 进度行', () { + final service = GitService.instance; + expect(service.parseProgressPercent('Receiving objects: 45% (450/1000), 1.2 MiB'), equals(45)); + expect(service.parseProgressPercent('Writing objects: 100% (12/12), done.'), equals(100)); + expect(service.parseProgressPercent('Resolving deltas: 7% (7/100)'), equals(7)); + // 非进度行 → null(由 UI 展示不确定态) + expect(service.parseProgressPercent('From github.com:owner/repo'), isNull); + expect(service.parseProgressPercent('Counting objects: 3, done.'), isNull); + }); + + test('parseProgressPercent 对越界百分比做钳制', () { + expect(GitService.instance.parseProgressPercent('Weird: 999%'), equals(100)); + }); + + test('isProgressLine 过滤 remote: 日志行与空行', () { + final service = GitService.instance; + expect(service.isProgressLine('Receiving objects: 45%'), isTrue); + expect(service.isProgressLine('Writing objects: 100%'), isTrue); + expect(service.isProgressLine('remote: Enumerating objects'), isFalse); + expect(service.isProgressLine(' '), isFalse); + expect(service.isProgressLine('From github.com:owner/repo'), isTrue); + }); + }); + + group('remote -v 解析', () { + test('解析单个 origin 的 fetch/push 相同地址', () { + const output = 'origin\thttps://github.com/owner/repo.git (fetch)\n' + 'origin\thttps://github.com/owner/repo.git (push)\n'; + + final remotes = GitService.instance.parseRemotes(output); + expect(remotes.length, equals(1)); + expect(remotes.first.name, equals('origin')); + expect(remotes.first.fetchUrl, equals('https://github.com/owner/repo.git')); + // 与 fetch 相同则不重复保存 + expect(remotes.first.pushUrl, isNull); + expect(remotes.first.effectivePushUrl, equals('https://github.com/owner/repo.git')); + expect(remotes.first.isHttps, isTrue); + expect(remotes.first.isSsh, isFalse); + expect(remotes.first.host, equals('github.com')); + expect(remotes.first.repositoryPath, equals('owner/repo.git')); + }); + + test('解析 fetch 与 push 地址不同时的双地址', () { + const output = 'origin\thttps://github.com/owner/repo.git (fetch)\n' + 'origin\tgit@github.com:owner/repo.git (push)\n'; + + final remotes = GitService.instance.parseRemotes(output); + expect(remotes.length, equals(1)); + expect(remotes.first.fetchUrl, equals('https://github.com/owner/repo.git')); + expect(remotes.first.pushUrl, equals('git@github.com:owner/repo.git')); + expect(remotes.first.effectivePushUrl, equals('git@github.com:owner/repo.git')); + }); + + test('解析多个 remote 并保持出现顺序', () { + const output = 'upstream\thttps://github.com/up/repo.git (fetch)\n' + 'upstream\thttps://github.com/up/repo.git (push)\n' + 'origin\tgit@github.com:me/repo.git (fetch)\n' + 'origin\tgit@github.com:me/repo.git (push)\n'; + + final remotes = GitService.instance.parseRemotes(output); + expect(remotes.map((r) => r.name).toList(), equals(['upstream', 'origin'])); + expect(remotes[1].isSsh, isTrue); + // scp 风格地址的 host 解析 + expect(remotes[1].host, equals('github.com')); + expect(remotes[1].repositoryPath, equals('me/repo.git')); + }); + + test('空输出返回空列表,且忽略非法行', () { + final service = GitService.instance; + expect(service.parseRemotes(''), isEmpty); + expect(service.parseRemotes('garbage line without parens\n'), isEmpty); + }); + }); + + group('分支追踪状态解析', () { + test('porcelain v2 解析上游与 ahead/behind', () { + const output = '# branch.oid abc123\n' + '# branch.head main\n' + '# branch.upstream origin/main\n' + '# branch.ab +3 -2\n' + '1 M. N... 100644 100644 100644 aaa bbb file.dart\n'; + + final tracking = GitService.instance.parseBranchTracking(output); + expect(tracking.branch, equals('main')); + expect(tracking.upstream, equals('origin/main')); + expect(tracking.ahead, equals(3)); + expect(tracking.behind, equals(2)); + expect(tracking.hasUpstream, isTrue); + expect(tracking.isDiverged, isTrue); + expect(tracking.needsPush, isTrue); + expect(tracking.needsPull, isTrue); + expect(tracking.isUpToDate, isFalse); + expect(tracking.remoteName, equals('origin')); + expect(tracking.upstreamBranch, equals('main')); + }); + + test('porcelain v2 无上游时 hasUpstream 为 false', () { + const output = '# branch.oid abc123\n' + '# branch.head feature/local\n'; + + final tracking = GitService.instance.parseBranchTracking(output); + expect(tracking.branch, equals('feature/local')); + expect(tracking.hasUpstream, isFalse); + expect(tracking.needsPush, isFalse); + expect(tracking.remoteName, isNull); + }); + + test('porcelain v2 detached HEAD 不覆盖兜底分支名', () { + const output = '# branch.oid abc123\n' + '# branch.head (detached)\n' + '# branch.ab +0 -0\n'; + + final tracking = GitService.instance.parseBranchTracking(output, fallbackBranch: 'main'); + expect(tracking.branch, equals('main')); + expect(tracking.ahead, equals(0)); + expect(tracking.behind, equals(0)); + }); + + test('porcelain v1 简写解析 ahead/behind', () { + const output = '## main...origin/main [ahead 1, behind 2]\n' + ' M file.dart\n'; + + final tracking = GitService.instance.parseBranchTracking(output); + expect(tracking.branch, equals('main')); + expect(tracking.upstream, equals('origin/main')); + expect(tracking.ahead, equals(1)); + expect(tracking.behind, equals(2)); + }); + + test('porcelain v1 上游被删除时标记 isGone', () { + const output = '## feature/old...origin/feature/old [gone]\n'; + + final tracking = GitService.instance.parseBranchTracking(output); + expect(tracking.isGone, isTrue); + expect(tracking.upstream, equals('origin/feature/old')); + expect(tracking.ahead, equals(0)); + expect(tracking.behind, equals(0)); + }); + + test('porcelain v1 无上游分支(无 ... 分隔)', () { + const output = '## feature/new\n'; + + final tracking = GitService.instance.parseBranchTracking(output); + expect(tracking.branch, equals('feature/new')); + expect(tracking.hasUpstream, isFalse); + }); + + test('仅领先时 isUpToDate 为 false、needsPull 为 false', () { + const tracking = GitBranchTracking(branch: 'main', upstream: 'origin/main', ahead: 2); + expect(tracking.needsPush, isTrue); + expect(tracking.needsPull, isFalse); + expect(tracking.isDiverged, isFalse); + expect(tracking.isUpToDate, isFalse); + }); + + test('完全同步时 isUpToDate 为 true', () { + const tracking = GitBranchTracking(branch: 'main', upstream: 'origin/main'); + expect(tracking.isUpToDate, isTrue); + expect(tracking.needsPush, isFalse); + expect(tracking.needsPull, isFalse); + }); + }); + + group('远端命令参数生成', () { + test('fetch 默认带 --progress 与 --prune', () async { + fakeStream(); + await GitService.instance.fetch(tempDir.path, remote: 'origin'); + + expect(calls.length, equals(1)); + final cmd = calls.first.executable; + expect(cmd, contains('fetch --progress --prune origin')); + }); + + test('fetch 可关闭 prune', () async { + fakeStream(); + await GitService.instance.fetch(tempDir.path, remote: 'origin', prune: false); + + expect(calls.first.executable, contains('fetch --progress origin')); + expect(calls.first.executable, isNot(contains('--prune'))); + }); + + test('pull 使用 --rebase 且不自动 autostash', () async { + fakeStream(); + await GitService.instance.pullRebase(tempDir.path, remote: 'origin', branch: 'main'); + + final cmd = calls.first.executable; + expect(cmd, contains('pull --progress --rebase origin main')); + expect(cmd, isNot(contains('--autostash'))); + }); + + test('push 普通推送不带任何强制参数', () async { + fakeStream(); + await GitService.instance.push(tempDir.path, remote: 'origin', branch: 'main'); + + final cmd = calls.first.executable; + expect(cmd, contains('push --progress origin main')); + expect(cmd, isNot(contains('--force'))); + expect(cmd, isNot(contains('--set-upstream'))); + }); + + test('强推一律使用 --force-with-lease 而非 --force', () async { + fakeStream(); + await GitService.instance.push( + tempDir.path, + remote: 'origin', + branch: 'main', + forceWithLease: true, + ); + + final cmd = calls.first.executable; + expect(cmd, contains('--force-with-lease')); + // 关键安全断言:绝不生成裸 --force + expect(cmd, isNot(RegExp(r'--force(?![-\w])'))); + }); + + test('首次发布分支使用 --set-upstream', () async { + fakeStream(); + await GitService.instance.push( + tempDir.path, + remote: 'origin', + branch: 'feature/new', + setUpstream: true, + ); + + final cmd = calls.first.executable; + expect(cmd, contains('--set-upstream')); + expect(cmd, contains('origin feature/new')); + }); + + test('checkRemoteAuth 使用 ls-remote 校验连通性', () async { + fakeStream(); + await GitService.instance.checkRemoteAuth( + tempDir.path, + 'https://github.com/owner/repo.git', + ); + + expect(calls.first.executable, contains('ls-remote')); + expect(calls.first.executable, contains('https://github.com/owner/repo.git')); + }); + + test('checkRemoteAuth 空地址直接失败且不执行命令', () async { + fakeStream(); + final res = await GitService.instance.checkRemoteAuth(tempDir.path, ' '); + expect(res.success, isFalse); + expect(calls, isEmpty); + }); + }); + + group('命令结果与取消', () { + test('非零退出码映射为失败并保留 stderr', () async { + fakeStream(exitCode: 128, stderr: 'fatal: could not read Username'); + final res = await GitService.instance.fetch(tempDir.path, remote: 'origin'); + + expect(res.success, isFalse); + expect(res.exitCode, equals(128)); + expect(res.stderr, contains('could not read Username')); + expect(res.cancelled, isFalse); + }); + + test('成功时回传 stdout', () async { + fakeStream(stdout: 'From github.com:owner/repo\n'); + final res = await GitService.instance.fetch(tempDir.path, remote: 'origin'); + + expect(res.success, isTrue); + expect(res.stdout, contains('From github.com:owner/repo')); + }); + + test('进度回调收到解析后的百分比', () async { + fakeStream(stdoutChunks: [ + 'Receiving objects: 45% (450/1000)\n', + 'remote: some server log\n', + 'Receiving objects: 100% (1000/1000), done.\n', + ]); + + final seen = []; + await GitService.instance.fetch( + tempDir.path, + remote: 'origin', + onProgress: seen.add, + ); + + expect(seen.length, equals(2)); + expect(seen[0].percent, equals(45)); + expect(seen[0].phase, equals('fetch')); + expect(seen[1].percent, equals(100)); + }); + + test('Git 未安装时不执行命令并给出错误', () async { + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + throw const ProcessException('git', ['--version'], 'No such file', 2); + }; + GitService.instance.invalidateEnvStatus(); + fakeStream(); + + final res = await GitService.instance.fetch(tempDir.path, remote: 'origin'); + expect(res.success, isFalse); + expect(calls, isEmpty); + }); + }); + + group('远端仓库管理命令', () { + late List> executed; + + setUp(() { + executed = []; + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + executed.add(args); + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + }); + + test('addRemote 生成正确参数', () async { + await GitService.instance.addRemote(tempDir.path, 'origin', 'https://github.com/a/b.git'); + expect(executed.last, equals(['remote', 'add', 'origin', 'https://github.com/a/b.git'])); + }); + + test('addRemote 支持独立推送地址', () async { + await GitService.instance.addRemote( + tempDir.path, + 'origin', + 'https://github.com/a/b.git', + pushUrl: 'git@github.com:a/b.git', + ); + expect(executed.last, equals(['remote', 'set-url', '--push', 'origin', 'git@github.com:a/b.git'])); + }); + + test('addRemote 拒绝空名称或空地址', () async { + final r1 = await GitService.instance.addRemote(tempDir.path, ' ', 'https://x/y.git'); + expect(r1.success, isFalse); + final r2 = await GitService.instance.addRemote(tempDir.path, 'origin', ' '); + expect(r2.success, isFalse); + expect(executed.any((a) => a.contains('add')), isFalse); + }); + + test('removeRemote 与 pruneRemote 生成正确参数', () async { + await GitService.instance.removeRemote(tempDir.path, 'origin'); + expect(executed.last, equals(['remote', 'remove', 'origin'])); + + await GitService.instance.pruneRemote(tempDir.path, 'origin'); + expect(executed.last, equals(['remote', 'prune', 'origin'])); + }); + + test('renameRemote 生成正确参数并拒绝同名', () async { + await GitService.instance.renameRemote(tempDir.path, 'origin', 'upstream'); + expect(executed.last, equals(['remote', 'rename', 'origin', 'upstream'])); + + final same = await GitService.instance.renameRemote(tempDir.path, 'origin', 'origin'); + expect(same.success, isFalse); + }); + + test('setRemoteUrl 区分普通地址与推送地址', () async { + await GitService.instance.setRemoteUrl(tempDir.path, 'origin', 'https://new/url.git'); + expect(executed.last, equals(['remote', 'set-url', 'origin', 'https://new/url.git'])); + + await GitService.instance.setRemoteUrl( + tempDir.path, + 'origin', + 'git@new/url.git', + push: true, + ); + expect(executed.last, equals(['remote', 'set-url', '--push', 'origin', 'git@new/url.git'])); + }); + + test('getRemotes 解析输出', () async { + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + return ProcessResult( + 0, + 0, + 'origin\thttps://github.com/a/b.git (fetch)\norigin\thttps://github.com/a/b.git (push)\n', + '', + ); + }; + + final remotes = await GitService.instance.getRemotes(tempDir.path); + expect(remotes.length, equals(1)); + expect(remotes.first.name, equals('origin')); + }); + }); + + group('GitErrorMapper 错误分类', () { + late AppLocalizations l10nZh; + late AppLocalizations l10nEn; + + setUp(() async { + l10nZh = await AppLocalizations.delegate.load(const Locale('zh')); + l10nEn = await AppLocalizations.delegate.load(const Locale('en')); + }); + + test('识别认证失败(HTTP 401)', () { + final info = GitErrorMapper.describe('fatal: Authentication failed for https://github.com/'); + expect(info.kind, equals(GitOperationErrorKind.authFailed)); + expect(info.needsAccountFix, isTrue); + expect(info.kind.message(l10nZh), contains('认证失败')); + expect(info.kind.suggestion(l10nZh), isNotEmpty); + }); + + test('错误文案具备中英双语(不再硬编码中文)', () { + // 回归测试:GitErrorMapper 原先硬编码中文,绕过了项目的 l10n 体系 + const kind = GitOperationErrorKind.writePermissionDenied; + expect(kind.message(l10nZh), equals('当前账号对该仓库没有写权限')); + expect(kind.message(l10nEn), contains('no write access')); + expect(kind.suggestion(l10nEn), contains('fork')); + }); + + test('每种错误类型都有非空的本地化文案', () { + for (final kind in GitOperationErrorKind.values) { + if (kind == GitOperationErrorKind.none) continue; + expect(kind.message(l10nZh), isNotEmpty, reason: '${kind.name} 缺少中文说明'); + expect(kind.message(l10nEn), isNotEmpty, reason: '${kind.name} 缺少英文说明'); + } + }); + + test('区分平台已禁用密码认证', () { + final info = GitErrorMapper.describe( + 'remote: Support for password authentication was removed on August 13, 2021.', + ); + expect(info.kind, equals(GitOperationErrorKind.passwordAuthDisabled)); + expect(info.needsAccountFix, isTrue); + }); + + test('识别网络不可达', () { + final info = GitErrorMapper.describe('fatal: unable to access: Could not resolve host: github.com'); + expect(info.kind, equals(GitOperationErrorKind.networkUnreachable)); + // 不应被误判为认证问题 + expect(info.needsAccountFix, isFalse); + }); + + test('识别 SSH 公钥被拒', () { + final info = GitErrorMapper.describe('git@github.com: Permission denied (publickey).'); + expect(info.kind, equals(GitOperationErrorKind.sshPublicKeyDenied)); + }); + + test('识别主机指纹未确认', () { + final info = GitErrorMapper.describe('Host key verification failed.'); + expect(info.kind, equals(GitOperationErrorKind.hostKeyUnverified)); + }); + + test('识别推送被拒并提供 Pull 后重试', () { + final info = GitErrorMapper.describe( + '! [rejected] main -> main (non-fast-forward)\n' + 'error: failed to push some refs to origin', + ); + expect(info.kind, equals(GitOperationErrorKind.nonFastForward)); + expect(info.canPullThenPush, isTrue); + }); + + test('强推租约失败优先于普通推送被拒', () { + final info = GitErrorMapper.describe( + '! [rejected] main -> main (stale info)\n' + 'error: failed to push some refs to origin', + ); + expect(info.kind, equals(GitOperationErrorKind.staleForcePush)); + expect(info.canRefreshThenRetry, isTrue); + expect(info.canPullThenPush, isFalse); + }); + + test('识别 rebase 冲突', () { + final info = GitErrorMapper.describe( + 'CONFLICT (content): Merge conflict in lib/main.dart\n' + 'error: could not apply abc1234... feat', + ); + expect(info.kind, equals(GitOperationErrorKind.conflictDetected)); + expect(info.kind.suggestion(l10nZh), contains('rebase --abort')); + expect( + GitErrorMapper.isConflict('CONFLICT (content): Merge conflict in a.dart'), + isTrue, + ); + }); + + test('识别本地改动会被覆盖', () { + final info = GitErrorMapper.describe( + 'error: Your local changes to the following files would be overwritten by merge:', + ); + expect(info.kind, equals(GitOperationErrorKind.localChangesWouldBeOverwritten)); + }); + + test('识别未设置上游分支', () { + final info = GitErrorMapper.describe( + 'fatal: The current branch feat has no upstream branch.', + ); + expect(info.kind, equals(GitOperationErrorKind.noUpstreamConfigured)); + }); + + test('识别远端仓库不存在', () { + final info = GitErrorMapper.describe('remote: Repository not found.'); + expect(info.kind, equals(GitOperationErrorKind.repositoryNotFound)); + }); + + test('识别引用锁冲突', () { + final info = GitErrorMapper.describe( + "fatal: Unable to create '/proj/.git/index.lock': File exists.", + ); + expect(info.kind, equals(GitOperationErrorKind.refLockFailed)); + }); + + test('识别磁盘空间不足', () { + final info = GitErrorMapper.describe('fatal: write error: No space left on device'); + expect(info.kind, equals(GitOperationErrorKind.outOfSpace)); + }); + + test('stderr 为空时回退解析 stdout', () { + final info = GitErrorMapper.describe('', stdout: 'fatal: Authentication failed'); + expect(info.kind, equals(GitOperationErrorKind.authFailed)); + }); + + test('完全无输出时归类为操作未完成', () { + final info = GitErrorMapper.describe(''); + expect(info.kind, equals(GitOperationErrorKind.operationIncomplete)); + expect(info.kind.message(l10nZh), isNotEmpty); + }); + + test('未归类错误保留真实错误行便于排查', () { + final info = GitErrorMapper.describe('fatal: something entirely unexpected happened'); + expect(info.kind, equals(GitOperationErrorKind.unknown)); + expect(info.rawDetail, contains('something entirely unexpected')); + }); + + // ---------------- HTTP 状态码细分(不做统一归并)---------------- + + test('HTTP 407 单独归类为代理需要认证', () { + final info = GitErrorMapper.describe( + 'fatal: unable to access ... : The requested URL returned error: 407', + ); + expect(info.kind, equals(GitOperationErrorKind.proxyAuthRequired)); + // 不应与"令牌无效"混为一谈 + expect(info.kind, isNot(equals(GitOperationErrorKind.authFailed))); + expect(info.needsAccountFix, isFalse); + }); + + test('HTTP 429 单独归类为限流', () { + final info = GitErrorMapper.describe( + 'fatal: unable to access ... : The requested URL returned error: 429', + ); + expect(info.kind, equals(GitOperationErrorKind.rateLimited)); + }); + + test('HTTP 422 单独归类为请求被拒', () { + final info = GitErrorMapper.describe( + 'fatal: unable to access ... : The requested URL returned error: 422', + ); + expect(info.kind, equals(GitOperationErrorKind.requestRejected)); + }); + + test('未列举的 HTTP 状态码保留原始码值', () { + final info = GitErrorMapper.describe( + 'fatal: unable to access ... : The requested URL returned error: 502', + ); + expect(info.kind, equals(GitOperationErrorKind.httpError)); + expect(info.rawDetail, equals('502')); + }); + + test('401/403/404/407/422/429 各自归入不同类型', () { + const samples = { + '401': GitOperationErrorKind.authFailed, + '403': GitOperationErrorKind.writePermissionDenied, + '404': GitOperationErrorKind.repositoryNotFound, + '407': GitOperationErrorKind.proxyAuthRequired, + '422': GitOperationErrorKind.requestRejected, + '429': GitOperationErrorKind.rateLimited, + }; + for (final entry in samples.entries) { + final info = GitErrorMapper.describe( + 'fatal: unable to access ... : The requested URL returned error: ${entry.key}', + ); + expect( + info.kind, + equals(entry.value), + reason: 'HTTP ${entry.key} 应归类为 ${entry.value.name}', + ); + } + }); + + test('输出只有进度行时不再把进度当作错误原因', () { + // 真实事故:fetch 被超时打断,输出只剩进度,UI 却显示 + // "Git 操作失败 / remote: Enumerating objects: 2233, done." + final info = GitErrorMapper.describe( + 'remote: Enumerating objects: 2233, done.\n' + 'remote: Counting objects: 100% (2233/2233), done.', + ); + expect(info.kind, equals(GitOperationErrorKind.operationIncomplete)); + expect(info.kind.message(l10nZh), contains('没有返回具体错误信息')); + // 关键:绝不能把进度行当错误展示 + expect(info.rawDetail, isNull); + expect(info.kind.suggestion(l10nZh), isNot(contains('Enumerating objects'))); + expect(info.kind.suggestion(l10nZh), isNot(contains('Counting objects'))); + }); + + test('纯进度输出即便带百分比也不被当作错误', () { + final info = GitErrorMapper.describe( + 'Receiving objects: 45% (450/1000)\n' + 'Resolving deltas: 100% (7/7), done.', + ); + expect(info.kind, equals(GitOperationErrorKind.operationIncomplete)); + }); + + test('进度与真实错误混杂时挑出真实错误', () { + final info = GitErrorMapper.describe( + 'remote: Enumerating objects: 2233, done.\n' + 'fatal: the remote end hung up unexpectedly', + ); + expect(info.kind, equals(GitOperationErrorKind.unknown)); + expect(info.rawDetail, contains('remote end hung up unexpectedly')); + }); + + test('推送上游仓库被拒时提示 Fork,而不是甩锅给令牌', () { + // 真实事故:origin 指向 ggml-org/llama.cpp(别人的仓库), + // 原来的实现把 403 一律归为"令牌无效",把排查方向带偏 + final info = GitErrorMapper.describe( + 'remote: Permission to ggml-org/llama.cpp.git denied to lzxnone.\n' + 'fatal: unable to access ... : The requested URL returned error: 403', + ); + expect(info.kind, equals(GitOperationErrorKind.writePermissionDenied)); + expect(info.kind.message(l10nZh), contains('没有写权限')); + expect(info.kind.suggestion(l10nZh), contains('Fork')); + expect(info.fixAction, equals(GitErrorFixAction.openAccountManagement)); + }); + }); + + group('远端分支解析与检出', () { + test('解析 branch -r 输出并跳过 origin/HEAD 符号引用', () { + // 用 --format=%(HEAD)|%(refname:short),origin/HEAD 只会输出自己的名字 + // (箭头 -> 是 `git branch -r` 默认格式才有的,指定 --format 后不会出现) + const stdout = '*|origin/main\n' + ' |origin/feature/login\n' + ' |origin/HEAD\n'; + + final branches = GitService.instance.parseRemoteBranches(stdout); + expect(branches.length, equals(2)); + expect(branches[0].name, equals('origin/main')); + expect(branches[0].remoteName, equals('origin')); + expect(branches[0].branchName, equals('main')); + expect(branches[0].isCheckedOut, isTrue); + expect(branches[1].name, equals('origin/feature/login')); + expect(branches[1].isCheckedOut, isFalse); + // origin/HEAD 不应出现(它是符号引用,不是可检出的分支) + expect(branches.any((b) => b.name.endsWith('/HEAD')), isFalse); + }); + + test('兼容制表符分隔与 refs/remotes/ 完整引用', () { + // `%(HEAD)` 前导空格的数量由 git 决定,因此解析必须容忍制表符 + const stdout = '*\trefs/remotes/origin/main\n' + ' \torigin/dev\n'; + + final branches = GitService.instance.parseRemoteBranches(stdout); + expect(branches.length, equals(2)); + expect(branches[0].name, equals('origin/main')); + expect(branches[0].isCheckedOut, isTrue); + expect(branches[1].name, equals('origin/dev')); + }); + + test('多远程下分别解析出各自的远程名', () { + const stdout = ' |upstream/master\n' + ' |origin/master\n'; + + final branches = GitService.instance.parseRemoteBranches(stdout); + expect( + branches.map((b) => b.remoteName).toList(), + equals(['upstream', 'origin']), + ); + }); + + test('空输出与非法行不产生条目', () { + final service = GitService.instance; + expect(service.parseRemoteBranches(''), isEmpty); + expect(service.parseRemoteBranches('\n \n'), isEmpty); + // 没有远程前缀的行无法判断归属,直接忽略 + expect(service.parseRemoteBranches(' \tjustbranch\t\n'), isEmpty); + }); + + test('本地无同名分支时以 --track 创建', () async { + final executed = >[]; + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + executed.add(args); + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + if (args.contains('branch') && args.contains('--format=%(refname:short)')) { + return ProcessResult(0, 0, 'master\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + final res = await GitService.instance.checkoutRemoteBranch( + tempDir.path, + 'origin', + 'feature/login', + ); + + expect(res.success, isTrue); + expect( + executed.last, + equals(['checkout', '-b', 'feature/login', '--track', 'origin/feature/login']), + ); + }); + + test('本地已有同名分支时直接切换,不重复创建', () async { + final executed = >[]; + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + executed.add(args); + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + if (args.contains('branch') && args.contains('--format=%(refname:short)')) { + return ProcessResult(0, 0, 'master\nfeature/login\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + + await GitService.instance.checkoutRemoteBranch( + tempDir.path, + 'origin', + 'feature/login', + ); + + expect(executed.last, equals(['checkout', 'feature/login'])); + }); + + test('分支名为空时直接失败', () async { + final res = await GitService.instance.checkoutRemoteBranch( + tempDir.path, + 'origin', + ' ', + ); + expect(res.success, isFalse); + }); + }); + + group('仓库自检解析', () { + test('干净仓库判定为健康', () { + final report = GitService.instance.parseFsckReport( + 'Checking object directories: 100% (256/256), done.\n', + '', + exitCode: 0, + ); + expect(report.isHealthy, isTrue); + expect(report.hasObjectLoss, isFalse); + expect(report.problemCount, equals(0)); + }); + + test('识别对象丢失 —— 正是导致 Error building trees 的元凶', () { + final report = GitService.instance.parseFsckReport( + 'missing blob 26354cddec953ec05564851aed002b23ba9af4\n' + 'broken link from tree 1234567\n' + ' to blob 26354cddec953ec05564851aed002b23ba9af4\n', + '', + exitCode: 2, + ); + expect(report.hasObjectLoss, isTrue); + expect(report.isHealthy, isFalse); + expect(report.problemCount, greaterThan(0)); + expect(report.missing.length, equals(3)); + }); + + test('悬空对象不算问题,仅作提示', () { + final report = GitService.instance.parseFsckReport( + 'dangling blob abc123\n' + 'dangling commit def456\n', + '', + exitCode: 0, + ); + // dangling 是正常现象:仓库仍然健康,不应吓到用户 + expect(report.isHealthy, isTrue); + expect(report.hasObjectLoss, isFalse); + expect(report.dangling.length, equals(2)); + expect(report.problemCount, equals(0)); + }); + + test('stderr 中的问题同样被归类', () { + final report = GitService.instance.parseFsckReport( + '', + 'error: unable to read tree 1234567\n', + exitCode: 2, + ); + expect(report.hasObjectLoss, isTrue); + expect(report.corrupt, isNotEmpty); + }); + + test('无问题但退出码非 0 时视为未能完成', () { + final report = GitService.instance.parseFsckReport('', '', exitCode: -1); + expect(report.isHealthy, isFalse); + // 但这不是对象丢失,处置建议完全不同 + expect(report.hasObjectLoss, isFalse); + }); + }); + + group('克隆参数生成', () { + test('基础克隆生成 clone --progress ', () async { + fakeStream(); + await GitService.instance.clone( + tempDir.path, + 'https://github.com/a/b.git', + 'b', + ); + + final cmd = calls.first.executable; + expect(cmd, contains('clone --progress')); + expect(cmd, contains('https://github.com/a/b.git b')); + expect(cmd, isNot(contains('--depth'))); + expect(cmd, isNot(contains('--branch'))); + }); + + test('支持指定分支与浅克隆深度', () async { + fakeStream(); + await GitService.instance.clone( + tempDir.path, + 'https://github.com/a/b.git', + 'b', + branch: 'dev', + depth: 1, + ); + + final cmd = calls.first.executable; + expect(cmd, contains('--depth 1')); + expect(cmd, contains('--branch dev')); + }); + + test('地址或目录名为空时拒绝执行', () async { + fakeStream(); + final r1 = await GitService.instance.clone(tempDir.path, ' ', 'b'); + expect(r1.success, isFalse); + final r2 = await GitService.instance.clone( + tempDir.path, + 'https://x/y.git', + ' ', + ); + expect(r2.success, isFalse); + expect(calls, isEmpty); + }); + }); +} diff --git a/test/git_sync_bar_test.dart b/test/git_sync_bar_test.dart new file mode 100644 index 0000000..8bc0de2 --- /dev/null +++ b/test/git_sync_bar_test.dart @@ -0,0 +1,1209 @@ +import 'dart:io'; + +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/git_model.dart'; +import 'package:code_editor/providers/git_provider.dart'; +import 'package:code_editor/providers/project_provider.dart'; +import 'package:code_editor/providers/search_provider.dart'; +import 'package:code_editor/providers/tab_provider.dart'; +import 'package:code_editor/services/distro_manager.dart'; +import 'package:code_editor/services/git_service.dart'; +import 'package:code_editor/utils/git_error_mapper.dart'; +import 'package:code_editor/widgets/code_editor_drawer.dart'; +import 'package:code_editor/widgets/git/git_panel_widget.dart'; +import 'package:code_editor/widgets/git/git_remote_management_sheet.dart'; +import 'package:code_editor/widgets/git/git_sync_bar.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory tempDir; + late GitProvider gitProvider; + late ProjectProvider projectProvider; + late TabProvider tabProvider; + late SearchProvider searchProvider; + + /// 记录流式执行的命令串 + late List executedCommands; + + setUp(() { + tempDir = Directory.systemTemp.createTempSync('git_sync_bar_test_'); + executedCommands = []; + GitService.instance.resetForTesting(); + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + return ProcessResult(0, 0, '', ''); + }; + GitService.instance.streamRunner = ({ + required String executable, + required List arguments, + required String workspacePath, + required String? containerWorkDir, + void Function(String chunk)? onOutput, + HeadlessCancelToken? cancelToken, + Duration timeout = const Duration(minutes: 5), + }) async { + executedCommands.add(executable); + return ProcessResult(1, 0, '', ''); + }; + gitProvider = GitProvider(); + projectProvider = ProjectProvider(); + tabProvider = TabProvider()..bindProjectProvider(projectProvider); + searchProvider = SearchProvider()..bindRootPath(tempDir.path); + }); + + tearDown(() { + GitService.instance.resetForTesting(); + if (tempDir.existsSync()) { + try { + tempDir.deleteSync(recursive: true); + } catch (_) {} + } + }); + + Widget buildApp({Widget? home}) { + return ChangeNotifierProvider.value( + value: gitProvider, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: home ?? const Scaffold(body: GitPanelWidget()), + ), + ); + } + + /// 构造一个"已配置 origin 的正常仓库"状态 + void seedRepo({ + GitBranchTracking? tracking, + int changedCount = 0, + List? remotes, + }) { + final repoPath = p.normalize(tempDir.path); + gitProvider.setStateForTesting( + rootPath: repoPath, + currentRepoPath: repoPath, + currentBranch: 'main', + gitInstalled: true, + repositories: [ + GitRepositoryInfo( + rootPath: repoPath, + name: 'proj', + isRoot: true, + currentBranch: 'main', + ), + ], + changedFiles: List.generate( + changedCount, + (i) => GitFileStatus( + path: p.normalize(p.join(repoPath, 'f$i.dart')), + relativePath: 'f$i.dart', + statusType: GitFileStatusType.modified, + ), + ), + remotes: remotes ?? + const [ + GitRemote(name: 'origin', fetchUrl: 'https://github.com/me/repo.git'), + ], + tracking: tracking, + ); + } + + group('GitSyncBar 渲染', () { + /// 打开云按钮的动作菜单 + Future openSyncMenu(WidgetTester tester) async { + await tester.tap(find.byKey(const ValueKey('git_sync_cloud_button'))); + await tester.pumpAndSettle(); + } + + testWidgets('未打开仓库时不渲染同步工具条', (tester) async { + gitProvider.bindRootPath(null); + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + expect(find.byKey(const ValueKey('git_sync_cloud_button')), findsNothing); + }); + + testWidgets('未配置远程仓库时展示添加入口而非无效按钮', (tester) async { + seedRepo(remotes: const []); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + expect(find.byKey(const ValueKey('git_sync_add_remote_guide_button')), findsOneWidget); + expect(find.text('尚未配置远程仓库'), findsOneWidget); + // 关键:没有任何会必然失败的动作入口 + expect(find.byKey(const ValueKey('git_sync_cloud_button')), findsNothing); + }); + + testWidgets('有追踪上游但远程列表为空时仍展示同步按钮', (tester) async { + // 例如 remote 定义丢失但上游引用残留,此时不该屏蔽同步能力 + seedRepo( + remotes: const [], + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main', ahead: 1), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + expect(find.byKey(const ValueKey('git_sync_cloud_button')), findsOneWidget); + expect(find.byKey(const ValueKey('git_sync_add_remote_guide_button')), findsNothing); + }); + + testWidgets('云按钮展开后包含 抓取/拉取/推送 三个动作与计数', (tester) async { + seedRepo( + tracking: const GitBranchTracking( + branch: 'main', + upstream: 'origin/main', + ahead: 2, + behind: 3, + ), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + // 收起状态下只有一个云按钮,不再占据大半行宽 + expect(find.byKey(const ValueKey('git_sync_cloud_button')), findsOneWidget); + expect(find.text('抓取'), findsNothing); + + await openSyncMenu(tester); + expect(find.text('抓取'), findsOneWidget); + expect(find.text('拉取'), findsOneWidget); + expect(find.text('推送'), findsOneWidget); + // 菜单项上带计数 + expect(find.text('3'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + }); + + testWidgets('云按钮为纯图标,计数只在菜单中呈现', (tester) async { + seedRepo( + tracking: const GitBranchTracking( + branch: 'main', + upstream: 'origin/main', + ahead: 2, + behind: 3, + ), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + // 与「分支」行的更多按钮一致:纯图标、不带文字、不带角标 + expect(find.text('同步'), findsNothing); + expect(find.text('↓3'), findsNothing); + expect(find.text('↑2'), findsNothing); + // 落后时图标切换为下拉箭头,提示"有东西要拉" + expect(find.byIcon(Icons.arrow_downward_rounded), findsWidgets); + + await openSyncMenu(tester); + expect(find.text('3'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + }); + + testWidgets('仅领先时云按钮图标切换为上传', (tester) async { + seedRepo( + tracking: const GitBranchTracking( + branch: 'main', + upstream: 'origin/main', + ahead: 4, + ), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + expect(find.byIcon(Icons.arrow_upward_rounded), findsWidgets); + expect(find.text('↑4'), findsNothing); + }); + + testWidgets('无上游时菜单项变为「发布分支」', (tester) async { + seedRepo(tracking: const GitBranchTracking(branch: 'main')); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + await openSyncMenu(tester); + + expect(find.text('发布分支'), findsOneWidget); + expect(find.text('推送'), findsNothing); + }); + + testWidgets('上游被删除时同样视为需要发布分支', (tester) async { + seedRepo( + tracking: const GitBranchTracking( + branch: 'main', + upstream: 'origin/main', + isGone: true, + ), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + await openSyncMenu(tester); + + expect(find.text('发布分支'), findsOneWidget); + }); + + testWidgets('进行中的操作展示取消按钮,且云按钮被禁用', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main'), + changedCount: 0, + ); + gitProvider.setStateForTesting( + isFetching: true, + remoteProgress: const GitOperationProgress( + phase: 'fetch', + percent: 45, + raw: 'Receiving objects: 45% (450/1000)', + ), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + // 进度条为不确定态动画(无百分比),pumpAndSettle 永远不会稳定,只能用 pump + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(find.byKey(const ValueKey('git_sync_cancel_button')), findsOneWidget); + // 进行中时云按钮不可再点,避免并发操作打爆索引锁 + final button = tester.widget>( + find.byKey(const ValueKey('git_sync_cloud_button')), + ); + expect(button.enabled, isFalse); + }); + + testWidgets('错误面板为推送被拒提供「先拉取再推送」', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main'), + ); + gitProvider.setStateForTesting( + lastRemoteError: const GitErrorInfo( + kind: GitOperationErrorKind.nonFastForward, + fixAction: GitErrorFixAction.pullThenPush, + ), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + // 文案来自 l10n(中文环境),而非硬编码 + expect(find.text('推送被拒绝:远端存在本地尚无的提交'), findsOneWidget); + expect(find.byKey(const ValueKey('git_error_fix_pull_then_push')), findsOneWidget); + expect(find.text('先拉取再推送'), findsOneWidget); + }); + + testWidgets('错误面板按错误类型取词,无权限时提示 Fork', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main'), + ); + gitProvider.setStateForTesting( + lastRemoteError: const GitErrorInfo( + kind: GitOperationErrorKind.writePermissionDenied, + fixAction: GitErrorFixAction.openAccountManagement, + ), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + expect(find.text('当前账号对该仓库没有写权限'), findsOneWidget); + expect(find.textContaining('Fork'), findsOneWidget); + expect(find.byKey(const ValueKey('git_error_fix_accounts')), findsOneWidget); + }); + + testWidgets('兜底错误展示 git 原始输出行并可展开完整日志', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main'), + ); + gitProvider.setStateForTesting( + lastRemoteError: const GitErrorInfo( + kind: GitOperationErrorKind.unknown, + rawDetail: 'fatal: the remote end hung up unexpectedly', + ), + remoteLog: 'fatal: the remote end hung up unexpectedly\nsome more output', + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + // 原始英文错误行直接展示(便于精确检索) + expect(find.text('Git 操作失败'), findsOneWidget); + expect(find.text('fatal: the remote end hung up unexpectedly'), findsOneWidget); + + // 默认折叠,点击后展开完整输出 + expect(find.text('some more output'), findsNothing); + await tester.tap(find.byKey(const ValueKey('git_error_toggle_raw_log'))); + await tester.pumpAndSettle(); + expect(find.textContaining('some more output'), findsOneWidget); + }); + + testWidgets('冲突错误提供「放弃本次变基」', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main'), + ); + gitProvider.setStateForTesting( + lastRemoteError: const GitErrorInfo( + kind: GitOperationErrorKind.conflictDetected, + fixAction: GitErrorFixAction.abortRebase, + ), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + expect(find.byKey(const ValueKey('git_error_fix_abort_rebase')), findsOneWidget); + }); + + testWidgets('操作进行中显示已用时间计时', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main'), + ); + gitProvider.setStateForTesting( + isFetching: true, + remoteProgress: const GitOperationProgress( + phase: 'fetch', + raw: 'remote: Enumerating objects: 2233, done.', + ), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + await tester.pump(const Duration(seconds: 65)); + + // 无百分比的阶段靠"已用时间"判断是否卡死 + expect(find.textContaining('已用'), findsOneWidget); + expect(find.textContaining('Enumerating objects'), findsWidgets); + }); + }); + + group('GitSyncBar 响应式布局(窄屏不溢出)', () { + /// 在指定宽度下渲染同步条 + Future pumpAtWidth(WidgetTester tester, double width) async { + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: gitProvider, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: width, child: const GitSyncBar()), + ), + ), + ), + ), + ); + await tester.pump(); + } + + testWidgets('回归:窄屏抽屉宽度下不再水平溢出', (tester) async { + // 真实事故:360dp 手机打开抽屉后内容区仅剩 ~170dp, + // 4 个带文字的按钮造成 "RIGHT OVERFLOWED BY 12 PIXELS" + seedRepo( + tracking: const GitBranchTracking( + branch: 'main', + upstream: 'origin/main', + ahead: 3, + behind: 1, + ), + ); + + for (final width in [150, 170, 180, 200, 240, 320]) { + await pumpAtWidth(tester, width); + expect( + tester.takeException(), + isNull, + reason: '宽度 $width 下发生了布局溢出', + ); + } + }); + + testWidgets('极窄宽度下选定条与云按钮都保留且不溢出', (tester) async { + seedRepo( + tracking: const GitBranchTracking( + branch: 'main', + upstream: 'origin/main', + ahead: 3, + behind: 1, + ), + ); + + // 170dp 容器 ≈ 360dp 手机抽屉里的实际可用宽度。 + // 结构改为「Expanded 选定条 + 固定 32dp 按钮」后不再依赖像素分配, + // 因此任意宽度都不会溢出。 + for (final width in [120, 150, 170, 200]) { + await pumpAtWidth(tester, width); + expect(find.byKey(const ValueKey('git_remote_selector_bar')), findsOneWidget); + expect(find.byKey(const ValueKey('git_sync_cloud_button')), findsOneWidget); + expect( + tester.takeException(), + isNull, + reason: '宽度 $width 下发生了布局溢出', + ); + } + }); + + testWidgets('选定条占满剩余宽度,远程名用等宽字体展示', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main'), + ); + + await pumpAtWidth(tester, 300); + + expect(find.byKey(const ValueKey('git_remote_selector_bar')), findsOneWidget); + expect(find.text('origin'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('极窄宽度下远程名仍可见且不溢出', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main'), + ); + + await pumpAtWidth(tester, 150); + + expect(find.text('origin'), findsOneWidget); + expect(find.byKey(const ValueKey('git_sync_cloud_button')), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('云按钮始终为纯图标,任何宽度都不显示文字', (tester) async { + seedRepo( + tracking: const GitBranchTracking( + branch: 'main', + upstream: 'origin/main', + ahead: 2, + ), + ); + + for (final width in [150, 300, 360, 500]) { + await pumpAtWidth(tester, width); + expect(find.text('同步'), findsNothing, reason: '宽度 $width 下出现了按钮文字'); + expect(tester.takeException(), isNull); + } + }); + + + testWidgets('中文长菜单项「发布分支」在窄屏不溢出', (tester) async { + // 无上游时菜单文案变长,是中文界面下最容易溢出的分支 + seedRepo(tracking: const GitBranchTracking(branch: 'main')); + + for (final width in [150, 170, 200, 240, 320]) { + await pumpAtWidth(tester, width); + expect( + tester.takeException(), + isNull, + reason: '「发布分支」在宽度 $width 下发生了布局溢出', + ); + } + }); + + testWidgets('英文界面下长菜单项不溢出', (tester) async { + seedRepo(tracking: const GitBranchTracking(branch: 'main')); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: gitProvider, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('en'), + home: const Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 170, child: GitSyncBar()), + ), + ), + ), + ), + ); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(find.byKey(const ValueKey('git_sync_cloud_button')), findsOneWidget); + }); + }); + + group('GitSyncBar 交互', () { + /// 展开云按钮菜单并点选指定动作 + Future chooseSyncAction(WidgetTester tester, String label) async { + await tester.tap(find.byKey(const ValueKey('git_sync_cloud_button'))); + await tester.pumpAndSettle(); + await tester.tap(find.text(label)); + await tester.pumpAndSettle(); + } + + testWidgets('菜单中选「抓取」执行 fetch 命令', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main'), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + // 真实异步流程(含 toast 计时器)需在 runAsync 中完成 + await tester.runAsync(() async { + await chooseSyncAction(tester, '抓取'); + await Future.delayed(const Duration(milliseconds: 100)); + }); + await tester.pump(); + + expect(executedCommands.length, equals(1)); + expect(executedCommands.first, contains('fetch --progress --prune origin')); + + // 排空 toast 计时器 + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('有未提交改动时选「拉取」弹出三选一,取消则不执行任何命令', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main', behind: 1), + changedCount: 2, + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + await chooseSyncAction(tester, '拉取'); + + // 弹窗出现且包含三个出口 + expect(find.text('存在未提交的改动'), findsOneWidget); + expect(find.text('贮藏并拉取'), findsOneWidget); + expect(find.text('先去提交'), findsOneWidget); + + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + + // 关键:取消后绝不静默执行 stash 或 pull + expect(executedCommands, isEmpty); + + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('无未提交改动时选「拉取」直接执行 pull --rebase', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main', behind: 1), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + // 真实异步流程(含凭据灌注与 toast 计时器)需在 runAsync 中完成 + await tester.runAsync(() async { + await chooseSyncAction(tester, '拉取'); + await Future.delayed(const Duration(milliseconds: 120)); + }); + await tester.pump(); + + expect(executedCommands.length, equals(1)); + expect(executedCommands.first, contains('pull --progress --rebase origin main')); + + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('选「推送」执行 push 命令', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main', ahead: 1), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + await tester.runAsync(() async { + await chooseSyncAction(tester, '推送'); + await Future.delayed(const Duration(milliseconds: 120)); + }); + await tester.pump(); + + expect(executedCommands.length, equals(1)); + expect(executedCommands.first, contains('push --progress origin main')); + + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('选「发布分支」推送带 --set-upstream', (tester) async { + seedRepo(tracking: const GitBranchTracking(branch: 'main')); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + // 真实异步流程(含凭据灌注与 toast 计时器)需在 runAsync 中完成 + await tester.runAsync(() async { + await chooseSyncAction(tester, '发布分支'); + await Future.delayed(const Duration(milliseconds: 120)); + }); + await tester.pump(); + + expect(executedCommands.length, equals(1)); + expect(executedCommands.first, contains('--set-upstream')); + expect(executedCommands.first, isNot(contains('--force'))); + + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('远程管理已移出同步条,改由更多操作菜单进入', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main'), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + // 同步条上不再有独立的远程管理按钮(避免与「更多操作」重复) + expect(find.byKey(const ValueKey('git_sync_remote_button')), findsNothing); + expect(find.byType(GitRemoteManagementSheet), findsNothing); + }); + }); + + group('GitRemoteManagementSheet', () { + testWidgets('无远端时展示引导与添加入口', (tester) async { + seedRepo(remotes: const []); + + await tester.pumpWidget(buildApp( + home: const Scaffold(body: GitRemoteManagementSheet()), + )); + await tester.pumpAndSettle(); + + expect(find.text('尚未配置远程仓库'), findsOneWidget); + expect(find.byKey(const ValueKey('git_remote_add_button')), findsOneWidget); + }); + + testWidgets('添加远端时校验名称与地址必填', (tester) async { + seedRepo(remotes: const []); + + await tester.pumpWidget(buildApp( + home: const Scaffold(body: GitRemoteManagementSheet()), + )); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const ValueKey('git_remote_add_button'))); + await tester.pumpAndSettle(); + + // 清空默认的 origin 名称后直接确认 + await tester.enterText( + find.byKey(const ValueKey('git_remote_name_field')), + '', + ); + await tester.tap(find.byKey(const ValueKey('git_remote_confirm_button'))); + await tester.pumpAndSettle(); + + expect(find.text('请输入远程名称'), findsOneWidget); + expect(find.text('请输入远程地址'), findsOneWidget); + }); + + testWidgets('添加远端后执行 git remote add 并通知', (tester) async { + seedRepo(remotes: const []); + + final executed = >[]; + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + executed.add(args); + if (args.contains('remote') && args.contains('-v')) { + return ProcessResult( + 0, + 0, + 'origin\thttps://github.com/me/repo.git (fetch)\n' + 'origin\thttps://github.com/me/repo.git (push)\n', + '', + ); + } + return ProcessResult(0, 0, '', ''); + }; + + await tester.pumpWidget(buildApp( + home: const Scaffold(body: GitRemoteManagementSheet()), + )); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const ValueKey('git_remote_add_button'))); + await tester.pumpAndSettle(); + + await tester.enterText( + find.byKey(const ValueKey('git_remote_name_field')), + 'origin', + ); + await tester.enterText( + find.byKey(const ValueKey('git_remote_url_field')), + 'https://github.com/me/repo.git', + ); + await tester.tap(find.byKey(const ValueKey('git_remote_confirm_button'))); + await tester.pumpAndSettle(); + + expect( + executed.any((args) => + args.length >= 4 && + args[0] == 'remote' && + args[1] == 'add' && + args[2] == 'origin'), + isTrue, + ); + + await tester.pump(const Duration(seconds: 3)); + }); + }); + + group('多远程推送目标解析', () { + /// 让 git 返回完整的仓库信息(远程列表 + 上游 + 可配置的 config 值) + /// + /// [branch] 同时决定 `git status` 汇报的当前分支与查询哪个分支的 config, + /// 因此切换分支的测试必须同步改这个值。 + void seedGit({ + String? pushRemote, + String? pushDefault, + String? branchRemote, + String? upstreamRef = 'upstream/main', + String branch = 'main', + }) { + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + if (args.isNotEmpty && args[0] == 'config') { + final key = args.length > 1 ? args[1] : ''; + String? value; + if (key == 'branch.$branch.pushRemote') { + value = pushRemote; + } else if (key == 'remote.pushDefault') { + value = pushDefault; + } else if (key == 'branch.$branch.remote') { + value = branchRemote; + } + return value == null + ? ProcessResult(1, 1, '', '') + : ProcessResult(0, 0, '$value\n', ''); + } + if (args.contains('branch') && args.contains('--show-current')) { + // getCurrentRefInfo 优先走这一条;缺了它就会落到 .git/HEAD 兜底, + // 而测试目录没有真实 HEAD,最终返回硬编码的 'main'。 + return ProcessResult(0, 0, '$branch\n', ''); + } + if (args.contains('remote') && args.contains('-v')) { + return ProcessResult( + 0, + 0, + 'upstream\thttps://github.com/ggml-org/llama.cpp.git (fetch)\n' + 'upstream\thttps://github.com/ggml-org/llama.cpp.git (push)\n' + 'origin\thttps://github.com/lzxnone/llama.cpp.git (fetch)\n' + 'origin\thttps://github.com/lzxnone/llama.cpp.git (push)\n', + '', + ); + } + if (args.contains('status')) { + final buf = StringBuffer('# branch.head $branch\n'); + if (upstreamRef != null) { + buf.writeln('# branch.upstream $upstreamRef'); + buf.writeln('# branch.ab +0 -0'); + } + return ProcessResult(0, 0, buf.toString(), ''); + } + return ProcessResult(0, 0, '', ''); + }; + } + + /// 走真实的 refresh() 流程加载仓库配置 + Future loadForkRepo({ + String? pushRemote, + String? pushDefault, + String? branchRemote, + String? upstreamRef = 'upstream/main', + String branch = 'main', + }) async { + Directory(p.join(tempDir.path, '.git')).createSync(recursive: true); + seedGit( + pushRemote: pushRemote, + pushDefault: pushDefault, + branchRemote: branchRemote, + upstreamRef: upstreamRef, + branch: branch, + ); + gitProvider = GitProvider(); + gitProvider.bindRootPath(tempDir.path); + await gitProvider.refresh(); + } + + test('无任何配置时推送目标跟随上游远程', () async { + await loadForkRepo(); + + final target = gitProvider.pushTarget; + expect(target.remote?.name, equals('upstream')); + expect(target.source, equals(GitRemoteSource.upstream)); + // 上游与推送目标一致时,两者同值 + expect(gitProvider.fetchTarget?.name, equals('upstream')); + }); + + test('branch..pushRemote 优先级最高(fork 推送场景)', () async { + // git config branch.main.pushRemote origin + await loadForkRepo(pushRemote: 'origin'); + + final target = gitProvider.pushTarget; + expect(target.remote?.name, equals('origin')); + expect(target.source, equals(GitRemoteSource.pushRemote)); + // 关键:拉取仍走 upstream,推送走 origin —— 这正是 fork 工作流 + expect(gitProvider.fetchTarget?.name, equals('upstream')); + }); + + test('remote.pushDefault 次之', () async { + await loadForkRepo(pushDefault: 'origin'); + + final target = gitProvider.pushTarget; + expect(target.remote?.name, equals('origin')); + expect(target.source, equals(GitRemoteSource.pushDefault)); + }); + + test('fetch 目标优先 branch..remote(回归:不再固定抓 origin)', () async { + // 分支配置 remote=upstream,但上游引用缺失 + await loadForkRepo(branchRemote: 'upstream', upstreamRef: null); + + // 修复的核心:fork 场景下抓取必须走上游, + // 否则 upstream/* 永不更新,ahead/behind 会一直算错。 + expect(gitProvider.fetchTarget?.name, equals('upstream')); + }); + + test('缺少分支配置时 fetch 回退到 origin', () async { + await loadForkRepo(branchRemote: null, upstreamRef: null); + expect(gitProvider.fetchTarget?.name, equals('origin')); + }); + + test('pull 目标跟随上游远程', () async { + await loadForkRepo(pushRemote: 'origin'); + // 即使推送被改到 origin,拉取仍应跟随上游 + expect(gitProvider.pullTarget?.name, equals('upstream')); + }); + + test('会话级覆盖优先于 git 配置,且可恢复自动解析', () async { + await loadForkRepo(pushRemote: 'origin'); + + gitProvider.setPushTargetOverride('upstream'); + expect(gitProvider.pushTarget.remote?.name, equals('upstream')); + expect(gitProvider.pushTarget.source, equals(GitRemoteSource.manualOverride)); + expect(gitProvider.hasPushTargetOverride, isTrue); + + // 传 null 恢复按 git 配置自动解析 + gitProvider.setPushTargetOverride(null); + expect(gitProvider.hasPushTargetOverride, isFalse); + expect(gitProvider.pushTarget.remote?.name, equals('origin')); + expect(gitProvider.pushTarget.source, equals(GitRemoteSource.pushRemote)); + }); + + test('切换仓库会清空会话级覆盖', () async { + await loadForkRepo(); + gitProvider.setPushTargetOverride('origin'); + expect(gitProvider.hasPushTargetOverride, isTrue); + + seedGit(); + gitProvider.bindRootPath('/other/project'); + expect(gitProvider.hasPushTargetOverride, isFalse); + }); + + test('切换分支会清空会话级覆盖(防止把分支选择带过去)', () async { + await loadForkRepo(pushRemote: 'origin'); + // 用户在 main 上手动选了 upstream + gitProvider.setPushTargetOverride('upstream'); + expect(gitProvider.pushTarget.remote?.name, equals('upstream')); + + // 切到 feature 分支:该分支自己的 pushRemote 是 origin + seedGit(pushRemote: 'origin', branch: 'feature', upstreamRef: 'origin/feature'); + final res = await gitProvider.switchBranch('feature'); + expect(res.success, isTrue); + + // 关键:main 上的选择不能带到 feature 上,必须按 feature 自己的配置解析 + expect(gitProvider.hasPushTargetOverride, isFalse); + expect(gitProvider.pushTarget.remote?.name, equals('origin')); + expect(gitProvider.pushTarget.source, equals(GitRemoteSource.pushRemote)); + }); + + test('覆盖指向的远程被删除后自动失效并回落', () async { + await loadForkRepo(pushRemote: 'origin'); + // 覆盖到一个即将被删除的远程 + gitProvider.setPushTargetOverride('upstream'); + expect(gitProvider.pushTarget.remote?.name, equals('upstream')); + + // 模拟远程被删除后重新加载列表 + GitService.instance.processRunner = (exec, args, {workingDirectory}) async { + if (args.contains('--version')) { + return ProcessResult(0, 0, 'git version 2.45.0\n', ''); + } + if (args.contains('remote') && args.contains('-v')) { + return ProcessResult( + 0, + 0, + 'origin\thttps://github.com/lzxnone/llama.cpp.git (fetch)\n' + 'origin\thttps://github.com/lzxnone/llama.cpp.git (push)\n', + '', + ); + } + return ProcessResult(0, 0, '', ''); + }; + await gitProvider.reloadRemotes(); + + // 不能静默继续用旧名字,也不能悄悄推到别的远程还不告诉用户 + expect(gitProvider.hasPushTargetOverride, isFalse); + expect(gitProvider.pushTarget.remote?.name, equals('origin')); + expect(gitProvider.pushTarget.source, equals(GitRemoteSource.pushRemote)); + }); + + test('无远程时推送目标为空', () { + gitProvider.setStateForTesting( + rootPath: tempDir.path, + currentRepoPath: tempDir.path, + remotes: const [], + tracking: const GitBranchTracking(branch: 'main'), + ); + expect(gitProvider.pushTarget.remote, isNull); + expect(gitProvider.pushTarget.source, equals(GitRemoteSource.none)); + }); + + test('推送实际使用解析出的目标,而非固定 origin', () async { + await loadForkRepo(pushRemote: 'origin'); + gitProvider.setPushTargetOverride('origin'); + executedCommands.clear(); + + await gitProvider.push(); + + expect(executedCommands.length, equals(1)); + expect(executedCommands.first, contains('push --progress origin main')); + // 绝不推到上游(用户对上游没有写权限) + expect(executedCommands.first, isNot(contains('upstream main'))); + }); + + test('未配置 pushRemote 时推送跟随上游', () async { + await loadForkRepo(); + executedCommands.clear(); + + await gitProvider.push(); + + expect(executedCommands.length, equals(1)); + expect(executedCommands.first, contains('push --progress upstream main')); + }); + + testWidgets('多远程时点击选定条可切换推送目标', (tester) async { + await loadForkRepo(); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + expect(find.byKey(const ValueKey('git_remote_selector_bar')), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('git_remote_selector_bar'))); + await tester.pumpAndSettle(); + + // 列出全部远程,并标注哪个是上游 + expect(find.text('选择推送目标'), findsOneWidget); + expect(find.byKey(const ValueKey('git_push_target_origin')), findsOneWidget); + expect(find.byKey(const ValueKey('git_push_target_upstream')), findsOneWidget); + expect(find.textContaining('上游(拉取)'), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('git_push_target_origin'))); + await tester.pumpAndSettle(); + + expect(gitProvider.pushTarget.remote?.name, equals('origin')); + await tester.pump(const Duration(seconds: 3)); + }); + + testWidgets('单一远程时点击选定条不弹出选择器', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main'), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitSyncBar()))); + await tester.pumpAndSettle(); + + // 选定条仍然展示远程名,但只有一个时点击无意义 + expect(find.text('origin'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('git_remote_selector_bar'))); + await tester.pumpAndSettle(); + expect(find.text('选择推送目标'), findsNothing); + }); + + /// 在指定宽度下渲染并断言无溢出 + Future pumpForkAt(WidgetTester tester, double width) async { + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: gitProvider, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: width, child: const GitSyncBar()), + ), + ), + ), + ), + ); + await tester.pump(); + } + + testWidgets('推送目标≠上游时各宽度都不溢出(回归)', (tester) async { + // 真实事故:把「推送目标与上游不同」这句话塞进选择条当徽标, + // 使选择条内出现第三个抢宽度的元素 —— 窄屏溢出 45px, + // 且长远程名(upstream)被挤到看不见。 + await loadForkRepo(pushRemote: 'origin'); + expect(gitProvider.pushTarget.remote?.name, equals('origin')); + + for (final width in [150, 170, 200, 300]) { + await pumpForkAt(tester, width); + expect( + tester.takeException(), + isNull, + reason: '宽度 $width 下发生了布局溢出', + ); + } + }); + + testWidgets('提示行在极窄宽度下自动换行而不溢出', (tester) async { + await loadForkRepo(pushRemote: 'origin'); + + // 提示行只有图标 + Expanded 文本(maxLines 2),结构上不会溢出; + // 这里仍逐宽度验证,因为这句话比"推送目标与上游不同"长得多。 + for (final width in [120, 150, 170, 320]) { + await pumpForkAt(tester, width); + expect(find.textContaining('拉取走'), findsOneWidget); + expect( + tester.takeException(), + isNull, + reason: '提示行在宽度 $width 下发生了布局溢出', + ); + } + }); + + testWidgets('选择器里上游角色与地址分两行,角色不会被 URL 挤掉', (tester) async { + await loadForkRepo(pushRemote: 'origin'); + + await pumpForkAt(tester, 320); + await tester.tap(find.byKey(const ValueKey('git_remote_selector_bar'))); + await tester.pumpAndSettle(); + + // 关键:URL 很长时「上游(拉取)」仍然完整可见 + expect(find.text('上游(拉取)'), findsOneWidget); + expect( + find.text('https://github.com/ggml-org/llama.cpp.git'), + findsOneWidget, + ); + expect(tester.takeException(), isNull); + + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + }); + + testWidgets('提示单独占一行,选择条仍完整展示远程名', (tester) async { + await loadForkRepo(pushRemote: 'origin'); + + await pumpForkAt(tester, 320); + + expect(find.text('拉取走 upstream,推送走 origin'), findsOneWidget); + expect(find.text('origin'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('推送目标与上游一致时不显示提示行', (tester) async { + await loadForkRepo(); + + await pumpForkAt(tester, 320); + + // 推送目标跟随上游(都是 upstream),无需额外提示,避免噪音 + expect(find.textContaining('拉取走'), findsNothing); + expect(tester.takeException(), isNull); + }); + }); + + group('GitPanelWidget 集成云端入口', () { + testWidgets('320dp 手机宽度打开抽屉时 Git 面板不溢出', (tester) async { + // 端到端验证:真实 Drawer 布局下的可用宽度比单独渲染同步条更窄 + tester.view.physicalSize = const Size(320, 800); + tester.view.devicePixelRatio = 1.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + + seedRepo( + tracking: const GitBranchTracking( + branch: 'main', + upstream: 'origin/main', + ahead: 3, + behind: 2, + ), + ); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: gitProvider), + ChangeNotifierProvider.value(value: projectProvider), + ChangeNotifierProvider.value(value: tabProvider), + ChangeNotifierProvider.value(value: searchProvider), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: const Scaffold( + drawer: CodeEditorDrawer(), + body: Center(child: Text('Main Editor')), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final scaffoldState = tester.state(find.byType(Scaffold)); + scaffoldState.openDrawer(); + await tester.pumpAndSettle(); + + // 切到 Git 页签 + await tester.tap(find.byIcon(Icons.alt_route_rounded)); + await tester.pumpAndSettle(); + + expect(find.byType(GitSyncBar), findsOneWidget); + // 云按钮收拢了全部同步动作,收紧后主行只留远程名 + 一个按钮 + expect(find.byKey(const ValueKey('git_sync_cloud_button')), findsOneWidget); + expect(find.text('抓取'), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('Git 面板头部包含同步工具条', (tester) async { + seedRepo( + tracking: const GitBranchTracking( + branch: 'main', + upstream: 'origin/main', + ahead: 1, + behind: 1, + ), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + expect(find.byType(GitSyncBar), findsOneWidget); + expect(find.byKey(const ValueKey('git_sync_cloud_button')), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('更多操作菜单包含远程仓库管理', (tester) async { + seedRepo( + tracking: const GitBranchTracking(branch: 'main', upstream: 'origin/main'), + ); + + await tester.pumpWidget(buildApp(home: const Scaffold(body: GitPanelWidget()))); + await tester.pumpAndSettle(); + + await tester.tap(find.byTooltip('更多操作')); + await tester.pumpAndSettle(); + + expect(find.text('远程仓库管理'), findsWidgets); + }); + }); +} diff --git a/test/widget_test.dart b/test/widget_test.dart index 1eea739..e55a693 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -782,6 +782,15 @@ void main() { ); }); + test('buildAppTheme leaves horizontal margin for dialogs on narrow screens', () { + // 窄屏下对话框若顶满两侧,含输入框的弹窗容易水平溢出 + final theme = buildAppTheme(seedColor: Colors.blue, brightness: Brightness.light); + final inset = theme.dialogTheme.insetPadding!; + expect(inset.horizontal, greaterThan(0)); + // 320dp 屏扣掉边距后仍应留出足够的表单宽度 + expect(320 - inset.horizontal, greaterThanOrEqualTo(280)); + }); + test('terminalThemeWithBackground switches foreground on light backgrounds', () { final dark = terminalThemeWithBackground(const Color(0xFF1E1E1E)); expect(dark.background.toARGB32(), 0xFF1E1E1E);