This commit is contained in:
LZX committed 2026-09-16 20:43:39 +08:00
1 parent 5efc778165
commit 59125d185c
64 files changed
+7912 -1393

No files matched your search

@@ -1,296 +1,209 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path/path.dart' as p;
import '../../models/notice_item.dart';
import '../../models/run_task.dart';
import 'gradle_ide_model.dart';
import 'project_module.dart';
import 'project_probe.dart';
/// 专门负责 Gradle 项目全自动深度自省与任务构建的模块
/// Gradle 项目模块:通过 init script 获取**结构化模型**来搜索真实任务。
///
/// 与旧实现的区别:
/// * 不再解析 `gradle tasks --all` 的人类可读文本(正则/分组启发式全部删除);
/// * 不再返回任何硬编码兜底任务:探测失败就如实返回失败分类 + 细节;
/// * 先在后台上完成工具链定位与探测脚本准备(warmUp),再正式探测(probe)。
class GradleProjectModule extends ProjectModule {
/// 探测模型文件(init script 输出,位于工程 .code_editor 内,容器内同为 /workspace)
static const String modelFileName = 'gradle_ide_model.json';
/// init script 在工程内的落盘路径(相对工程根)
static const String initScriptRelativePath = '.code_editor/code_editor_model.init.gradle';
@override
String get id => 'gradle';
@override
String get displayName => 'Gradle';
@override
bool get supportsResync => true;
/// Gradle 依赖:`gradle` 这条工具链需求的 checkBinary 就是 `java`
/// (Gradle 本身是 JVM 程序,没有 JDK 连启动都做不到,所以自动补全 = 装 JDK)。
@override
List<String> get requiredToolchainKeys => const ['gradle'];
@override
List<String> get triggerFiles => const [
'build.gradle',
'build.gradle.kts',
'settings.gradle',
'settings.gradle.kts',
'gradlew',
];
'build.gradle',
'build.gradle.kts',
'settings.gradle',
'settings.gradle.kts',
'gradlew',
];
@override
bool shouldActivate(Directory projectDir) {
return triggerFiles.any((f) => File(p.join(projectDir.path, f)).existsSync());
}
/// 环境准备:把结构化探测脚本写入工程 .code_editor/
@override
Future<List<RunTask>> detect(ProjectModuleContext context, {bool forceRefresh = false}) async {
final projectDir = context.projectDir;
final currentHash = computeBuildScriptHash(projectDir);
// 1. 优先读取持久化缓存
if (!forceRefresh) {
final cached = await context.storageService.loadModuleTasks(projectDir.path, id);
if (cached.tasks.isNotEmpty && cached.hash == currentHash) {
debugPrint('[GradleProjectModule] 命中 ${projectDir.path} 真实任务缓存 (共 ${cached.tasks.length} 项)');
return cached.tasks;
}
}
// 2. 发起真实容器静默探测
final execCmd = File(p.join(projectDir.path, 'gradlew')).existsSync() ? 'sh ./gradlew' : 'gradle';
try {
debugPrint('[GradleProjectModule] 开始在容器后台执行真实 Gradle Task 自省...');
final result = await context.runHeadless(
'$execCmd tasks --all --console=plain -q',
timeout: const Duration(seconds: 90),
);
if (result != null && result.exitCode == 0 && result.stdout.toString().trim().isNotEmpty) {
final tasks = parseGradleTasksOutput(result.stdout.toString(), execCmd);
if (tasks.isNotEmpty) {
debugPrint('[GradleProjectModule] 成功解析到 ${tasks.length} 个真实 Gradle 任务,正在持久化写入缓存...');
await context.storageService.saveModuleTasks(
projectRoot: projectDir.path,
moduleName: id,
tasks: tasks,
hash: currentHash,
);
return tasks;
}
} else {
debugPrint('[GradleProjectModule] 静默自省退出码非0或无输出: exitCode=${result?.exitCode}, stderr=${result?.stderr}');
}
} catch (e) {
debugPrint('[GradleProjectModule] 静默自省异常: $e');
}
// 3. 兜底保障:若未生成缓存且静默执行暂不可用(如离线或环境未准备好),回退至预置核心常用任务
return fallbackDefaultTasks(projectDir, execCmd);
Future<void> prepare(ProjectProbe probe) async {
await _ensureInitScript(probe.projectDir);
}
/// 计算构建脚本的综合指纹哈希(用于智能感知构建文件变更并使缓存失效)
static String computeBuildScriptHash(Directory projectDir) {
final buffer = StringBuffer();
final candidateFiles = [
'build.gradle',
'build.gradle.kts',
'settings.gradle',
'settings.gradle.kts',
'gradle.properties',
];
@override
Future<ModuleProbeResult> probe(ProjectProbe probe) async {
if (probe.isCancelled) return ModuleProbeResult.cancelled(id);
for (final fileName in candidateFiles) {
final file = File(p.join(projectDir.path, fileName));
if (file.existsSync()) {
final projectDir = probe.projectDir;
// 系统任务不落盘:每次都跑真实自省(模块结果只写入内存任务表)
// 1. 没有 wrapper 时必须存在 gradle 可执行文件(JDK 由总调度的依赖检测/自动补全保证)
final hasWrapper = _wrapperExists(projectDir);
if (!hasWrapper) {
final hasGradle = await probe.hasCommand('gradle');
if (!hasGradle) {
return ModuleProbeResult.failed(
id,
failure: NoticeFailure.toolchainMissing,
detail: 'gradle',
);
}
}
final execCmd = hasWrapper ? 'sh ./gradlew' : 'gradle';
try {
await _ensureInitScript(projectDir);
final modelFile = File(p.join(projectDir.path, '.code_editor', modelFileName));
// 清理上一次的结果,避免读到陈旧模型
if (modelFile.existsSync()) {
try {
final stat = file.statSync();
buffer.write('$fileName:${stat.size}:${stat.modified.millisecondsSinceEpoch};');
modelFile.deleteSync();
} catch (_) {}
}
}
return buffer.toString();
}
/// 解析 `./gradlew tasks --all --console=plain -q` 的纯文本输出
static List<RunTask> parseGradleTasksOutput(String output, String execCmd) {
final List<RunTask> tasks = [];
final lines = LineSplitter.split(output).toList();
String currentProjectPrefix = '';
String currentGroup = 'other';
bool inTasksSection = false;
for (int i = 0; i < lines.length; i++) {
final line = lines[i].trim();
if (line.isEmpty) continue;
// 匹配项目标题行,形如:
// "Tasks runnable from root project 'demo'" 或 "Tasks runnable from project ':app'"
final projectMatch = RegExp(r"Tasks runnable from (?:root )?project '([^']+)'").firstMatch(line);
if (projectMatch != null) {
final proj = projectMatch.group(1)!;
if (proj.startsWith(':')) {
currentProjectPrefix = '$proj:';
} else {
currentProjectPrefix = '';
}
inTasksSection = true;
continue;
}
// 遇到 Rules 或非任务分段时跳过
if (line == 'Rules' || line.startsWith('Pattern:')) {
inTasksSection = false;
continue;
}
// 忽略单纯的分割线 (如 ------------------------------------------------------------)
if (RegExp(r'^[-=]{3,}$').hasMatch(line)) {
continue;
}
// 匹配分组名称与下划线分割,例如:
// Build tasks
// -----------
if (i + 1 < lines.length && RegExp(r'^-{3,}$').hasMatch(lines[i + 1].trim())) {
final groupMatch = RegExp(r'^([a-zA-Z0-9_\s]+)\s+tasks$', caseSensitive: false).firstMatch(line);
if (groupMatch != null) {
currentGroup = groupMatch.group(1)!.trim().toLowerCase();
inTasksSection = true;
i++; // 跳过下划线行
continue;
ProcessResult? result = await _runModelCommand(probe, execCmd, offline: false);
if (!_isSuccess(result) && !probe.isCancelled) {
debugPrint('[GradleProjectModule] 在线结构化探测未成功 (exit=${result?.exitCode}),尝试 --offline 重试');
final offlineResult = await _runModelCommand(probe, execCmd, offline: true);
if (_isSuccess(offlineResult) || offlineResult?.exitCode == -1) {
result = offlineResult;
} else if (offlineResult != null) {
final offlineErr = _stderrTail(offlineResult.stderr);
result = (offlineErr != null && offlineErr.isNotEmpty) ? offlineResult : (result ?? offlineResult);
}
}
if (!inTasksSection) continue;
if (probe.isCancelled) return ModuleProbeResult.cancelled(id);
// 匹配单个任务定义,例如:
// assemble - Assembles the outputs of this project.
// 或没有描述的任务:myCustomTask (任务名必须以字母/数字/冒号开头)
final taskMatch = RegExp(r'^([a-zA-Z0-9:][a-zA-Z0-9_:\-]*)(?:\s+-\s+(.*))?$').firstMatch(line);
if (taskMatch != null) {
final rawTaskName = taskMatch.group(1)!;
final description = taskMatch.group(2)?.trim();
// 避免重复解析分组标题
if (rawTaskName.toLowerCase().endsWith('tasks')) continue;
final fullTaskName = rawTaskName.startsWith(':')
? rawTaskName
: (currentProjectPrefix.isNotEmpty ? '$currentProjectPrefix$rawTaskName' : rawTaskName);
final taskId = 'gradle_${fullTaskName.replaceAll(':', '_')}';
final taskGroup = _normalizeGroup(currentGroup, fullTaskName);
final icon = _selectIconForTask(fullTaskName, taskGroup);
tasks.add(RunTask(
id: taskId,
name: fullTaskName,
command: '$execCmd $fullTaskName',
source: TaskSource.detected,
description: description ?? 'Gradle task: $fullTaskName',
group: taskGroup,
moduleId: 'gradle',
icon: icon,
));
if (!modelFile.existsSync() || modelFile.lengthSync() == 0) {
if (!_isSuccess(result)) {
// exitCode == -1:容器内命令被超时 kill(DistroManager 的 onTimeout 约定)
if (result != null && result.exitCode == -1) {
return ModuleProbeResult.failed(id, failure: NoticeFailure.timeout);
}
return ModuleProbeResult.failed(
id,
failure: NoticeFailure.executionFailed,
detail: _stderrTail(result?.stderr),
);
}
final detail = _stderrTail(result?.stderr) ?? _stderrTail(result?.stdout);
return ModuleProbeResult.failed(
id,
failure: NoticeFailure.unparsable,
detail: detail,
);
}
}
// 按任务分组与名称进行合理排序(常用 Build / Application / Verification 优先展示)
tasks.sort((a, b) {
final rankA = _groupPriority(a.group ?? '');
final rankB = _groupPriority(b.group ?? '');
if (rankA != rankB) {
return rankA.compareTo(rankB);
final raw = await modelFile.readAsString();
final decoded = jsonDecode(raw);
if (decoded is! Map) {
return ModuleProbeResult.failed(id, failure: NoticeFailure.unparsable);
}
final model = GradleIdeModel.fromJson(Map<String, dynamic>.from(decoded));
if (model.error != null && model.error!.isNotEmpty) {
return ModuleProbeResult.failed(
id,
failure: NoticeFailure.executionFailed,
detail: model.error,
);
}
return a.name.compareTo(b.name);
});
return tasks;
}
final tasks = model.toRunTasks(execCmd);
if (tasks.isEmpty) {
// 探测成功但工程确实没有任何任务:如实返回空(不伪造)
return ModuleProbeResult.ok(id, const <RunTask>[]);
}
/// 兜底默认任务集(在未联网同步真实任务前呈现)
static List<RunTask> fallbackDefaultTasks(Directory projectDir, String execCmd) {
return [
RunTask(
id: 'detected_gradle_run',
name: 'run',
command: '$execCmd run',
source: TaskSource.detected,
description: 'Execute application main entrypoint',
group: 'application',
moduleId: 'gradle',
icon: Icons.play_circle_outline,
),
RunTask(
id: 'detected_gradle_assemble',
name: 'assembleDebug',
command: '$execCmd assembleDebug',
source: TaskSource.detected,
description: 'Build debug output package',
group: 'build',
moduleId: 'gradle',
icon: Icons.build_outlined,
),
RunTask(
id: 'detected_gradle_build',
name: 'build',
command: '$execCmd build',
source: TaskSource.detected,
description: 'Execute full build and tests',
group: 'build',
moduleId: 'gradle',
icon: Icons.build_outlined,
),
RunTask(
id: 'detected_gradle_clean',
name: 'clean',
command: '$execCmd clean',
source: TaskSource.detected,
description: 'Clean project build outputs',
group: 'build',
moduleId: 'gradle',
icon: Icons.cleaning_services_outlined,
),
];
}
static String _normalizeGroup(String group, String taskName) {
final g = group.trim().toLowerCase();
if (g.contains('build')) return 'build';
if (g.contains('application') || g.contains('run')) return 'application';
if (g.contains('verification') || g.contains('test') || g.contains('check')) return 'verification';
if (g.contains('documentation') || g.contains('doc')) return 'documentation';
if (g.contains('help')) return 'help';
if (g.contains('android')) return 'android';
return g.isEmpty ? 'other' : g;
}
static int _groupPriority(String group) {
switch (group) {
case 'application':
return 1;
case 'build':
return 2;
case 'android':
return 3;
case 'verification':
return 4;
case 'documentation':
return 5;
case 'other':
return 6;
case 'help':
return 7;
default:
return 8;
debugPrint(
'[GradleProjectModule] 结构化探测成功: gradle=${model.gradleVersion} '
'projects=${model.projects.length} tasks=${tasks.length}');
return ModuleProbeResult.ok(id, tasks);
} catch (e) {
debugPrint('[GradleProjectModule] 结构化探测异常: $e');
return ModuleProbeResult.failed(
id,
failure: NoticeFailure.unparsable,
detail: '$e',
);
}
}
static IconData _selectIconForTask(String taskName, String group) {
final lower = taskName.toLowerCase();
if (lower.contains('run') || lower.contains('start')) {
return Icons.play_circle_outline;
/// 缓存指纹 = 缓存 schema 版本 + 构建脚本指纹
// 说明:系统任务不再落盘,因此构建脚本指纹与模块缓存读写一并移除。
bool _wrapperExists(Directory projectDir) =>
File(p.join(projectDir.path, 'gradlew')).existsSync();
/// 把探测脚本写入工程 .code_editor/(容器内 /workspace/.code_editor/...)
Future<void> _ensureInitScript(Directory projectDir) async {
try {
final content = await rootBundle.loadString('assets/gradle/code_editor_model.init.gradle');
final target = File(p.join(projectDir.path, initScriptRelativePath));
final parent = target.parent;
if (!parent.existsSync()) {
parent.createSync(recursive: true);
}
if (!target.existsSync() || target.readAsStringSync() != content) {
target.writeAsStringSync(content, flush: true);
debugPrint('[GradleProjectModule] 已写入结构化探测脚本: ${target.path}');
}
} catch (e) {
debugPrint('[GradleProjectModule] 写入探测脚本失败: $e');
}
if (lower.contains('clean')) {
return Icons.cleaning_services_outlined;
}
if (lower.contains('test') || lower.contains('check') || lower.contains('lint')) {
return Icons.fact_check_outlined;
}
if (group == 'build' || lower.contains('assemble') || lower.contains('bundle') || lower.contains('build') || lower.contains('compile')) {
return Icons.build_outlined;
}
if (group == 'help' || lower.contains('help') || lower.contains('info')) {
return Icons.help_outline;
}
return Icons.terminal_outlined;
}
Future<ProcessResult?> _runModelCommand(
ProjectProbe probe,
String execCmd, {
required bool offline,
}) {
final offlineFlag = offline ? ' --offline' : '';
// 强制英文输出(避免本地化文本影响任何诊断信息),-q 抑制无关日志;
// 模型本体通过 .code_editor/gradle_ide_model.json 回传,不依赖 stdout。
// 在容器(PRoot)环境中必须显式传递 --no-daemon 并关闭配置缓存(-Dorg.gradle.configuration-cache=false):
// 1. 避免残留孤儿 JVM 守护进程或锁文件损坏导致后续调用连接超时/拒绝;
// 2. 避免配置缓存复用直接跳过 projectsEvaluated 项目评估导致不生成模型文件。
return probe.runHeadless(
'LC_ALL=C LANG=C $execCmd --no-daemon -Dorg.gradle.configuration-cache=false --console=plain -q -I $initScriptRelativePath help$offlineFlag',
timeout: const Duration(seconds: 90),
);
}
bool _isSuccess(ProcessResult? result) =>
result != null && result.exitCode == 0;
String? _stderrTail(Object? stderr) {
final text = stderr?.toString().trim() ?? '';
if (text.isEmpty) return null;
const maxLength = 240;
return text.length <= maxLength ? text : '…${text.substring(text.length - maxLength)}';
}
}