This commit is contained in:
LZX committed 2026-09-19 21:07:45 +08:00
1 parent 4614825b7f
commit 6f5d1ed570
19 files changed
+9864 -99

No files matched your search

+401 -96
View File
@@ -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<GitPanelWidget> {
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<GitPanelWidget> {
],
),
],
// 第三行:云端同步工具条(抓取 / 拉取 / 推送 / 远程管理)
if (gitProvider.hasRepository && gitProvider.gitInstalled) ...[
const SizedBox(height: 6),
const GitSyncBar(),
],
],
),
),
@@ -433,6 +405,23 @@ class _GitPanelWidgetState extends State<GitPanelWidget> {
}
}
},
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<GitPanelWidget> {
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<void> _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<void> _handleClone(BuildContext context, AppLocalizations l10n) async {
final projectProvider = context.read<ProjectProvider>();
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<void> _showCreateBranchDialog(
BuildContext context,
@@ -2626,6 +2767,9 @@ class _BranchOrTagSelectorMenuDialog extends StatefulWidget {
final ValueChanged<String> onSwitchBranch;
final ValueChanged<String> onSwitchTag;
/// 基于远端分支检出本地分支
final ValueChanged<GitRemoteBranch> 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<String> branches) {
/// 分支列表 = 本地分支 + 远端分支两个分区
///
/// 分区标题只在对应分区非空时出现,避免只有一个分区时多一行噪音。
Widget _buildBranchSection(
BuildContext dialogCtx,
ColorScheme colorScheme,
List<String> localBranches,
List<GitRemoteBranch> remoteBranches,
) {
final showLocalHeader = localBranches.isNotEmpty && remoteBranches.isNotEmpty;
final rows = <Widget>[];
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<GitRemoteBranch> 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<String> 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];
@@ -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<void> show(BuildContext context) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
builder: (_) => const GitRemoteManagementSheet(),
);
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final provider = context.watch<GitProvider>();
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<String>(
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<void> _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<void> _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<void> _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<void> _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<void> _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<void> _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),
),
],
);
}
}
+501
View File
@@ -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<void> show(BuildContext context) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
builder: (_) => const GitRepairPanel(),
);
}
@override
State<GitRepairPanel> createState() => _GitRepairPanelState();
}
class _GitRepairPanelState extends State<GitRepairPanel> {
@override
void initState() {
super.initState();
// 打开即自动跑一次;面板本身不产生副作用(fsck 只读)
WidgetsBinding.instance.addPostFrameCallback((_) {
final provider = context.read<GitProvider>();
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<GitProvider>();
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<String?> show(BuildContext context) {
return showDialog<String>(
context: context,
builder: (_) => const GitCloneDialog(),
);
}
@override
State<GitCloneDialog> createState() => _GitCloneDialogState();
}
class _GitCloneDialogState extends State<GitCloneDialog> {
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<void> _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<GitProvider>();
// 克隆期间订阅进度;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<GitProvider>().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),
),
],
);
}
}
File diff suppressed because it is too large. Load diff