This commit is contained in:
LZX committed 2026-09-19 23:00:50 +08:00
1 parent 875840147d
commit a8b7bdf606
13 files changed
+2038 -16

No files matched your search

+48
View File
@@ -1365,6 +1365,54 @@
},
"gitConflictApplyOurs": "Use this",
"gitConflictApplyBoth": "Keep both",
"gitConflictResolveTitle": "Resolve Conflict",
"gitConflictBlockIndex": "Conflict {index} of {total}",
"@gitConflictBlockIndex": {
"placeholders": {
"index": {
"type": "int"
},
"total": {
"type": "int"
}
}
},
"gitConflictSectionBaseline": "Baseline (common ancestor)",
"gitConflictSectionOurs": "Current side",
"gitConflictSectionTheirs": "Incoming side",
"gitConflictTakeBoth": "Keep both",
"gitConflictEditManually": "Edit manually",
"gitConflictAllOurs": "Use current side for all",
"gitConflictAllTheirs": "Use incoming side for all",
"gitConflictSaveAndMark": "Save and mark resolved",
"gitConflictAcceptCurrent": "Accept Current Change",
"gitConflictAcceptIncoming": "Accept Incoming Change",
"gitConflictAcceptBoth": "Accept Both Changes",
"gitConflictCompare": "Compare Changes",
"gitConflictPrev": "Previous conflict",
"gitConflictNext": "Next conflict",
"gitConflictSaveAndMarkDone": "Resolved and written back",
"gitConflictNoBlocks": "No conflict markers left in this file",
"gitConflictLoadFailed": "Failed to load conflict contents",
"gitConflictUnresolvedRemain": "{count} block(s) still unresolved",
"@gitConflictUnresolvedRemain": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"gitConflictMarkWithMarkers": "{count} conflict marker(s) still remain in the file",
"@gitConflictMarkWithMarkers": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"gitConflictMarkWithMarkersHint": "Marking as resolved would commit them as normal content.",
"gitConflictMarkAnyway": "Mark anyway",
"gitConflictGoResolve": "Resolve first",
"gitRemoteBranches": "Remote Branches",
"gitLocalBranches": "Local Branches",
+144
View File
@@ -4018,6 +4018,150 @@ abstract class AppLocalizations {
/// **'两段都要'**
String get gitConflictApplyBoth;
/// No description provided for @gitConflictResolveTitle.
///
/// In zh, this message translates to:
/// **'解决冲突'**
String get gitConflictResolveTitle;
/// No description provided for @gitConflictBlockIndex.
///
/// In zh, this message translates to:
/// **'冲突 {index} / {total}'**
String gitConflictBlockIndex(int index, int total);
/// No description provided for @gitConflictSectionBaseline.
///
/// In zh, this message translates to:
/// **'基线(共同祖先)'**
String get gitConflictSectionBaseline;
/// No description provided for @gitConflictSectionOurs.
///
/// In zh, this message translates to:
/// **'当前侧'**
String get gitConflictSectionOurs;
/// No description provided for @gitConflictSectionTheirs.
///
/// In zh, this message translates to:
/// **'传入侧'**
String get gitConflictSectionTheirs;
/// No description provided for @gitConflictTakeBoth.
///
/// In zh, this message translates to:
/// **'两段都要'**
String get gitConflictTakeBoth;
/// No description provided for @gitConflictEditManually.
///
/// In zh, this message translates to:
/// **'手动编辑'**
String get gitConflictEditManually;
/// No description provided for @gitConflictAllOurs.
///
/// In zh, this message translates to:
/// **'全部采用当前侧'**
String get gitConflictAllOurs;
/// No description provided for @gitConflictAllTheirs.
///
/// In zh, this message translates to:
/// **'全部采用传入侧'**
String get gitConflictAllTheirs;
/// No description provided for @gitConflictSaveAndMark.
///
/// In zh, this message translates to:
/// **'保存并标记为已解决'**
String get gitConflictSaveAndMark;
/// No description provided for @gitConflictAcceptCurrent.
///
/// In zh, this message translates to:
/// **'采用当前侧'**
String get gitConflictAcceptCurrent;
/// No description provided for @gitConflictAcceptIncoming.
///
/// In zh, this message translates to:
/// **'采用传入侧'**
String get gitConflictAcceptIncoming;
/// No description provided for @gitConflictAcceptBoth.
///
/// In zh, this message translates to:
/// **'两段都保留'**
String get gitConflictAcceptBoth;
/// No description provided for @gitConflictCompare.
///
/// In zh, this message translates to:
/// **'对比查看'**
String get gitConflictCompare;
/// No description provided for @gitConflictPrev.
///
/// In zh, this message translates to:
/// **'上一处冲突'**
String get gitConflictPrev;
/// No description provided for @gitConflictNext.
///
/// In zh, this message translates to:
/// **'下一处冲突'**
String get gitConflictNext;
/// No description provided for @gitConflictSaveAndMarkDone.
///
/// In zh, this message translates to:
/// **'已解决并写回文件'**
String get gitConflictSaveAndMarkDone;
/// No description provided for @gitConflictNoBlocks.
///
/// In zh, this message translates to:
/// **'该文件已无冲突标记'**
String get gitConflictNoBlocks;
/// No description provided for @gitConflictLoadFailed.
///
/// In zh, this message translates to:
/// **'读取冲突内容失败'**
String get gitConflictLoadFailed;
/// No description provided for @gitConflictUnresolvedRemain.
///
/// In zh, this message translates to:
/// **'还剩 {count} 处未处理'**
String gitConflictUnresolvedRemain(int count);
/// No description provided for @gitConflictMarkWithMarkers.
///
/// In zh, this message translates to:
/// **'文件里仍残留 {count} 处冲突标记'**
String gitConflictMarkWithMarkers(int count);
/// No description provided for @gitConflictMarkWithMarkersHint.
///
/// In zh, this message translates to:
/// **'标记为已解决会把它们当作正常内容提交进仓库。建议先处理干净。'**
String get gitConflictMarkWithMarkersHint;
/// No description provided for @gitConflictMarkAnyway.
///
/// In zh, this message translates to:
/// **'仍然标记'**
String get gitConflictMarkAnyway;
/// No description provided for @gitConflictGoResolve.
///
/// In zh, this message translates to:
/// **'去处理'**
String get gitConflictGoResolve;
/// No description provided for @gitRemoteBranches.
///
/// In zh, this message translates to:
+79
View File
@@ -2394,6 +2394,85 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get gitConflictApplyBoth => 'Keep both';
@override
String get gitConflictResolveTitle => 'Resolve Conflict';
@override
String gitConflictBlockIndex(int index, int total) {
return 'Conflict $index of $total';
}
@override
String get gitConflictSectionBaseline => 'Baseline (common ancestor)';
@override
String get gitConflictSectionOurs => 'Current side';
@override
String get gitConflictSectionTheirs => 'Incoming side';
@override
String get gitConflictTakeBoth => 'Keep both';
@override
String get gitConflictEditManually => 'Edit manually';
@override
String get gitConflictAllOurs => 'Use current side for all';
@override
String get gitConflictAllTheirs => 'Use incoming side for all';
@override
String get gitConflictSaveAndMark => 'Save and mark resolved';
@override
String get gitConflictAcceptCurrent => 'Accept Current Change';
@override
String get gitConflictAcceptIncoming => 'Accept Incoming Change';
@override
String get gitConflictAcceptBoth => 'Accept Both Changes';
@override
String get gitConflictCompare => 'Compare Changes';
@override
String get gitConflictPrev => 'Previous conflict';
@override
String get gitConflictNext => 'Next conflict';
@override
String get gitConflictSaveAndMarkDone => 'Resolved and written back';
@override
String get gitConflictNoBlocks => 'No conflict markers left in this file';
@override
String get gitConflictLoadFailed => 'Failed to load conflict contents';
@override
String gitConflictUnresolvedRemain(int count) {
return '$count block(s) still unresolved';
}
@override
String gitConflictMarkWithMarkers(int count) {
return '$count conflict marker(s) still remain in the file';
}
@override
String get gitConflictMarkWithMarkersHint =>
'Marking as resolved would commit them as normal content.';
@override
String get gitConflictMarkAnyway => 'Mark anyway';
@override
String get gitConflictGoResolve => 'Resolve first';
@override
String get gitRemoteBranches => 'Remote Branches';
+78
View File
@@ -2321,6 +2321,84 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get gitConflictApplyBoth => '两段都要';
@override
String get gitConflictResolveTitle => '解决冲突';
@override
String gitConflictBlockIndex(int index, int total) {
return '冲突 $index / $total';
}
@override
String get gitConflictSectionBaseline => '基线(共同祖先)';
@override
String get gitConflictSectionOurs => '当前侧';
@override
String get gitConflictSectionTheirs => '传入侧';
@override
String get gitConflictTakeBoth => '两段都要';
@override
String get gitConflictEditManually => '手动编辑';
@override
String get gitConflictAllOurs => '全部采用当前侧';
@override
String get gitConflictAllTheirs => '全部采用传入侧';
@override
String get gitConflictSaveAndMark => '保存并标记为已解决';
@override
String get gitConflictAcceptCurrent => '采用当前侧';
@override
String get gitConflictAcceptIncoming => '采用传入侧';
@override
String get gitConflictAcceptBoth => '两段都保留';
@override
String get gitConflictCompare => '对比查看';
@override
String get gitConflictPrev => '上一处冲突';
@override
String get gitConflictNext => '下一处冲突';
@override
String get gitConflictSaveAndMarkDone => '已解决并写回文件';
@override
String get gitConflictNoBlocks => '该文件已无冲突标记';
@override
String get gitConflictLoadFailed => '读取冲突内容失败';
@override
String gitConflictUnresolvedRemain(int count) {
return '还剩 $count 处未处理';
}
@override
String gitConflictMarkWithMarkers(int count) {
return '文件里仍残留 $count 处冲突标记';
}
@override
String get gitConflictMarkWithMarkersHint => '标记为已解决会把它们当作正常内容提交进仓库。建议先处理干净。';
@override
String get gitConflictMarkAnyway => '仍然标记';
@override
String get gitConflictGoResolve => '去处理';
@override
String get gitRemoteBranches => '远端分支';
+48
View File
@@ -1365,6 +1365,54 @@
},
"gitConflictApplyOurs": "采用此段",
"gitConflictApplyBoth": "两段都要",
"gitConflictResolveTitle": "解决冲突",
"gitConflictBlockIndex": "冲突 {index} / {total}",
"@gitConflictBlockIndex": {
"placeholders": {
"index": {
"type": "int"
},
"total": {
"type": "int"
}
}
},
"gitConflictSectionBaseline": "基线(共同祖先)",
"gitConflictSectionOurs": "当前侧",
"gitConflictSectionTheirs": "传入侧",
"gitConflictTakeBoth": "两段都要",
"gitConflictEditManually": "手动编辑",
"gitConflictAllOurs": "全部采用当前侧",
"gitConflictAllTheirs": "全部采用传入侧",
"gitConflictSaveAndMark": "保存并标记为已解决",
"gitConflictAcceptCurrent": "采用当前侧",
"gitConflictAcceptIncoming": "采用传入侧",
"gitConflictAcceptBoth": "两段都保留",
"gitConflictCompare": "对比查看",
"gitConflictPrev": "上一处冲突",
"gitConflictNext": "下一处冲突",
"gitConflictSaveAndMarkDone": "已解决并写回文件",
"gitConflictNoBlocks": "该文件已无冲突标记",
"gitConflictLoadFailed": "读取冲突内容失败",
"gitConflictUnresolvedRemain": "还剩 {count} 处未处理",
"@gitConflictUnresolvedRemain": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"gitConflictMarkWithMarkers": "文件里仍残留 {count} 处冲突标记",
"@gitConflictMarkWithMarkers": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"gitConflictMarkWithMarkersHint": "标记为已解决会把它们当作正常内容提交进仓库。建议先处理干净。",
"gitConflictMarkAnyway": "仍然标记",
"gitConflictGoResolve": "去处理",
"gitRemoteBranches": "远端分支",
"gitLocalBranches": "本地分支",
+37
View File
@@ -206,4 +206,41 @@ class GitConflictParser {
static String _labelOf(String line, String marker) {
return line.length > marker.length ? line.substring(marker.length).trim() : '';
}
/// 把第 [blockIndex] 个冲突块替换为 [replacement],返回新内容
///
/// 这是"逐块解决"的核心算法,独立成纯函数以便测试:
/// - 只替换**该块的行范围**,前后内容原样保留(多块文件各块互不影响)
/// - 传入旧的 [blocks] 与 [content] 必须来自同一次解析,否则行号会错位
/// - [replacement] 为空表示"该块删掉"
///
/// 调用方应在替换后**重新解析**再处理下一块:块的行号会随替换而整体移动,
/// 维护偏移量容易出错,重解析代价可以忽略。
static String? replaceBlock({
required String content,
required List<GitConflictBlock> blocks,
required int blockIndex,
required String replacement,
}) {
if (blockIndex < 0 || blockIndex >= blocks.length) return null;
final lines = content.split('\n');
final block = blocks[blockIndex];
if (block.startLine < 0 || block.endLine >= lines.length) return null;
final before = lines.sublist(0, block.startLine);
final after = lines.sublist(block.endLine + 1);
final replacementLines =
replacement.isEmpty ? <String>[] : replacement.split('\n').toList();
// split 在内容以换行结尾时会多出一个空串,去掉以免多插空行
if (replacementLines.isNotEmpty && replacementLines.last.isEmpty) {
replacementLines.removeLast();
}
return <String>[...before, ...replacementLines, ...after].join('\n');
}
/// 统计内容中未解决的冲突块数量(不做完整解析,用于快速校验)
static int countMarkers(String content) => parse(content).blocks.length;
}
+15 -4
View File
@@ -197,10 +197,21 @@ class _FileItemWidgetState extends State<FileItemWidget> {
),
selected: isSelected,
selectedTileColor: theme.colorScheme.primaryContainer.withValues(alpha: 0.5),
leading: Icon(
_getFileIcon(item),
size: 20,
color: iconColor,
// 与文件夹项前导区对齐:文件夹有「折叠箭头 + 间距 + 图标」,
// 文件只有图标。若直接给图标,同一层级下文件图标会比文件夹图标
// 左移一个箭头的宽度(16+4),视觉上文件缩进反而更浅。
// 这里补一个等宽占位(区别于 VS Code:文件项不显示箭头),
// 使同一层级的图标与文件名严格对齐。
leading: Row(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(width: 16 + 4),
Icon(
_getFileIcon(item),
size: 20,
color: iconColor,
),
],
),
title: Text(
item.name,
+158
View File
@@ -0,0 +1,158 @@
/// 冲突页的行模型与内容组装(纯逻辑,便于单测)
///
/// 与 `git_conflict_parser.dart` 的分工:
/// - 解析器负责"标记块在文件中的位置"
/// - 这里负责"把解析结果摊平成一条条带语义的行",供 UI 直接渲染
///
/// 独立成文件的原因:VS Code 风格的内联冲突视图**完全由行渲染**组成
/// (标记行变标题带、内容行带整段底色),把"哪些行属于哪一段"算清楚
/// 是正确性的核心,而它必须可测 —— 上一版页面的内容错乱正是栽在
/// 行号映射上。
library;
import '../../utils/git_conflict_parser.dart';
/// 一行在冲突视图中的角色
enum ConflictLineRole {
/// 普通上下文行(不属于任何冲突块)
context,
/// 冲突块开头标记行(渲染为标题带 + 内联操作)
oursHeader,
/// 当前侧内容行
oursContent,
/// 基线段标题(diff3 风格;不显示操作)
baseHeader,
/// 基线段内容行
baseContent,
/// 分隔线(`=======`),渲染为极窄分隔
separator,
/// 传入侧标题带
theirsHeader,
/// 传入侧内容行
theirsContent,
}
/// 一行渲染数据
class ConflictLine {
/// 文件中的绝对行号(1-based,供行号栏显示)
final int lineNumber;
/// 该行的原始文本
final String text;
final ConflictLineRole role;
/// 若该行是一处分段的标题,这里给出它所属的冲突块序号(0-based)
final int? blockIndex;
const ConflictLine({
required this.lineNumber,
required this.text,
required this.role,
this.blockIndex,
});
bool get isHeader =>
role == ConflictLineRole.oursHeader ||
role == ConflictLineRole.baseHeader ||
role == ConflictLineRole.theirsHeader;
bool get isContent =>
role == ConflictLineRole.oursContent ||
role == ConflictLineRole.baseContent ||
role == ConflictLineRole.theirsContent;
}
/// 把冲突文件内容摊平成可渲染的行序列
class ConflictLineBuilder {
ConflictLineBuilder._();
/// 解析 [content] 并生成行序列
///
/// [parseResult] 必须与 [content] 来自同一次解析,否则行号会错位。
static List<ConflictLine> build(
String content,
GitConflictParseResult parseResult,
) {
final lines = content.split('\n');
final result = <ConflictLine>[];
// 行号 → 该行承担的段角色
final roles = List<ConflictLineRole?>.filled(lines.length, null);
final blockOfLine = List<int?>.filled(lines.length, null);
for (var b = 0; b < parseResult.blocks.length; b++) {
final block = parseResult.blocks[b];
void mark(int from, int toExclusive, ConflictLineRole role) {
for (var i = from; i < toExclusive; i++) {
if (i >= 0 && i < roles.length) {
roles[i] = role;
blockOfLine[i] = b;
}
}
}
// 起始标记行
mark(block.startLine, block.startLine + 1, ConflictLineRole.oursHeader);
// 当前侧内容
mark(
block.ours.startLine,
block.ours.endLine,
ConflictLineRole.oursContent,
);
if (block.base != null) {
// diff3:基线段(其上一行是 ||||||| 标记)
mark(
block.base!.startLine - 1,
block.base!.startLine,
ConflictLineRole.baseHeader,
);
mark(
block.base!.startLine,
block.base!.endLine,
ConflictLineRole.baseContent,
);
}
// 分隔线位于基线段结束处(有基线时)或 ours 结束处
final separatorLine = block.base != null
? block.base!.endLine
: block.ours.endLine;
mark(separatorLine, separatorLine + 1, ConflictLineRole.separator);
// 传入侧内容
mark(
block.theirs.startLine,
block.theirs.endLine,
ConflictLineRole.theirsContent,
);
// 结束标记行
mark(block.endLine, block.endLine + 1, ConflictLineRole.theirsHeader);
}
for (var i = 0; i < lines.length; i++) {
result.add(
ConflictLine(
lineNumber: i + 1,
text: lines[i],
role: roles[i] ?? ConflictLineRole.context,
blockIndex: blockOfLine[i],
),
);
}
return result;
}
/// 统计各块是否已解决(视图中没有标记块时即为完全解决)
static bool isFullyResolved(GitConflictParseResult parseResult) =>
parseResult.blocks.isEmpty;
}
+37 -7
View File
@@ -7,6 +7,7 @@ import '../../providers/git_provider.dart';
import '../../providers/tab_provider.dart';
import '../../utils/dialog_utils.dart';
import '../../utils/git_error_mapper.dart';
import 'git_conflict_resolve_page.dart';
/// 冲突解决面板(底部弹出)
///
@@ -380,11 +381,19 @@ class _ConflictFileTile extends StatelessWidget {
tooltip: l10n.gitConflictTitle,
onSelected: (action) => _handle(context, l10n, provider, action),
itemBuilder: (_) => [
if (file.canEditManually)
if (file.canEditManually) ...[
PopupMenuItem(
value: 'resolve',
child: _menuRow(
Icons.merge_type,
l10n.gitConflictResolveTitle,
),
),
PopupMenuItem(
value: 'open',
child: _menuRow(Icons.open_in_new_rounded, l10n.gitConflictOpenFile),
),
],
PopupMenuItem(
value: 'ours',
child: _menuRow(
@@ -415,8 +424,9 @@ class _ConflictFileTile extends StatelessWidget {
),
],
),
// 点击文件条目直接进入三方解决页(这是主要路径)
onTap: file.canEditManually
? () => _handle(context, l10n, provider, 'open')
? () => _openResolvePage(context, provider)
: null,
);
}
@@ -458,6 +468,9 @@ class _ConflictFileTile extends StatelessWidget {
String action,
) async {
switch (action) {
case 'resolve':
await _openResolvePage(context, provider);
break;
case 'open':
await _openInEditor(context, provider);
break;
@@ -500,6 +513,21 @@ class _ConflictFileTile extends StatelessWidget {
}
}
/// 打开三方冲突解决页(逐块选择,由程序替换而非人工删标记)
Future<void> _openResolvePage(BuildContext context, GitProvider provider) async {
await provider.refreshConflictState();
if (!context.mounted) return;
// 先收起面板与抽屉,再压入解决页 —— 否则返回时层级会错乱
Navigator.of(context).maybePop();
await Navigator.of(context).push(
GitConflictResolvePage.route(file: file, gitProvider: provider),
);
// 返回后刷新:用户可能已在解决页里标记完成
await provider.refreshConflictState();
}
/// 在编辑器中打开冲突文件
///
/// **必须先强制从磁盘重载**:Git 冲突时直接改写了工作区文件并写入标记,
@@ -509,11 +537,13 @@ class _ConflictFileTile extends StatelessWidget {
await provider.refreshConflictState();
await tabProvider.reloadTabFromDisk(file.absolutePath);
await tabProvider.openFile(file.absolutePath);
if (context.mounted) {
// 关闭面板并退出抽屉,把焦点交给编辑器
Navigator.of(context).maybePop();
Navigator.of(context).maybePop();
}
if (!context.mounted) return;
// 先收起 bottom sheet 面板,再显式关闭抽屉。
// 这里不能用连续两次 maybePop():抽屉是 Scaffold 管理的路由,
// 用 closeDrawer() 才是项目内一致且可靠的做法(见 file_item_widget)。
Navigator.of(context).maybePop();
Scaffold.maybeOf(context)?.closeDrawer();
}
Future<void> _takeSide(
File diff suppressed because it is too large. Load diff
+6 -5
View File
@@ -98,11 +98,6 @@ class _GitSyncBarState extends State<GitSyncBar> {
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
// 冲突优先于一切:此时同步动作都无法继续,必须先把冲突摆到最前面
if (gitProvider.hasPendingOperation) ...[
_buildConflictBanner(context, theme, l10n, gitProvider),
const SizedBox(height: 6),
],
// 与上方「分支」行完全一致的结构:左侧占满的选择条 + 右侧 32×32 图标按钮。
// 这样三行(分支 / 远程 / 进度)视觉对齐,宽度也天然不会溢出。
Row(
@@ -120,6 +115,12 @@ class _GitSyncBarState extends State<GitSyncBar> {
_buildSyncButton(context, theme, l10n, gitProvider),
],
),
// 冲突横幅放在远程行**下方**:它是一段需要处理的状态说明,
// 放在远程行之上会把「分支 → 远程」这两行的对应关系打断。
if (gitProvider.hasPendingOperation) ...[
const SizedBox(height: 6),
_buildConflictBanner(context, theme, l10n, gitProvider),
],
// 推送目标与上游不一致时的提示:单独占一行。
// 绝不能塞进上面的选择条 —— 那是第三个抢宽度的元素,会把远程名挤到溢出。
if (differs) ...[
+201
View File
@@ -0,0 +1,201 @@
import 'package:code_editor/utils/git_conflict_parser.dart';
import 'package:code_editor/widgets/git/conflict_view_model.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('冲突行模型(VS Code 内联视图的数据来源)', () {
const standard = 'line1\n'
'<<<<<<< HEAD\n'
'ours-a\n'
'ours-b\n'
'=======\n'
'theirs-a\n'
'>>>>>>> feature\n'
'line2';
test('标准风格:标记行变标题带、内容行归属正确', () {
final parsed = GitConflictParser.parse(standard);
final lines = ConflictLineBuilder.build(standard, parsed);
expect(lines.length, equals(8));
// 行号必须是文件绝对行号(1-based)——上一版页面正是栽在这里
expect(lines[0].lineNumber, equals(1));
expect(lines[0].role, equals(ConflictLineRole.context));
expect(lines[0].text, equals('line1'));
expect(lines[1].lineNumber, equals(2));
expect(lines[1].role, equals(ConflictLineRole.oursHeader));
expect(lines[1].isHeader, isTrue);
expect(lines[1].blockIndex, equals(0));
expect(lines[2].role, equals(ConflictLineRole.oursContent));
expect(lines[3].role, equals(ConflictLineRole.oursContent));
expect(lines[4].role, equals(ConflictLineRole.separator));
expect(lines[5].role, equals(ConflictLineRole.theirsContent));
expect(lines[6].role, equals(ConflictLineRole.theirsHeader));
expect(lines[6].blockIndex, equals(0));
expect(lines[7].role, equals(ConflictLineRole.context));
expect(lines[7].text, equals('line2'));
});
test('标题带行保留 git 原始标记文本', () {
final parsed = GitConflictParser.parse(standard);
final lines = ConflictLineBuilder.build(standard, parsed);
expect(lines[1].text, equals('<<<<<<< HEAD'));
expect(lines[6].text, equals('>>>>>>> feature'));
});
test('diff3 风格:基线段被单独标注,且不参与操作', () {
const diff3 = 'head\n'
'<<<<<<< HEAD\n'
'ours\n'
'||||||| merged common ancestors\n'
'base\n'
'=======\n'
'theirs\n'
'>>>>>>> x\n'
'tail';
final parsed = GitConflictParser.parse(diff3);
expect(parsed.blocks.first.hasBaseSegment, isTrue);
final lines = ConflictLineBuilder.build(diff3, parsed);
final baseHeader = lines.firstWhere(
(l) => l.role == ConflictLineRole.baseHeader,
);
final baseContent = lines.firstWhere(
(l) => l.role == ConflictLineRole.baseContent,
);
expect(baseHeader.text, contains('|||||||'));
expect(baseContent.text, equals('base'));
expect(baseContent.lineNumber, equals(5));
// 基线段不应被当作可操作侧
expect(baseContent.role, isNot(equals(ConflictLineRole.oursContent)));
expect(baseContent.role, isNot(equals(ConflictLineRole.theirsContent)));
});
test('多个冲突块各自带正确 blockIndex,互不串位', () {
const two = 'a\n'
'<<<<<<< HEAD\n'
'o1\n'
'=======\n'
't1\n'
'>>>>>>> x\n'
'b\n'
'<<<<<<< HEAD\n'
'o2\n'
'=======\n'
't2\n'
'>>>>>>> x\n'
'c';
final parsed = GitConflictParser.parse(two);
final lines = ConflictLineBuilder.build(two, parsed);
final headers = lines.where((l) => l.isHeader).toList();
expect(headers.length, equals(4));
expect(headers[0].blockIndex, equals(0));
expect(headers[1].blockIndex, equals(0));
expect(headers[2].blockIndex, equals(1));
expect(headers[3].blockIndex, equals(1));
// 上下文行不属于任何块
final contexts = lines.where((l) => l.role == ConflictLineRole.context);
expect(contexts.every((l) => l.blockIndex == null), isTrue);
});
test('行号连续覆盖整个文件,不丢行不多行', () {
final parsed = GitConflictParser.parse(standard);
final lines = ConflictLineBuilder.build(standard, parsed);
for (var i = 0; i < lines.length; i++) {
expect(lines[i].lineNumber, equals(i + 1));
}
expect(lines.length, equals(standard.split('\n').length));
});
test('空段(一侧无内容)不产生内容行但标题与分隔仍在', () {
const emptyOurs = '<<<<<<< HEAD\n'
'=======\n'
'theirs-only\n'
'>>>>>>> x';
final parsed = GitConflictParser.parse(emptyOurs);
final lines = ConflictLineBuilder.build(emptyOurs, parsed);
expect(lines.length, equals(4));
expect(lines[0].role, equals(ConflictLineRole.oursHeader));
expect(lines[1].role, equals(ConflictLineRole.separator));
expect(lines[2].role, equals(ConflictLineRole.theirsContent));
expect(lines[3].role, equals(ConflictLineRole.theirsHeader));
// 没有 oursContent 行
expect(
lines.any((l) => l.role == ConflictLineRole.oursContent),
isFalse,
);
});
test('无冲突文件全部是上下文行', () {
const clean = 'a\nb\nc';
final parsed = GitConflictParser.parse(clean);
final lines = ConflictLineBuilder.build(clean, parsed);
expect(lines.length, equals(3));
expect(
lines.every((l) => l.role == ConflictLineRole.context),
isTrue,
);
expect(ConflictLineBuilder.isFullyResolved(parsed), isTrue);
});
test('结构异常的标记不被当成冲突块,行仍全部输出', () {
const malformed = '<<<<<<< HEAD\nours\n';
final parsed = GitConflictParser.parse(malformed);
expect(parsed.isMalformed, isTrue);
final lines = ConflictLineBuilder.build(malformed, parsed);
// 解析失败时不应伪造标题带,全部按上下文渲染(用户会看到原始标记文本)
expect(lines.every((l) => l.role == ConflictLineRole.context), isTrue);
expect(lines.length, equals(malformed.split('\n').length));
expect(lines.length, equals(3));
});
});
group('段落文本提取(按绝对行号切分)', () {
test('从块范围取当前侧与传入侧文本', () {
const content = 'line1\n'
'<<<<<<< HEAD\n'
'ours-a\n'
'ours-b\n'
'=======\n'
'theirs-a\n'
'>>>>>>> feature\n'
'line2';
final parsed = GitConflictParser.parse(content);
final lines = content.split('\n');
final block = parsed.blocks.first;
String seg(int from, int to) =>
lines.sublist(from.clamp(0, lines.length), to.clamp(0, lines.length)).join('\n');
expect(seg(block.ours.startLine, block.ours.endLine), equals('ours-a\nours-b'));
expect(seg(block.theirs.startLine, block.theirs.endLine), equals('theirs-a'));
});
test('段落行号越界时被钳制而不是抛异常', () {
const content = '<<<<<<< HEAD\nours\n=======\n';
final parsed = GitConflictParser.parse(content);
// 该内容结构不完整,应被判定为 malformed(不产生块)
expect(parsed.isMalformed, isTrue);
expect(parsed.blocks, isEmpty);
});
});
}
+161
View File
@@ -243,4 +243,165 @@ void main() {
expect(block.theirsLabel, contains('1a2b3c4'));
});
});
group('逐块替换(解决冲突的核心算法)', () {
const twoBlocks = 'header\n'
'<<<<<<< HEAD\n'
'ours-1\n'
'=======\n'
'theirs-1\n'
'>>>>>>> x\n'
'middle\n'
'<<<<<<< HEAD\n'
'ours-2\n'
'=======\n'
'theirs-2\n'
'>>>>>>> x\n'
'footer';
test('替换第一个块只影响该块范围,其余原样保留', () {
final parsed = GitConflictParser.parse(twoBlocks);
expect(parsed.blocks.length, equals(2));
final result = GitConflictParser.replaceBlock(
content: twoBlocks,
blocks: parsed.blocks,
blockIndex: 0,
replacement: 'RESOLVED-1',
);
expect(result, isNotNull);
expect(result!, contains('header'));
expect(result, contains('RESOLVED-1'));
expect(result, contains('middle'));
expect(result, contains('footer'));
// 第一个块的标记没了
expect(result, isNot(contains('ours-1')));
expect(result, isNot(contains('theirs-1')));
// 第二个块完好无损
expect(result, contains('ours-2'));
expect(result, contains('theirs-2'));
});
test('替换第二个块时第一个块不受影响', () {
final parsed = GitConflictParser.parse(twoBlocks);
final result = GitConflictParser.replaceBlock(
content: twoBlocks,
blocks: parsed.blocks,
blockIndex: 1,
replacement: 'RESOLVED-2',
);
expect(result, isNotNull);
expect(result!, contains('ours-1'));
expect(result, contains('theirs-1'));
expect(result, contains('RESOLVED-2'));
expect(result, isNot(contains('ours-2')));
});
test('替换为空字符串即删除该块内容', () {
final parsed = GitConflictParser.parse(twoBlocks);
final result = GitConflictParser.replaceBlock(
content: twoBlocks,
blocks: parsed.blocks,
blockIndex: 0,
replacement: '',
);
expect(result, isNotNull);
// 块内容被整段移除,剩下 header/middle/第二个块/footer
expect(result!.split('\n')[0], equals('header'));
expect(result.split('\n')[1], equals('middle'));
expect(result, isNot(contains('ours-1')));
});
test('多行替换内容保留全部行', () {
final parsed = GitConflictParser.parse(twoBlocks);
final result = GitConflictParser.replaceBlock(
content: twoBlocks,
blocks: parsed.blocks,
blockIndex: 0,
replacement: 'line-a\nline-b\nline-c',
);
expect(result, isNotNull);
expect(result!, contains('line-a\nline-b\nline-c'));
});
test('末尾空串不会多插空行', () {
final parsed = GitConflictParser.parse(twoBlocks);
final result = GitConflictParser.replaceBlock(
content: twoBlocks,
blocks: parsed.blocks,
blockIndex: 0,
replacement: 'only\n',
);
// 'only\n' 应等价于 'only'
final result2 = GitConflictParser.replaceBlock(
content: twoBlocks,
blocks: parsed.blocks,
blockIndex: 0,
replacement: 'only',
);
expect(result, equals(result2));
});
test('越界索引返回 null 而不是破坏内容', () {
final parsed = GitConflictParser.parse(twoBlocks);
expect(
GitConflictParser.replaceBlock(
content: twoBlocks,
blocks: parsed.blocks,
blockIndex: 5,
replacement: 'x',
),
isNull,
);
expect(
GitConflictParser.replaceBlock(
content: twoBlocks,
blocks: parsed.blocks,
blockIndex: -1,
replacement: 'x',
),
isNull,
);
});
test('逐个替换两块后不再有标记', () {
// 模拟用户逐块点选:每替换一次都重新解析(行号会移动)
var content = twoBlocks;
var parsed = GitConflictParser.parse(content);
expect(parsed.blocks.length, equals(2));
content = GitConflictParser.replaceBlock(
content: content,
blocks: parsed.blocks,
blockIndex: 0,
replacement: 'R1',
)!;
parsed = GitConflictParser.parse(content);
expect(parsed.blocks.length, equals(1), reason: '重解析后应只剩一块');
content = GitConflictParser.replaceBlock(
content: content,
blocks: parsed.blocks,
blockIndex: 0,
replacement: 'R2',
)!;
parsed = GitConflictParser.parse(content);
expect(parsed.blocks, isEmpty);
expect(content, contains('R1'));
expect(content, contains('R2'));
// 全部标记清除
expect(content, isNot(contains('<<<<<<<')));
expect(content, isNot(contains('>>>>>>>')));
});
test('countMarkers 快速统计残留块数', () {
expect(GitConflictParser.countMarkers(twoBlocks), equals(2));
expect(GitConflictParser.countMarkers('clean file\n'), equals(0));
});
});
}