1
This commit is contained in:
1 parent
5efc778165
commit
59125d185c
64 files changed
+7912
-1393
No files matched your search
@@ -0,0 +1,104 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import '../../models/run_task.dart';
|
||||
import 'project_module.dart';
|
||||
import 'project_probe.dart';
|
||||
|
||||
/// Cargo (Rust) 工程模块:真实读取 Cargo.toml 的 [[bin]] 定义
|
||||
class CargoProjectModule extends ProjectModule {
|
||||
@override
|
||||
String get id => 'cargo';
|
||||
|
||||
@override
|
||||
String get displayName => 'Cargo';
|
||||
|
||||
@override
|
||||
List<String> get triggerFiles => const ['Cargo.toml'];
|
||||
|
||||
@override
|
||||
bool shouldActivate(Directory projectDir) =>
|
||||
File(p.join(projectDir.path, 'Cargo.toml')).existsSync();
|
||||
|
||||
@override
|
||||
List<String> get requiredToolchainKeys => const ['cargo'];
|
||||
|
||||
@override
|
||||
Future<ModuleProbeResult> probe(ProjectProbe probe) async {
|
||||
if (probe.isCancelled) return ModuleProbeResult.cancelled(id);
|
||||
final bins = _declaredBinaryNames(probe.projectDir);
|
||||
return ModuleProbeResult.ok(id, [
|
||||
// 显式声明的二进制目标优先展示(真实读取 [[bin]] name)
|
||||
for (final bin in bins)
|
||||
RunTask(
|
||||
id: 'cargo_run_$bin',
|
||||
name: 'Cargo: Run $bin',
|
||||
command: 'cargo run --bin $bin',
|
||||
source: TaskSource.detected,
|
||||
group: 'application',
|
||||
moduleId: id,
|
||||
icon: Icons.play_circle_outline,
|
||||
),
|
||||
RunTask(
|
||||
id: 'detected_cargo_run',
|
||||
name: 'Cargo: Run',
|
||||
command: 'cargo run',
|
||||
source: TaskSource.detected,
|
||||
group: 'application',
|
||||
moduleId: id,
|
||||
icon: Icons.play_circle_outline,
|
||||
),
|
||||
RunTask(
|
||||
id: 'detected_cargo_build',
|
||||
name: 'Cargo: Build',
|
||||
command: 'cargo build',
|
||||
source: TaskSource.detected,
|
||||
group: 'build',
|
||||
moduleId: id,
|
||||
icon: Icons.build_outlined,
|
||||
),
|
||||
RunTask(
|
||||
id: 'cargo_test',
|
||||
name: 'Cargo: Test',
|
||||
command: 'cargo test',
|
||||
source: TaskSource.detected,
|
||||
group: 'verification',
|
||||
moduleId: id,
|
||||
icon: Icons.fact_check_outlined,
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
/// 从 Cargo.toml 提取 [[bin]] name(结构化读取)
|
||||
static List<String> _declaredBinaryNames(Directory projectDir) {
|
||||
try {
|
||||
final file = File(p.join(projectDir.path, 'Cargo.toml'));
|
||||
if (!file.existsSync()) return const [];
|
||||
final content = file.readAsStringSync();
|
||||
final names = <String>[];
|
||||
var inBinSection = false;
|
||||
for (final rawLine in content.split('\n')) {
|
||||
final commentIdx = rawLine.indexOf('#');
|
||||
final lineWithoutComment = commentIdx != -1 ? rawLine.substring(0, commentIdx) : rawLine;
|
||||
final line = lineWithoutComment.trim();
|
||||
if (line.isEmpty) continue;
|
||||
if (line.startsWith('[')) {
|
||||
inBinSection = RegExp(r'^\[\[\s*bin\s*\]\]$').hasMatch(line);
|
||||
continue;
|
||||
}
|
||||
if (inBinSection && line.startsWith('name')) {
|
||||
final parts = line.split('=');
|
||||
if (parts.length >= 2) {
|
||||
final value = parts[1].trim().replaceAll('"', '').replaceAll("'", '').trim();
|
||||
if (value.isNotEmpty && !names.contains(value)) names.add(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
} catch (_) {
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import '../../models/run_task.dart';
|
||||
import 'project_module.dart';
|
||||
import 'project_probe.dart';
|
||||
|
||||
/// CMake 工程模块:工具链在目标系统内可用时才产出任务
|
||||
class CMakeProjectModule extends ProjectModule {
|
||||
@override
|
||||
String get id => 'cmake';
|
||||
|
||||
@override
|
||||
String get displayName => 'CMake';
|
||||
|
||||
@override
|
||||
List<String> get triggerFiles => const ['CMakeLists.txt'];
|
||||
|
||||
@override
|
||||
bool shouldActivate(Directory projectDir) =>
|
||||
File(p.join(projectDir.path, 'CMakeLists.txt')).existsSync();
|
||||
|
||||
@override
|
||||
List<String> get requiredToolchainKeys => const ['cmake'];
|
||||
|
||||
@override
|
||||
Future<ModuleProbeResult> probe(ProjectProbe probe) async {
|
||||
if (probe.isCancelled) return ModuleProbeResult.cancelled(id);
|
||||
final targetName = _detectExecutableTarget(probe.projectDir) ?? p.basename(probe.projectDir.path);
|
||||
final safeTarget = targetName.replaceAll("'", r"'\''");
|
||||
return ModuleProbeResult.ok(id, [
|
||||
RunTask(
|
||||
id: 'detected_cmake_build_run',
|
||||
name: 'CMake: Build & Run',
|
||||
command: "cmake -B build && cmake --build build && './build/$safeTarget'",
|
||||
source: TaskSource.detected,
|
||||
group: 'build',
|
||||
moduleId: id,
|
||||
icon: Icons.play_circle_outline,
|
||||
),
|
||||
RunTask(
|
||||
id: 'detected_cmake_build',
|
||||
name: 'CMake: Build Only',
|
||||
command: 'cmake -B build && cmake --build build',
|
||||
source: TaskSource.detected,
|
||||
group: 'build',
|
||||
moduleId: id,
|
||||
icon: Icons.build_outlined,
|
||||
),
|
||||
RunTask(
|
||||
id: 'detected_cmake_clean',
|
||||
name: 'CMake: Clean',
|
||||
command: 'rm -rf build',
|
||||
source: TaskSource.detected,
|
||||
group: 'build',
|
||||
moduleId: id,
|
||||
icon: Icons.cleaning_services_outlined,
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
/// 从 CMakeLists.txt 尝试提取首个 add_executable(target ...) 目标名
|
||||
static String? _detectExecutableTarget(Directory projectDir) {
|
||||
try {
|
||||
final cmakeFile = File(p.join(projectDir.path, 'CMakeLists.txt'));
|
||||
if (!cmakeFile.existsSync()) return null;
|
||||
final content = cmakeFile.readAsStringSync();
|
||||
final match = RegExp(
|
||||
r'add_executable\s*\(\s*([A-Za-z0-9_.\-]+)',
|
||||
caseSensitive: false,
|
||||
).firstMatch(content);
|
||||
return match?.group(1);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import '../../models/notice_item.dart';
|
||||
import '../../models/run_task.dart';
|
||||
import 'project_module.dart';
|
||||
import 'project_probe.dart';
|
||||
|
||||
/// Dart (pubspec.yaml) 工程模块
|
||||
class DartProjectModule extends ProjectModule {
|
||||
@override
|
||||
String get id => 'dart';
|
||||
|
||||
@override
|
||||
String get displayName => 'Dart';
|
||||
|
||||
@override
|
||||
List<String> get triggerFiles => const ['pubspec.yaml'];
|
||||
|
||||
@override
|
||||
bool shouldActivate(Directory projectDir) =>
|
||||
File(p.join(projectDir.path, 'pubspec.yaml')).existsSync();
|
||||
|
||||
/// Dart SDK 目前没有可用的发行版一键安装命令,因此不做自动补全,
|
||||
/// 仅在探测阶段如实报告"未找到 dart"。
|
||||
@override
|
||||
Future<ModuleProbeResult> probe(ProjectProbe probe) async {
|
||||
if (probe.isCancelled) return ModuleProbeResult.cancelled(id);
|
||||
final available = await probe.hasCommand('dart');
|
||||
if (!available) {
|
||||
return const ModuleProbeResult.failed(
|
||||
'dart',
|
||||
failure: NoticeFailure.toolchainMissing,
|
||||
detail: 'dart',
|
||||
);
|
||||
}
|
||||
return ModuleProbeResult.ok(id, [
|
||||
RunTask(
|
||||
id: 'detected_dart_run',
|
||||
name: 'Dart: Run',
|
||||
command: 'dart run',
|
||||
source: TaskSource.detected,
|
||||
group: 'application',
|
||||
moduleId: id,
|
||||
icon: Icons.play_circle_outline,
|
||||
),
|
||||
RunTask(
|
||||
id: 'dart_test',
|
||||
name: 'Dart: Test',
|
||||
command: 'dart test',
|
||||
source: TaskSource.detected,
|
||||
group: 'verification',
|
||||
moduleId: id,
|
||||
icon: Icons.fact_check_outlined,
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../models/run_task.dart';
|
||||
|
||||
/// Gradle 结构化模型(由 init script 输出到 .code_editor/gradle_ide_model.json)
|
||||
///
|
||||
/// 这是"真正意义上搜索任务"的数据来源:任务名/路径/分组/描述/类型、
|
||||
/// 以及 sourceSets、插件、配置名等后续做依赖导入所需要的信息,全部按字段读取,
|
||||
/// 不再依赖任何人类可读文本输出与正则。
|
||||
class GradleIdeModel {
|
||||
static const int schemaVersion = 1;
|
||||
|
||||
final int schema;
|
||||
final String? gradleVersion;
|
||||
final String rootProject;
|
||||
final List<GradleIdeProject> projects;
|
||||
|
||||
/// init script 内部异常时回填的错误信息(schema == 0)
|
||||
final String? error;
|
||||
|
||||
const GradleIdeModel({
|
||||
required this.schema,
|
||||
required this.rootProject,
|
||||
required this.projects,
|
||||
this.gradleVersion,
|
||||
this.error,
|
||||
});
|
||||
|
||||
/// 解析失败时抛 [FormatException](调用方归类为 probeFailureUnparsable)
|
||||
static GradleIdeModel fromJson(Map<String, dynamic> json) {
|
||||
final schema = _asInt(json['schema']) ?? 0;
|
||||
if (schema == 0 && json.containsKey('error')) {
|
||||
throw FormatException(json['error']?.toString() ?? 'unexpected gradle ide model schema: 0');
|
||||
}
|
||||
if (schema != schemaVersion) {
|
||||
throw FormatException('unexpected gradle ide model schema: $schema');
|
||||
}
|
||||
final rawProjects = json['projects'];
|
||||
final projects = <GradleIdeProject>[];
|
||||
if (rawProjects is List) {
|
||||
for (final item in rawProjects) {
|
||||
if (item is Map) {
|
||||
projects.add(GradleIdeProject.fromJson(Map<String, dynamic>.from(item)));
|
||||
}
|
||||
}
|
||||
}
|
||||
return GradleIdeModel(
|
||||
schema: schema,
|
||||
gradleVersion: json['gradleVersion']?.toString(),
|
||||
rootProject: json['rootProject']?.toString() ?? '',
|
||||
projects: projects,
|
||||
error: json['error']?.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
/// 转换为可执行任务列表
|
||||
List<RunTask> toRunTasks(String execCmd) {
|
||||
final tasks = <RunTask>[];
|
||||
final seen = <String>{};
|
||||
|
||||
for (final project in projects) {
|
||||
final isRoot = project.path == ':' || project.path.isEmpty;
|
||||
for (final task in project.tasks) {
|
||||
// 根工程的 task.path 形如 ':assemble',展示与 id 均沿用旧的命名习惯,
|
||||
// 保证既有用户数据(最近运行记录等)不失效。
|
||||
final fullName = isRoot ? task.name : (task.path.isNotEmpty ? task.path : ':${task.name}');
|
||||
if (!seen.add(fullName)) continue;
|
||||
|
||||
final group = _normalizeGroup(task.group, fullName);
|
||||
tasks.add(RunTask(
|
||||
id: 'gradle_${fullName.replaceAll(':', '_')}',
|
||||
name: fullName,
|
||||
command: '$execCmd $fullName',
|
||||
source: TaskSource.detected,
|
||||
description: task.description,
|
||||
group: group,
|
||||
moduleId: 'gradle',
|
||||
icon: _selectIconForTask(fullName, group),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
tasks.sort((a, b) {
|
||||
final rankA = _groupPriority(a.group ?? '');
|
||||
final rankB = _groupPriority(b.group ?? '');
|
||||
if (rankA != rankB) return rankA.compareTo(rankB);
|
||||
return a.name.compareTo(b.name);
|
||||
});
|
||||
return tasks;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
static IconData _selectIconForTask(String taskName, String group) {
|
||||
final lower = taskName.toLowerCase();
|
||||
if (lower.contains('run') || lower.contains('start')) {
|
||||
return Icons.play_circle_outline;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
static int? _asInt(Object? value) {
|
||||
if (value is int) return value;
|
||||
if (value is num) return value.toInt();
|
||||
if (value is String) return int.tryParse(value);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个 Gradle 工程(含子模块)
|
||||
class GradleIdeProject {
|
||||
final String path;
|
||||
final String name;
|
||||
final String? description;
|
||||
final String? buildFile;
|
||||
final List<String> plugins;
|
||||
final List<String> sourceSets;
|
||||
final List<String> configurations;
|
||||
final String? javaVersion;
|
||||
final List<GradleIdeTask> tasks;
|
||||
|
||||
const GradleIdeProject({
|
||||
required this.path,
|
||||
required this.name,
|
||||
this.description,
|
||||
this.buildFile,
|
||||
this.plugins = const [],
|
||||
this.sourceSets = const [],
|
||||
this.configurations = const [],
|
||||
this.javaVersion,
|
||||
this.tasks = const [],
|
||||
});
|
||||
|
||||
static GradleIdeProject fromJson(Map<String, dynamic> json) {
|
||||
return GradleIdeProject(
|
||||
path: json['path']?.toString() ?? ':',
|
||||
name: json['name']?.toString() ?? '',
|
||||
description: json['description']?.toString(),
|
||||
buildFile: json['buildFile']?.toString(),
|
||||
plugins: _stringList(json['plugins']),
|
||||
sourceSets: _stringList(json['sourceSets']),
|
||||
configurations: _stringList(json['configurations']),
|
||||
javaVersion: json['javaVersion']?.toString(),
|
||||
tasks: [
|
||||
for (final item in (json['tasks'] as List? ?? const []))
|
||||
if (item is Map) GradleIdeTask.fromJson(Map<String, dynamic>.from(item)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
static List<String> _stringList(Object? value) {
|
||||
if (value is! List) return const [];
|
||||
return [for (final item in value) item.toString()];
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个 Gradle 任务
|
||||
class GradleIdeTask {
|
||||
final String name;
|
||||
final String path;
|
||||
final String? group;
|
||||
final String? description;
|
||||
final String? type;
|
||||
|
||||
const GradleIdeTask({
|
||||
required this.name,
|
||||
required this.path,
|
||||
this.group,
|
||||
this.description,
|
||||
this.type,
|
||||
});
|
||||
|
||||
static GradleIdeTask fromJson(Map<String, dynamic> json) {
|
||||
return GradleIdeTask(
|
||||
name: json['name']?.toString() ?? '',
|
||||
path: json['path']?.toString() ?? '',
|
||||
group: json['group']?.toString(),
|
||||
description: json['description']?.toString(),
|
||||
type: json['type']?.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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)}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import '../../models/run_task.dart';
|
||||
import 'project_module.dart';
|
||||
import 'project_probe.dart';
|
||||
|
||||
/// Makefile 工程模块:真实解析 Makefile 目标 + 工具链检查
|
||||
class MakeProjectModule extends ProjectModule {
|
||||
@override
|
||||
String get id => 'make';
|
||||
|
||||
@override
|
||||
String get displayName => 'Makefile';
|
||||
|
||||
@override
|
||||
List<String> get triggerFiles => const ['Makefile'];
|
||||
|
||||
@override
|
||||
bool shouldActivate(Directory projectDir) =>
|
||||
File(p.join(projectDir.path, 'Makefile')).existsSync();
|
||||
|
||||
@override
|
||||
List<String> get requiredToolchainKeys => const ['make'];
|
||||
|
||||
@override
|
||||
Future<ModuleProbeResult> probe(ProjectProbe probe) async {
|
||||
if (probe.isCancelled) return ModuleProbeResult.cancelled(id);
|
||||
final targets = _readTargets(probe.projectDir);
|
||||
return ModuleProbeResult.ok(
|
||||
id,
|
||||
[
|
||||
RunTask(
|
||||
id: 'detected_make_default',
|
||||
name: 'Make: Default',
|
||||
command: 'make',
|
||||
source: TaskSource.detected,
|
||||
group: 'build',
|
||||
moduleId: id,
|
||||
icon: Icons.build_circle_outlined,
|
||||
),
|
||||
for (final target in targets)
|
||||
RunTask(
|
||||
id: 'make_$target',
|
||||
name: 'make $target',
|
||||
command: 'make $target',
|
||||
source: TaskSource.detected,
|
||||
group: _groupForTarget(target),
|
||||
moduleId: id,
|
||||
icon: _iconForTarget(target),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
static String _groupForTarget(String target) {
|
||||
final lower = target.toLowerCase();
|
||||
if (lower.startsWith('test') || lower.startsWith('check') || lower.contains('lint')) {
|
||||
return 'verification';
|
||||
}
|
||||
return 'build';
|
||||
}
|
||||
|
||||
static IconData _iconForTarget(String target) {
|
||||
final lower = target.toLowerCase();
|
||||
if (lower == 'clean') return Icons.cleaning_services_outlined;
|
||||
if (lower.startsWith('test') || lower.startsWith('check') || lower.contains('lint')) {
|
||||
return Icons.fact_check_outlined;
|
||||
}
|
||||
return Icons.build_outlined;
|
||||
}
|
||||
|
||||
/// 解析 Makefile 中显式声明的目标名(跳过变量赋值与特殊目标)
|
||||
static List<String> _readTargets(Directory projectDir) {
|
||||
try {
|
||||
final file = File(p.join(projectDir.path, 'Makefile'));
|
||||
if (!file.existsSync()) return const [];
|
||||
final result = <String>[];
|
||||
final pattern = RegExp(r'^([A-Za-z0-9_][A-Za-z0-9_.\-]*)\s*:(?!=)');
|
||||
for (final rawLine in file.readAsLinesSync()) {
|
||||
if (rawLine.startsWith('\t') || rawLine.trimLeft().startsWith('#')) continue;
|
||||
final match = pattern.firstMatch(rawLine);
|
||||
if (match == null) continue;
|
||||
final target = match.group(1)!;
|
||||
if (target == 'default' || result.contains(target)) continue;
|
||||
result.add(target);
|
||||
}
|
||||
return result;
|
||||
} catch (_) {
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import '../../models/run_task.dart';
|
||||
import 'project_module.dart';
|
||||
import 'project_probe.dart';
|
||||
|
||||
/// NPM (Node / Web) 工程模块:真实读取 package.json 的 scripts
|
||||
class NpmProjectModule extends ProjectModule {
|
||||
@override
|
||||
String get id => 'npm';
|
||||
|
||||
@override
|
||||
String get displayName => 'NPM';
|
||||
|
||||
@override
|
||||
List<String> get triggerFiles => const ['package.json'];
|
||||
|
||||
@override
|
||||
bool shouldActivate(Directory projectDir) =>
|
||||
File(p.join(projectDir.path, 'package.json')).existsSync();
|
||||
|
||||
@override
|
||||
List<String> get requiredToolchainKeys => const ['npm'];
|
||||
|
||||
@override
|
||||
Future<ModuleProbeResult> probe(ProjectProbe probe) async {
|
||||
if (probe.isCancelled) return ModuleProbeResult.cancelled(id);
|
||||
final scripts = _readScripts(probe.projectDir);
|
||||
if (scripts.isEmpty) {
|
||||
return ModuleProbeResult.ok(id, const <RunTask>[]);
|
||||
}
|
||||
return ModuleProbeResult.ok(
|
||||
id,
|
||||
[
|
||||
for (final name in scripts)
|
||||
RunTask(
|
||||
// start / test 沿用历史 id 以复用已有的多语言描述
|
||||
id: switch (name) {
|
||||
'start' => 'detected_npm_start',
|
||||
'test' => 'detected_npm_test',
|
||||
_ => 'npm_$name',
|
||||
},
|
||||
name: 'npm run $name',
|
||||
command: 'npm run $name',
|
||||
source: TaskSource.detected,
|
||||
group: _groupForScript(name),
|
||||
moduleId: id,
|
||||
icon: _iconForScript(name),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// 解析 package.json 的 scripts(结构化读取,不做文本解析)
|
||||
static List<String> _readScripts(Directory projectDir) {
|
||||
try {
|
||||
final file = File(p.join(projectDir.path, 'package.json'));
|
||||
if (!file.existsSync()) return const [];
|
||||
final decoded = jsonDecode(file.readAsStringSync());
|
||||
if (decoded is! Map) return const [];
|
||||
final scripts = decoded['scripts'];
|
||||
if (scripts is! Map) return const [];
|
||||
return [for (final key in scripts.keys) key.toString()];
|
||||
} catch (_) {
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
|
||||
static String _groupForScript(String name) {
|
||||
final lower = name.toLowerCase();
|
||||
if (lower.startsWith('test') || lower.contains('lint') || lower.contains('check')) {
|
||||
return 'verification';
|
||||
}
|
||||
if (lower.startsWith('build')) return 'build';
|
||||
return 'application';
|
||||
}
|
||||
|
||||
static IconData _iconForScript(String name) {
|
||||
final group = _groupForScript(name);
|
||||
if (group == 'verification') return Icons.fact_check_outlined;
|
||||
if (group == 'build') return Icons.build_outlined;
|
||||
return Icons.play_circle_outline;
|
||||
}
|
||||
}
|
||||
@@ -1,61 +1,59 @@
|
||||
import 'dart:io';
|
||||
import '../../models/run_task.dart';
|
||||
import '../distro_manager.dart';
|
||||
import '../run_task_storage_service.dart';
|
||||
|
||||
/// 传递给各项目探测模块的上下文环境
|
||||
class ProjectModuleContext {
|
||||
/// 工程根目录
|
||||
final Directory projectDir;
|
||||
import '../toolchain_service.dart';
|
||||
import 'project_probe.dart';
|
||||
|
||||
/// 当前在编辑器中激活的文件路径(宿主绝对路径,可能为 null)
|
||||
final String? currentFilePath;
|
||||
|
||||
/// 容器系统名称(默认为 'ubuntu' 或当前激活的容器)
|
||||
final String systemName;
|
||||
|
||||
/// 任务持久化存储服务
|
||||
final RunTaskStorageService storageService;
|
||||
|
||||
/// 容器管理器
|
||||
final DistroManager distroManager;
|
||||
|
||||
const ProjectModuleContext({
|
||||
required this.projectDir,
|
||||
this.currentFilePath,
|
||||
this.systemName = 'ubuntu',
|
||||
required this.storageService,
|
||||
required this.distroManager,
|
||||
});
|
||||
|
||||
/// 在容器后台静默执行命令并捕获输出
|
||||
Future<ProcessResult?> runHeadless(
|
||||
String command, {
|
||||
Duration timeout = const Duration(seconds: 120),
|
||||
}) {
|
||||
return distroManager.runHeadlessCommand(
|
||||
systemName: systemName,
|
||||
workspacePath: projectDir.path,
|
||||
command: command,
|
||||
timeout: timeout,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 项目探测模块接口(对标 VS Code TaskProvider)
|
||||
/// 项目探测模块接口(对标 VS Code TaskProvider / IDE 的 ProjectModel 提供者)
|
||||
///
|
||||
/// 总调度按**队列线性执行**驱动每个模块,每个模块依次做三个动作:
|
||||
/// 1. [prepare] + [checkDependencies]:环境准备与**依赖检测**(返回缺失的依赖 key);
|
||||
/// 2. [installDependencies]:**自动补全**缺失依赖(默认实现 = 复用容器内发行版安装命令);
|
||||
/// 3. [probe]:**执行探测**,返回结构化结果。
|
||||
///
|
||||
/// 约定:
|
||||
/// * 模块不得返回任何硬编码兜底任务;探测失败就如实返回 failed;
|
||||
/// * 模块不得自行猜测执行环境,一切执行都通过 [ProjectProbe] 提供的当前系统会话;
|
||||
/// * 依赖必须声明为 [requiredToolchainKeys](键取自 [ToolchainService.supportedTools]),
|
||||
/// 这样"自动补全"才能拿到对应发行版的安装命令。
|
||||
abstract class ProjectModule {
|
||||
/// 模块唯一标识(如 'gradle', 'cmake', 'cargo', 'npm' 等)
|
||||
String get id;
|
||||
|
||||
/// 模块友好展示名称
|
||||
/// 模块展示名(用于 UI 文案插值,如 'Gradle')
|
||||
String get displayName;
|
||||
|
||||
/// 该项目特有的特征标记文件(命中其中任意一个才激活本探测器)
|
||||
List<String> get triggerFiles;
|
||||
|
||||
/// 快速判断当前工程是否匹配本模块(毫秒级,只检测文件存在与否,不进行深层解析)
|
||||
/// 是否支持"重新同步真实任务"
|
||||
bool get supportsResync => false;
|
||||
|
||||
/// 需要的工具链依赖 key(对应 [ToolchainService.supportedTools] 的键)
|
||||
List<String> get requiredToolchainKeys => const [];
|
||||
|
||||
/// 快速判断当前工程是否匹配本模块(毫秒级,只检测文件存在与否)
|
||||
bool shouldActivate(Directory projectDir);
|
||||
|
||||
/// 探测项目任务(支持优先读取本地缓存;当 forceRefresh=true 时强制发起真实探测)
|
||||
Future<List<RunTask>> detect(ProjectModuleContext context, {bool forceRefresh = false});
|
||||
/// 环境准备(写探测脚本、准备临时目录等),在依赖检测前执行。默认无操作。
|
||||
Future<void> prepare(ProjectProbe probe) async {}
|
||||
|
||||
/// 依赖检测:返回缺失的依赖 key 列表。默认实现按 [requiredToolchainKeys] 逐个检查。
|
||||
Future<List<String>> checkDependencies(ProjectProbe probe) async {
|
||||
final missing = <String>[];
|
||||
for (final key in requiredToolchainKeys) {
|
||||
final requirement = ToolchainService.supportedTools[key];
|
||||
if (requirement == null) continue;
|
||||
final installed = await probe.isToolchainInstalled(requirement);
|
||||
if (!installed) missing.add(key);
|
||||
}
|
||||
return missing;
|
||||
}
|
||||
|
||||
/// 自动补全缺失依赖:默认实现调用容器内安装(按发行版家族合成命令)。
|
||||
Future<bool> installDependencies(ProjectProbe probe, List<String> missing) {
|
||||
return probe.installToolchains(missing);
|
||||
}
|
||||
|
||||
/// 执行探测(结构化结果)
|
||||
Future<ModuleProbeResult> probe(ProjectProbe probe);
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../models/notice_item.dart';
|
||||
import '../../models/run_task.dart';
|
||||
import '../distro_manager.dart';
|
||||
import '../toolchain_service.dart';
|
||||
|
||||
/// 探测阶段(队列线性执行:入队 → 依赖检测 → 自动补全 → 执行探测 → 整理)
|
||||
enum ProbePhase { queued, checkingDependency, installingDependency, probing, finalizing }
|
||||
|
||||
/// 一次探测涉及的模块引用(供 UI 建通知条目)
|
||||
@immutable
|
||||
class ProbeModuleRef {
|
||||
final String id;
|
||||
final String displayName;
|
||||
|
||||
const ProbeModuleRef(this.id, this.displayName);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is ProbeModuleRef && other.id == id && other.displayName == displayName;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(id, displayName);
|
||||
}
|
||||
|
||||
/// 探测进度快照(队列线性执行:当前模块 + 队列全貌)
|
||||
@immutable
|
||||
class ProbeProgress {
|
||||
final ProbePhase phase;
|
||||
|
||||
/// 本轮队列中的全部模块(含已完成/排队中)
|
||||
final List<ProbeModuleRef> queue;
|
||||
|
||||
/// 当前正在执行三动作的模块
|
||||
final ProbeModuleRef? current;
|
||||
|
||||
const ProbeProgress({
|
||||
required this.phase,
|
||||
required this.queue,
|
||||
this.current,
|
||||
});
|
||||
}
|
||||
|
||||
/// 模块探测结果状态
|
||||
enum ModuleProbeStatus {
|
||||
/// 成功(可能 0 个任务,但探测本身成功)
|
||||
ok,
|
||||
|
||||
/// 探测失败(工具链缺失 / 依赖安装失败 / 执行失败 / 输出不可解析 / 超时)
|
||||
failed,
|
||||
|
||||
/// 被用户取消
|
||||
cancelled,
|
||||
|
||||
/// 因整轮探测超出时间预算而被跳过(尚未开始执行)
|
||||
skippedByBudget,
|
||||
}
|
||||
|
||||
/// 单个模块的探测结果(结构化,失败必须显式携带原因)
|
||||
@immutable
|
||||
class ModuleProbeResult {
|
||||
final String moduleId;
|
||||
final ModuleProbeStatus status;
|
||||
final List<RunTask> tasks;
|
||||
|
||||
/// 失败分类(用于 l10n 文案),status != failed 时为 null
|
||||
final NoticeFailure? failure;
|
||||
|
||||
/// 失败细节:缺失的工具名、stderr 末尾等(技术信息,允许原样展示)
|
||||
final String? failureDetail;
|
||||
|
||||
const ModuleProbeResult._({
|
||||
required this.moduleId,
|
||||
required this.status,
|
||||
this.tasks = const <RunTask>[],
|
||||
this.failure,
|
||||
this.failureDetail,
|
||||
});
|
||||
|
||||
const ModuleProbeResult.ok(String moduleId, List<RunTask> tasks)
|
||||
: this._(moduleId: moduleId, status: ModuleProbeStatus.ok, tasks: tasks);
|
||||
|
||||
const ModuleProbeResult.failed(
|
||||
String moduleId, {
|
||||
required NoticeFailure failure,
|
||||
String? detail,
|
||||
}) : this._(
|
||||
moduleId: moduleId,
|
||||
status: ModuleProbeStatus.failed,
|
||||
failure: failure,
|
||||
failureDetail: detail,
|
||||
);
|
||||
|
||||
const ModuleProbeResult.cancelled(String moduleId)
|
||||
: this._(moduleId: moduleId, status: ModuleProbeStatus.cancelled);
|
||||
|
||||
const ModuleProbeResult.skippedByBudget(String moduleId)
|
||||
: this._(moduleId: moduleId, status: ModuleProbeStatus.skippedByBudget);
|
||||
}
|
||||
|
||||
/// 探测请求
|
||||
@immutable
|
||||
class ProjectProbeRequest {
|
||||
final Directory projectDir;
|
||||
final String? currentFilePath;
|
||||
|
||||
/// 当前真实选中的容器系统名(必需)
|
||||
final String systemName;
|
||||
|
||||
/// 仅探测指定模块(用于"重新同步真实任务")
|
||||
final String? onlyModuleId;
|
||||
|
||||
const ProjectProbeRequest({
|
||||
required this.projectDir,
|
||||
required this.systemName,
|
||||
this.currentFilePath,
|
||||
this.onlyModuleId,
|
||||
});
|
||||
}
|
||||
|
||||
/// 探测报告:聚合所有模块结果 + 最终任务列表
|
||||
@immutable
|
||||
class ProjectProbeReport {
|
||||
final String systemName;
|
||||
final List<RunTask> detectedTasks;
|
||||
final Map<String, ModuleProbeResult> moduleResults;
|
||||
final DateTime finishedAt;
|
||||
|
||||
/// 本轮队列涉及的模块总数(用于"已完成 X/Y 个模块"文案)
|
||||
final int totalModules;
|
||||
|
||||
/// 是否因超出时间预算而中止
|
||||
final bool abortedByBudget;
|
||||
|
||||
const ProjectProbeReport({
|
||||
required this.systemName,
|
||||
required this.detectedTasks,
|
||||
required this.moduleResults,
|
||||
required this.finishedAt,
|
||||
this.totalModules = 0,
|
||||
this.abortedByBudget = false,
|
||||
});
|
||||
|
||||
static ProjectProbeReport empty(String systemName) => ProjectProbeReport(
|
||||
systemName: systemName,
|
||||
detectedTasks: const <RunTask>[],
|
||||
moduleResults: const <String, ModuleProbeResult>{},
|
||||
finishedAt: DateTime.now(),
|
||||
);
|
||||
|
||||
/// 真正跑完(成功或失败)的模块数,不含被跳过/被取消的
|
||||
int get completedModules => moduleResults.values
|
||||
.where((r) => r.status == ModuleProbeStatus.ok || r.status == ModuleProbeStatus.failed)
|
||||
.length;
|
||||
|
||||
bool get hasFailure =>
|
||||
moduleResults.values.any((r) => r.status == ModuleProbeStatus.failed);
|
||||
}
|
||||
|
||||
/// 一次探测会话:承载进度、取消、缓存读写与容器执行能力。
|
||||
///
|
||||
/// 依赖能力(供模块的"依赖检测 / 自动补全"两个动作使用):
|
||||
/// * [isToolchainInstalled]:优先在宿主 rootfs 内快速判定,必要时回落到容器 `command -v`;
|
||||
/// * [installToolchains]:按发行版家族复用 [ToolchainService] 的安装命令,
|
||||
/// 带长超时、可取消、逐行回传输出(供弹窗显示安装进度)。
|
||||
class ProjectProbe {
|
||||
/// 整轮探测的默认时间预算:超过后不再出队新模块(剩余模块标记为"预算跳过")
|
||||
static const Duration defaultBudget = Duration(minutes: 15);
|
||||
|
||||
final ProjectProbeRequest request;
|
||||
final DistroManager distroManager;
|
||||
|
||||
/// 本轮探测的时间预算
|
||||
final Duration budget;
|
||||
|
||||
/// 取消令牌(取消后容器内的子进程会被立即杀掉)
|
||||
final HeadlessCancelToken cancelToken;
|
||||
|
||||
/// 进度(null 表示已结束)
|
||||
final ValueNotifier<ProbeProgress?> progress;
|
||||
|
||||
/// 安装过程最后一行输出(供弹窗副标题显示安装进度)
|
||||
final ValueNotifier<String?> installLine;
|
||||
|
||||
bool _disposed = false;
|
||||
DateTime? _deadline;
|
||||
|
||||
ProjectProbe({
|
||||
required this.request,
|
||||
required this.distroManager,
|
||||
this.budget = defaultBudget,
|
||||
HeadlessCancelToken? cancelToken,
|
||||
ValueNotifier<ProbeProgress?>? progress,
|
||||
ValueNotifier<String?>? installLine,
|
||||
}) : cancelToken = cancelToken ?? HeadlessCancelToken(),
|
||||
progress = progress ?? ValueNotifier<ProbeProgress?>(null),
|
||||
installLine = installLine ?? ValueNotifier<String?>(null);
|
||||
|
||||
Directory get projectDir => request.projectDir;
|
||||
String? get currentFilePath => request.currentFilePath;
|
||||
String get systemName => request.systemName;
|
||||
String? get onlyModuleId => request.onlyModuleId;
|
||||
bool get isCancelled => cancelToken.isCancelled;
|
||||
bool get isDisposed => _disposed;
|
||||
|
||||
/// 开始计时(由总调度在真正开跑时调用,排队/等待用户的时间不计入预算)
|
||||
void startBudget([Duration? override]) {
|
||||
_deadline = DateTime.now().add(override ?? budget);
|
||||
}
|
||||
|
||||
/// 已耗时(未开始计时返回 Duration.zero)
|
||||
Duration get elapsed {
|
||||
final deadline = _deadline;
|
||||
if (deadline == null) return Duration.zero;
|
||||
final remaining = deadline.difference(DateTime.now());
|
||||
final used = budget - remaining;
|
||||
return used.isNegative ? Duration.zero : used;
|
||||
}
|
||||
|
||||
/// 是否已超出时间预算
|
||||
bool get isBudgetExceeded {
|
||||
final deadline = _deadline;
|
||||
if (deadline == null) return false;
|
||||
return DateTime.now().isAfter(deadline);
|
||||
}
|
||||
|
||||
void cancel() => cancelToken.cancel();
|
||||
|
||||
/// 在容器内静默执行命令(带取消支持 + 可选逐行输出)
|
||||
Future<ProcessResult?> runHeadless(
|
||||
String command, {
|
||||
Duration timeout = const Duration(seconds: 90),
|
||||
void Function(String chunk)? onStdout,
|
||||
}) {
|
||||
return distroManager.runHeadlessCommand(
|
||||
systemName: systemName,
|
||||
workspacePath: projectDir.path,
|
||||
command: command,
|
||||
timeout: timeout,
|
||||
cancelToken: cancelToken,
|
||||
onStdout: onStdout,
|
||||
);
|
||||
}
|
||||
|
||||
/// 容器内是否存在指定二进制(无法确认且未被取消时返回 true,避免受限/单测环境误报缺失)
|
||||
Future<bool> hasCommand(String binary) async {
|
||||
if (isCancelled) return false;
|
||||
final result = await runHeadless(
|
||||
'command -v $binary >/dev/null 2>&1 && echo CE_OK',
|
||||
timeout: const Duration(seconds: 20),
|
||||
);
|
||||
if (isCancelled) return false;
|
||||
if (result == null) return true;
|
||||
return result.exitCode == 0 && result.stdout.toString().contains('CE_OK');
|
||||
}
|
||||
|
||||
/// 依赖是否已安装(优先宿主侧 rootfs 快速判定,失败再回落容器检查)
|
||||
Future<bool> isToolchainInstalled(ToolchainRequirement requirement) async {
|
||||
if (isCancelled) return false;
|
||||
try {
|
||||
final rootDir = await distroManager.getSystemRootDir(systemName);
|
||||
if (rootDir.existsSync()) {
|
||||
return ToolchainService.isToolInstalledInRootfs(rootDir, requirement.checkBinary);
|
||||
}
|
||||
} catch (_) {
|
||||
// 宿主信息不可用 -> 回落容器内检查
|
||||
}
|
||||
return hasCommand(requirement.checkBinary);
|
||||
}
|
||||
|
||||
/// 自动补全依赖:按发行版家族合成安装命令并在容器内执行
|
||||
///
|
||||
/// 队列是线性执行的,因此同一时刻只会有一次安装,天然不会与其它模块争抢包管理器锁。
|
||||
/// 同一批缺失依赖合并成一条脚本执行(只取一次包管理器锁、只 update 一次)。
|
||||
Future<bool> installToolchains(List<String> toolchainKeys) async {
|
||||
if (isCancelled || _disposed || toolchainKeys.isEmpty) return false;
|
||||
|
||||
final DistroFamily family;
|
||||
try {
|
||||
family = await distroManager.detectDistroFamily(systemName);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
if (family == DistroFamily.unknown) return false;
|
||||
|
||||
final commands = <String>[];
|
||||
for (final key in toolchainKeys) {
|
||||
final requirement = ToolchainService.supportedTools[key];
|
||||
final command = requirement?.getInstallCommand(family);
|
||||
if (command != null && command.trim().isNotEmpty) {
|
||||
commands.add(command);
|
||||
}
|
||||
}
|
||||
if (commands.isEmpty) return false;
|
||||
|
||||
final script = commands.join(' && ');
|
||||
final result = await runHeadless(
|
||||
script,
|
||||
timeout: const Duration(minutes: 10),
|
||||
onStdout: (chunk) {
|
||||
final line = chunk.trim();
|
||||
if (line.isNotEmpty) setInstallLine(line);
|
||||
},
|
||||
);
|
||||
return result != null && result.exitCode == 0;
|
||||
}
|
||||
|
||||
/// 更新安装进度行(带释放保护,避免取消/释放后写入已 dispose 的 notifier)
|
||||
void setInstallLine(String? line) {
|
||||
if (_disposed) return;
|
||||
installLine.value = line;
|
||||
}
|
||||
|
||||
void reportProgress(ProbeProgress value) {
|
||||
if (isCancelled || _disposed) return;
|
||||
progress.value = value;
|
||||
}
|
||||
|
||||
/// 释放(幂等:取消与正常结束路径都可能调用)
|
||||
void dispose() {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
progress.dispose();
|
||||
installLine.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import '../../models/run_task.dart';
|
||||
|
||||
/// 单文件任务探测器:针对当前编辑器正在打开的单文件,生成开箱即用的轻量运行任务。
|
||||
///
|
||||
/// 包含 8 类语言后缀的独立检测与执行指令安全封装:
|
||||
/// 1. Python (.py)
|
||||
/// 2. C (.c)
|
||||
/// 3. C++ (.cpp, .cc, .cxx)
|
||||
/// 4. Shell (.sh, .bash)
|
||||
/// 5. Dart (.dart)
|
||||
/// 6. Go (.go)
|
||||
/// 7. Rust (.rs)
|
||||
/// 8. Node.js (.js)
|
||||
class SingleFileTaskDetector {
|
||||
/// 所有支持的单文件后缀集合(全小写)
|
||||
static const Set<String> supportedExtensions = {
|
||||
'.py',
|
||||
'.c',
|
||||
'.cpp',
|
||||
'.cc',
|
||||
'.cxx',
|
||||
'.sh',
|
||||
'.bash',
|
||||
'.dart',
|
||||
'.go',
|
||||
'.rs',
|
||||
'.js',
|
||||
};
|
||||
|
||||
/// 检查给定文件路径是否属于支持的单文件任务类型
|
||||
static bool isSupported(String filePath) {
|
||||
final ext = p.extension(filePath).toLowerCase();
|
||||
return supportedExtensions.contains(ext);
|
||||
}
|
||||
|
||||
/// 探测单文件运行指令(基于当前打开的文件)
|
||||
static RunTask? detect(String projectRoot, String currentFilePath) {
|
||||
final file = File(currentFilePath);
|
||||
if (!file.existsSync()) return null;
|
||||
|
||||
// 边界:只有位于工程根目录内的文件才有意义。
|
||||
// 容器里挂载为 /workspace 的正是工程根,工程外的文件在容器内不存在,
|
||||
// 生成的 "../xxx" 路径必然执行失败,因此直接不产出单文件任务。
|
||||
if (!p.isWithin(projectRoot, currentFilePath)) return null;
|
||||
|
||||
final fileName = p.basename(currentFilePath);
|
||||
final ext = p.extension(currentFilePath).toLowerCase();
|
||||
|
||||
String relPath = p.relative(currentFilePath, from: projectRoot).replaceAll(r'\', '/');
|
||||
if (!relPath.startsWith('./') && !relPath.startsWith('/')) {
|
||||
relPath = './$relPath';
|
||||
}
|
||||
|
||||
// 安全转义 Shell 路径参数(单引号包裹并转义内部单引号,彻底阻断 $ 变量展开与特殊字符)
|
||||
final escapedRelPath = "'${relPath.replaceAll("'", r"'\''")}'";
|
||||
|
||||
switch (ext) {
|
||||
case '.py':
|
||||
return RunTask(
|
||||
id: 'detected_single_python',
|
||||
name: 'Python: $fileName',
|
||||
command: 'python3 $escapedRelPath',
|
||||
source: TaskSource.detected,
|
||||
group: 'single_file',
|
||||
icon: Icons.code,
|
||||
);
|
||||
case '.c':
|
||||
return RunTask(
|
||||
id: 'detected_single_c',
|
||||
name: 'GCC: $fileName',
|
||||
command: 'gcc $escapedRelPath -lm -o /tmp/a.out && /tmp/a.out',
|
||||
source: TaskSource.detected,
|
||||
group: 'single_file',
|
||||
icon: Icons.terminal,
|
||||
);
|
||||
case '.cpp':
|
||||
case '.cc':
|
||||
case '.cxx':
|
||||
return RunTask(
|
||||
id: 'detected_single_cpp',
|
||||
name: 'G++: $fileName',
|
||||
command: 'g++ $escapedRelPath -o /tmp/a.out && /tmp/a.out',
|
||||
source: TaskSource.detected,
|
||||
group: 'single_file',
|
||||
icon: Icons.terminal,
|
||||
);
|
||||
case '.sh':
|
||||
case '.bash':
|
||||
return RunTask(
|
||||
id: 'detected_single_sh',
|
||||
name: 'Shell: $fileName',
|
||||
command: 'sh $escapedRelPath',
|
||||
source: TaskSource.detected,
|
||||
group: 'single_file',
|
||||
icon: Icons.terminal,
|
||||
);
|
||||
case '.dart':
|
||||
return RunTask(
|
||||
id: 'detected_single_dart',
|
||||
name: 'Dart: $fileName',
|
||||
command: 'dart run $escapedRelPath',
|
||||
source: TaskSource.detected,
|
||||
group: 'single_file',
|
||||
icon: Icons.code,
|
||||
);
|
||||
case '.go':
|
||||
return RunTask(
|
||||
id: 'detected_single_go',
|
||||
name: 'Go: $fileName',
|
||||
command: 'go run $escapedRelPath',
|
||||
source: TaskSource.detected,
|
||||
group: 'single_file',
|
||||
icon: Icons.code,
|
||||
);
|
||||
case '.rs':
|
||||
return RunTask(
|
||||
id: 'detected_single_rust',
|
||||
name: 'Rust: $fileName',
|
||||
command: 'rustc $escapedRelPath -o /tmp/a.out && /tmp/a.out',
|
||||
source: TaskSource.detected,
|
||||
group: 'single_file',
|
||||
icon: Icons.code,
|
||||
);
|
||||
case '.js':
|
||||
return RunTask(
|
||||
id: 'detected_single_js',
|
||||
name: 'Node: $fileName',
|
||||
command: 'node $escapedRelPath',
|
||||
source: TaskSource.detected,
|
||||
group: 'single_file',
|
||||
icon: Icons.javascript,
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,211 +1,9 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import '../../models/run_task.dart';
|
||||
import 'project_module.dart';
|
||||
/// 各标准工程模块的导出聚合文件(保持向后兼容)
|
||||
library;
|
||||
|
||||
/// CMake 工程探测模块
|
||||
class CMakeProjectModule extends ProjectModule {
|
||||
@override
|
||||
String get id => 'cmake';
|
||||
|
||||
@override
|
||||
String get displayName => 'CMake';
|
||||
|
||||
@override
|
||||
List<String> get triggerFiles => const ['CMakeLists.txt'];
|
||||
|
||||
@override
|
||||
bool shouldActivate(Directory projectDir) {
|
||||
return File(p.join(projectDir.path, 'CMakeLists.txt')).existsSync();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<RunTask>> detect(ProjectModuleContext context, {bool forceRefresh = false}) async {
|
||||
final projectName = p.basename(context.projectDir.path);
|
||||
return [
|
||||
RunTask(
|
||||
id: 'detected_cmake_build_run',
|
||||
name: 'CMake: Build & Run',
|
||||
command: 'cmake -B build && cmake --build build && ./build/$projectName',
|
||||
source: TaskSource.detected,
|
||||
description: 'Configure, build, and try launching the target executable',
|
||||
group: 'build',
|
||||
moduleId: id,
|
||||
icon: Icons.play_circle_outline,
|
||||
),
|
||||
RunTask(
|
||||
id: 'detected_cmake_build',
|
||||
name: 'CMake: Build Only',
|
||||
command: 'cmake -B build && cmake --build build',
|
||||
source: TaskSource.detected,
|
||||
description: 'Only execute cmake generation and build',
|
||||
group: 'build',
|
||||
moduleId: id,
|
||||
icon: Icons.build_outlined,
|
||||
),
|
||||
RunTask(
|
||||
id: 'detected_cmake_clean',
|
||||
name: 'CMake: Clean',
|
||||
command: 'rm -rf build',
|
||||
source: TaskSource.detected,
|
||||
description: 'Clean build cache directory',
|
||||
group: 'build',
|
||||
moduleId: id,
|
||||
icon: Icons.cleaning_services_outlined,
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// Cargo (Rust) 工程探测模块
|
||||
class CargoProjectModule extends ProjectModule {
|
||||
@override
|
||||
String get id => 'cargo';
|
||||
|
||||
@override
|
||||
String get displayName => 'Cargo';
|
||||
|
||||
@override
|
||||
List<String> get triggerFiles => const ['Cargo.toml'];
|
||||
|
||||
@override
|
||||
bool shouldActivate(Directory projectDir) {
|
||||
return File(p.join(projectDir.path, 'Cargo.toml')).existsSync();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<RunTask>> detect(ProjectModuleContext context, {bool forceRefresh = false}) async {
|
||||
return [
|
||||
RunTask(
|
||||
id: 'detected_cargo_run',
|
||||
name: 'Cargo: Run',
|
||||
command: 'cargo run',
|
||||
source: TaskSource.detected,
|
||||
description: 'Compile and run Rust project',
|
||||
group: 'application',
|
||||
moduleId: id,
|
||||
icon: Icons.play_circle_outline,
|
||||
),
|
||||
RunTask(
|
||||
id: 'detected_cargo_build',
|
||||
name: 'Cargo: Build',
|
||||
command: 'cargo build',
|
||||
source: TaskSource.detected,
|
||||
description: 'Compile Rust project only',
|
||||
group: 'build',
|
||||
moduleId: id,
|
||||
icon: Icons.build_outlined,
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// NPM (Node / Web) 工程探测模块
|
||||
class NpmProjectModule extends ProjectModule {
|
||||
@override
|
||||
String get id => 'npm';
|
||||
|
||||
@override
|
||||
String get displayName => 'NPM';
|
||||
|
||||
@override
|
||||
List<String> get triggerFiles => const ['package.json'];
|
||||
|
||||
@override
|
||||
bool shouldActivate(Directory projectDir) {
|
||||
return File(p.join(projectDir.path, 'package.json')).existsSync();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<RunTask>> detect(ProjectModuleContext context, {bool forceRefresh = false}) async {
|
||||
return [
|
||||
RunTask(
|
||||
id: 'detected_npm_start',
|
||||
name: 'NPM: Start',
|
||||
command: 'npm start',
|
||||
source: TaskSource.detected,
|
||||
description: 'Start Node service or frontend development environment',
|
||||
group: 'application',
|
||||
moduleId: id,
|
||||
icon: Icons.rocket_launch_outlined,
|
||||
),
|
||||
RunTask(
|
||||
id: 'detected_npm_test',
|
||||
name: 'NPM: Test',
|
||||
command: 'npm test',
|
||||
source: TaskSource.detected,
|
||||
description: 'Execute npm test suite',
|
||||
group: 'verification',
|
||||
moduleId: id,
|
||||
icon: Icons.checklist_outlined,
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// Makefile 工程探测模块
|
||||
class MakeProjectModule extends ProjectModule {
|
||||
@override
|
||||
String get id => 'make';
|
||||
|
||||
@override
|
||||
String get displayName => 'Makefile';
|
||||
|
||||
@override
|
||||
List<String> get triggerFiles => const ['Makefile'];
|
||||
|
||||
@override
|
||||
bool shouldActivate(Directory projectDir) {
|
||||
return File(p.join(projectDir.path, 'Makefile')).existsSync();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<RunTask>> detect(ProjectModuleContext context, {bool forceRefresh = false}) async {
|
||||
return [
|
||||
RunTask(
|
||||
id: 'detected_make_default',
|
||||
name: 'Make: Default',
|
||||
command: 'make',
|
||||
source: TaskSource.detected,
|
||||
description: 'Execute default Makefile build target',
|
||||
group: 'build',
|
||||
moduleId: id,
|
||||
icon: Icons.build_circle_outlined,
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// Dart (pubspec.yaml) 工程探测模块
|
||||
class DartProjectModule extends ProjectModule {
|
||||
@override
|
||||
String get id => 'dart';
|
||||
|
||||
@override
|
||||
String get displayName => 'Dart';
|
||||
|
||||
@override
|
||||
List<String> get triggerFiles => const ['pubspec.yaml'];
|
||||
|
||||
@override
|
||||
bool shouldActivate(Directory projectDir) {
|
||||
return File(p.join(projectDir.path, 'pubspec.yaml')).existsSync();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<RunTask>> detect(ProjectModuleContext context, {bool forceRefresh = false}) async {
|
||||
return [
|
||||
RunTask(
|
||||
id: 'detected_dart_run',
|
||||
name: 'Dart: Run',
|
||||
command: 'dart run',
|
||||
source: TaskSource.detected,
|
||||
description: 'Launch Dart application',
|
||||
group: 'application',
|
||||
moduleId: id,
|
||||
icon: Icons.play_circle_outline,
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
export 'cargo_project_module.dart';
|
||||
export 'cmake_project_module.dart';
|
||||
export 'dart_project_module.dart';
|
||||
export 'make_project_module.dart';
|
||||
export 'npm_project_module.dart';
|
||||
export 'single_file_task_detector.dart';
|
||||
Reference in new issue
Block a user