You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

120 lines
2.8 KiB

5 years ago
import 'dart:io';
import 'parse_arguments.dart';
import 'expressions/expressions.dart';
5 years ago
const FLAVORS = [
'test',
'tw',
'cn',
];
final _ctx = {
'debug': 'debug',
'release': 'release',
'profile': 'profile',
'default': 'default',
};
String? exp;
late String mode;
late String flavor;
5 years ago
enum STATE {
none,
notMatch,
caching,
replace,
}
void main(List<String> arguments) {
print("Running default pre_script.");
var args = parse(arguments);
mode = args.mode;
flavor = args.flavor;
5 years ago
_ctx.addEntries(FLAVORS.map((e) => MapEntry(e, e)));
_ctx.addAll({
'mode': mode,
'flavor': flavor,
});
5 years ago
var rootDir = Directory('./');
rootDir.listSync().forEach(walkPath);
}
File? file;
5 years ago
StringBuffer sb = StringBuffer();
StringBuffer tmp = StringBuffer();
STATE state = STATE.none;
RegExp re = RegExp(r'// #\{\{(.+)\}\}');
Match? ma;
5 years ago
bool modified = false;
5 years ago
const evaluator = const ExpressionEvaluator();
5 years ago
void walkPath(FileSystemEntity path) {
var stat = path.statSync();
if (stat.type == FileSystemEntityType.directory) {
Directory(path.path).listSync().forEach(walkPath);
} else if (stat.type == FileSystemEntityType.file) {
file = File(path.path);
sb.clear();
5 years ago
modified = false;
5 years ago
try {
file!.readAsLinesSync().forEach((line) {
5 years ago
ma = re.firstMatch(line);
if (ma != null) {
5 years ago
modified = true;
exp = ma!.group(1);
if (exp == "default") {
// 默认代码块开始
if (tmp.isNotEmpty) {
5 years ago
sb.write(tmp);
print([
"${file!.path} modified",
"-" * 80,
tmp.toString(),
"-" * 80,
].join("\n"));
5 years ago
state = STATE.replace;
} else {
5 years ago
state = STATE.none;
5 years ago
}
} else if (exp == "end") {
// 默认代码块结束
state = STATE.none;
tmp.clear();
5 years ago
} else {
if (evaluator.eval(Expression.parse(exp!), _ctx)) {
// 匹配到
tmp.clear();
state = STATE.caching;
} else {
state = STATE.notMatch;
5 years ago
}
}
} else {
// none状态时直接将line写入sb
5 years ago
if (state == STATE.none) {
5 years ago
sb.writeln(line);
5 years ago
}
5 years ago
// 缓存中状态,将用于替换的内容移除注释后写入缓存
else if (state == STATE.caching)
tmp.writeln(line.replaceFirst('// ', ''));
5 years ago
// 这样就跳过了没有匹配上的替换代码块和默认内容
}
});
5 years ago
if (modified) {
file!.renameSync(path.path + '.bak');
File(path.path).writeAsStringSync(sb.toString(), flush: true);
5 years ago
}
5 years ago
} catch (e) {
if (!(e is FileSystemException)) {
rethrow;
}
}
}
}