97 lines
2.5 KiB
Dart
97 lines
2.5 KiB
Dart
import 'dart:io';
|
|
|
|
import 'package:path/path.dart' as path;
|
|
|
|
/// 路径解析器
|
|
/// 提供统一的路径查找和解析功能
|
|
class PathResolver {
|
|
static String? _cachedConfigPath;
|
|
|
|
/// 查找配置文件
|
|
/// 从当前工作目录向上查找 generator_config.yaml
|
|
static String? findConfigFile({bool useCache = true}) {
|
|
if (useCache && _cachedConfigPath != null) {
|
|
return _cachedConfigPath;
|
|
}
|
|
|
|
var currentDir = Directory.current;
|
|
const maxDepth = 10; // 最多向上查找 10 层
|
|
var depth = 0;
|
|
|
|
while (depth < maxDepth) {
|
|
final configFile =
|
|
File(path.join(currentDir.path, 'generator_config.yaml'));
|
|
if (configFile.existsSync()) {
|
|
_cachedConfigPath = configFile.path;
|
|
return configFile.path;
|
|
}
|
|
|
|
final parent = currentDir.parent;
|
|
if (parent.path == currentDir.path) {
|
|
// 已到达根目录
|
|
break;
|
|
}
|
|
currentDir = parent;
|
|
depth++;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// 获取配置文件所在目录
|
|
static String? getConfigDirectory() {
|
|
final configPath = findConfigFile();
|
|
if (configPath != null) {
|
|
return path.dirname(configPath);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// 获取项目包名(从 pubspec.yaml 中读取)
|
|
static String? getPackageName() {
|
|
final configDir = getConfigDirectory();
|
|
if (configDir == null) {
|
|
return null;
|
|
}
|
|
|
|
final pubspecFile = File(path.join(configDir, 'pubspec.yaml'));
|
|
if (!pubspecFile.existsSync()) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
final content = pubspecFile.readAsStringSync();
|
|
// 简单的正则匹配提取包名
|
|
// 格式: name: package_name
|
|
final match =
|
|
RegExp(r'^name:\s*(\S+)', multiLine: true).firstMatch(content);
|
|
return match?.group(1);
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// 解析路径(支持相对路径和绝对路径)
|
|
/// 如果是相对路径,相对于项目根目录(配置文件所在目录)
|
|
static String resolvePath(String filePath) {
|
|
// 如果是绝对路径,直接返回
|
|
if (path.isAbsolute(filePath)) {
|
|
return filePath;
|
|
}
|
|
|
|
// 相对路径:相对于配置文件所在目录
|
|
final configDir = getConfigDirectory();
|
|
if (configDir != null) {
|
|
return path.join(configDir, filePath);
|
|
}
|
|
|
|
// 如果找不到配置文件,使用当前工作目录
|
|
return path.join(Directory.current.path, filePath);
|
|
}
|
|
|
|
/// 清除缓存
|
|
static void clearCache() {
|
|
_cachedConfigPath = null;
|
|
}
|
|
}
|