-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsetup.dart
More file actions
575 lines (517 loc) · 16 KB
/
Copy pathsetup.dart
File metadata and controls
575 lines (517 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
// ignore_for_file: avoid_print
import 'dart:convert';
import 'dart:io';
import 'package:args/command_runner.dart';
import 'package:path/path.dart';
/// 支持的目标平台
enum Target {
windows,
linux,
android,
ios,
macos,
}
extension TargetExt on Target {
/// 获取操作系统名称
String get os {
if (this == Target.macos) {
return "darwin";
}
return name;
}
/// 检查当前运行平台是否与目标平台相同
bool get same {
if (this == Target.android) {
return true;
}
if (Platform.isWindows && this == Target.windows) {
return true;
}
if (Platform.isLinux && this == Target.linux) {
return true;
}
if (Platform.isMacOS && this == Target.macos) {
return true;
}
return false;
}
/// 获取动态库扩展名
String get dynamicLibExtensionName {
final String extensionName;
switch (this) {
case Target.android || Target.linux:
extensionName = ".so";
break;
case Target.windows:
extensionName = ".dll";
break;
case Target.ios:
extensionName = ".dylib";
break;
case Target.macos:
extensionName = ".dylib";
break;
}
return extensionName;
}
/// 获取可执行文件扩展名
String get executableExtensionName {
final String extensionName;
switch (this) {
case Target.windows:
extensionName = ".exe";
break;
default:
extensionName = "";
break;
}
return extensionName;
}
}
/// 支持的架构类型
enum Arch { amd64, arm64, arm }
/// 构建项配置
class BuildItem {
Target target;
Arch? arch;
String? archName;
BuildItem({
required this.target,
this.arch,
this.archName,
});
@override
String toString() {
return 'BuildItem{target: $target, arch: $arch, archName: $archName}';
}
}
/// 构建工具类
class Build {
/// 所有支持的构建项配置
static List<BuildItem> get buildItems => [
BuildItem(
target: Target.macos,
),
BuildItem(
target: Target.linux,
arch: Arch.arm64,
),
BuildItem(
target: Target.linux,
arch: Arch.amd64,
),
BuildItem(
target: Target.windows,
arch: Arch.amd64,
),
BuildItem(
target: Target.windows,
arch: Arch.arm64,
),
BuildItem(
target: Target.android,
arch: Arch.arm,
archName: 'armeabi-v7a',
),
BuildItem(
target: Target.android,
arch: Arch.arm64,
archName: 'arm64-v8a',
),
BuildItem(
target: Target.android,
arch: Arch.amd64,
archName: 'x86_64',
),
];
/// 应用名称
static String get appName => "AiClient";
/// 输出目录路径
static String get distPath => join(current, "dist");
/// 执行命令
static Future<void> exec(
List<String> executable, {
String? name,
Map<String, String>? environment,
String? workingDirectory,
bool runInShell = true,
}) async {
if (name != null) print("执行命令: $name");
try {
final process = await Process.start(
executable[0],
executable.sublist(1),
environment: environment,
workingDirectory: workingDirectory,
runInShell: runInShell,
);
process.stdout.listen((data) {
print(utf8.decode(data));
});
process.stderr.listen((data) {
print(utf8.decode(data));
});
final exitCode = await process.exitCode;
if (exitCode != 0 && name != null) {
throw "命令执行失败: $name (退出码: $exitCode)";
}
} catch (e) {
print("命令执行异常: $e");
if (name != null) throw "命令 '$name' 执行失败: $e";
rethrow;
}
}
/// 将命令字符串转换为可执行列表
static List<String> getExecutable(String command) {
print("命令: $command");
return command.split(" ");
}
/// 安装或检查 fastforge 工具
static Future<void> getFastforge() async {
try {
// 检查 fastforge 是否已经安装
final result = await Process.run('fastforge', ['--version']);
if (result.exitCode != 0) {
// 如果没有安装,执行安装命令
print("fastforge未安装或版本检查失败,开始安装...");
await exec(
name: "安装 fastforge",
getExecutable("dart pub global activate fastforge"),
);
// 验证安装是否成功
final verifyResult = await Process.run('fastforge', ['--version']);
if (verifyResult.exitCode != 0) {
throw "fastforge安装失败,请确保Dart SDK已正确安装并添加到PATH中";
}
print("fastforge安装成功,版本: ${verifyResult.stdout.toString().trim()}");
} else {
print("fastforge 已安装,版本: ${result.stdout.toString().trim()}");
}
} catch (e) {
// 处理ProcessException,这通常意味着命令不存在
if (e is ProcessException) {
print("fastforge命令不存在,尝试安装...");
try {
await exec(
name: "安装 fastforge",
getExecutable("dart pub global activate fastforge"),
);
print("fastforge安装成功");
} catch (installError) {
print("安装fastforge失败: $installError");
throw "无法安装fastforge,请确保Dart SDK已正确安装并添加到PATH中";
}
} else {
print("获取fastforge时出错: $e");
rethrow;
}
}
}
/// 获取应用版本号
static Future<String> getAppVersion() async {
try {
// 读取pubspec.yaml文件获取版本号
final pubspecFile = File(join(current, 'pubspec.yaml'));
if (!pubspecFile.existsSync()) {
print("警告: 未找到pubspec.yaml文件,使用默认版本号0.0.1");
return "0.0.1";
}
final content = await pubspecFile.readAsString();
final versionRegex = RegExp(r'version:\s*([0-9]+\.[0-9]+\.[0-9]+)');
final match = versionRegex.firstMatch(content);
if (match != null && match.groupCount >= 1) {
final version = match.group(1)!;
print("从pubspec.yaml获取到版本号: $version");
return version;
} else {
print("警告: 在pubspec.yaml中未找到版本号,使用默认版本号0.0.1");
return "0.0.1";
}
} catch (e) {
print("获取版本号时出错: $e,使用默认版本号0.0.1");
return "0.0.1";
}
}
/// 复制文件
static void copyFile(String sourceFilePath, String destinationFilePath) {
final sourceFile = File(sourceFilePath);
if (!sourceFile.existsSync()) {
throw "源文件不存在: $sourceFilePath";
}
final destinationFile = File(destinationFilePath);
final destinationDirectory = destinationFile.parent;
if (!destinationDirectory.existsSync()) {
destinationDirectory.createSync(recursive: true);
print("创建目标目录: ${destinationDirectory.path}");
}
try {
sourceFile.copySync(destinationFilePath);
print("文件复制成功: $sourceFilePath -> $destinationFilePath");
} catch (e) {
print("文件复制失败: $e");
throw "复制文件失败: $sourceFilePath -> $destinationFilePath: $e";
}
}
}
/// 构建命令类
class BuildCommand extends Command {
Target target;
BuildCommand({
required this.target,
}) {
if (target == Target.android || target == Target.linux) {
argParser.addOption(
"arch",
valueHelp: arches.map((e) => e.name).join(','),
help: '指定 $name 构建的架构',
);
} else {
argParser.addOption(
"arch",
help: '指定 $name 构建的架构名称',
);
}
}
@override
String get description => "构建 $name 应用";
@override
String get name => target.name;
/// 获取目标平台支持的架构列表
List<Arch> get arches => Build.buildItems
.where((element) => element.target == target && element.arch != null)
.map((e) => e.arch!)
.toList();
/// 安装Linux构建依赖
Future<void> _getLinuxDependencies(Arch arch) async {
// 更新软件包列表
await Build.exec(
Build.getExecutable("sudo apt update -y"),
);
// 安装基本工具,包括file命令
await Build.exec(
Build.getExecutable("sudo apt install -y wget curl file"),
);
// 安装其他依赖
await Build.exec(
Build.getExecutable("sudo apt install -y ninja-build libgtk-3-dev"),
);
await Build.exec(
Build.getExecutable("sudo apt install -y libayatana-appindicator3-dev"),
);
await Build.exec(
Build.getExecutable("sudo apt-get install -y libkeybinder-3.0-dev"),
);
await Build.exec(
Build.getExecutable("sudo apt install -y locate"),
);
if (arch == Arch.amd64) {
await Build.exec(
Build.getExecutable("sudo apt install -y rpm patchelf"),
);
await Build.exec(
Build.getExecutable("sudo apt install -y libfuse2"),
);
final downloadName = arch == Arch.amd64 ? "x86_64" : "aarch_64";
await Build.exec(
Build.getExecutable(
"wget -O appimagetool https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-$downloadName.AppImage",
),
);
await Build.exec(
Build.getExecutable(
"chmod +x appimagetool",
),
);
}
await Build.exec(
Build.getExecutable(
"sudo mv appimagetool /usr/local/bin/",
),
);
}
/// 安装macOS构建依赖
Future<void> _getMacosDependencies() async {
await Build.exec(
Build.getExecutable("npm install -g appdmg"),
);
}
/// 使用fastforge构建应用
Future<void> _buildFastforge({
required Target target,
required String targets,
String args = '',
}) async {
await Build.getFastforge();
if (args.isNotEmpty) {
args = "--flutter-build-args=verbose $args";
}
await Build.exec(
name: name,
Build.getExecutable(
"fastforge package --skip-clean --platform ${target.name} --targets $targets $args",
),
);
}
/// 获取系统架构
Future<String?> get systemArch async {
if (Platform.isWindows) {
return Platform.environment["PROCESSOR_ARCHITECTURE"];
} else if (Platform.isLinux || Platform.isMacOS) {
final result = await Process.run('uname', ['-m']);
return result.stdout.toString().trim();
}
return null;
}
@override
Future<void> run() async {
final archName = argResults?["arch"];
final currentArches =
arches.where((element) => element.name == archName).toList();
final arch = currentArches.isEmpty ? null : currentArches.first;
print("目标平台: $target");
if (arch == null &&
target != Target.android &&
target != Target.ios &&
target != Target.macos) {
throw "无效的架构参数,请指定有效的架构";
}
// 获取应用版本号
final appVersion = await Build.getAppVersion();
print("应用版本: $appVersion");
switch (target) {
case Target.windows:
final archStr = archName != null ? "-$archName" : "";
_buildFastforge(
target: target,
targets: "exe,zip",
args: "--artifact-name=${Build.appName}-$appVersion$archStr",
);
return;
case Target.linux:
final targetMap = {
Arch.arm64: "linux-arm64",
Arch.amd64: "linux-x64",
};
final targets = [
"deb",
if (arch == Arch.amd64) ...[
"appimage",
"rpm",
],
].join(",");
final defaultTarget = targetMap[arch];
await _getLinuxDependencies(arch!);
_buildFastforge(
target: target,
targets: targets,
args: "--build-target-platform $defaultTarget",
);
return;
case Target.android:
final archNameMap = {
Arch.arm: "armeabi-v7a",
Arch.arm64: "arm64-v8a",
Arch.amd64: "x86_64",
};
final defaultArches = [Arch.arm, Arch.arm64, Arch.amd64];
final buildArches = defaultArches
.where((element) => arch == null ? true : element == arch)
.toList();
// 创建版本输出目录
final versionDistPath = join(Build.distPath, appVersion);
final outputDir = Directory(versionDistPath);
if (!outputDir.existsSync()) {
outputDir.createSync(recursive: true);
print("创建输出目录: $versionDistPath");
}
// 使用一次性命令构建所有目标架构的APK
print("开始构建所有目标架构的Android APK");
await Build.exec(
name: "构建Android APK",
Build.getExecutable(
"flutter build apk --split-per-abi",
),
);
// 复制并重命名所有生成的APK文件
for (final buildArch in buildArches) {
final archDisplayName = archNameMap[buildArch]!;
// 构建自定义APK名称
final apkName =
"${Build.appName}-$appVersion-android-$archDisplayName.apk";
final sourceApkPath = join(current, "build", "app", "outputs",
"flutter-apk", "app-$archDisplayName-release.apk");
final destApkPath = join(versionDistPath, apkName);
// 检查源文件是否存在
if (File(sourceApkPath).existsSync()) {
Build.copyFile(sourceApkPath, destApkPath);
print("已生成 APK: $destApkPath");
} else {
print("警告: 未找到 $archDisplayName 架构的APK文件: $sourceApkPath");
}
}
return;
case Target.ios:
// 执行本地构建脚本 ios_build.sh
await Build.exec(
name: "构建iOS应用",
Build.getExecutable(
"bash ios_build.sh",
),
);
return;
case Target.macos:
await _getMacosDependencies();
await _buildFastforge(
target: target,
targets: "dmg",
);
// 构建完成后,查找并重命名 DMG 文件
final appVersion = await Build.getAppVersion();
// 查找DMG 文件
print("正在搜索 DMG 文件...");
bool found = false;
// 检查版本目录
final versionDir = Directory(join(Build.distPath, appVersion));
if (versionDir.existsSync()) {
final files = versionDir.listSync();
for (final entity in files) {
if (entity is File &&
entity.path.endsWith('.dmg') &&
entity.path.contains(appVersion)) {
print("在版本目录中找到 DMG 文件: ${entity.path}");
try {
// 在原目录中重命名文件
final customDmgName = "${Build.appName}-$appVersion-macos.dmg";
final customDmgPath = join(dirname(entity.path), customDmgName);
File(entity.path).renameSync(customDmgPath);
print("已将 DMG 文件重命名为: $customDmgName");
found = true;
break;
} catch (e) {
print("重命名 DMG 文件失败: $e");
}
}
}
}
if (!found) {
print("警告: 未找到任何 DMG 文件,请检查 fastforge 的输出路径");
}
return;
}
}
}
/// 主函数
Future<void> main(List<String> args) async {
try {
final runner = CommandRunner("setup", "构建应用程序");
runner.addCommand(BuildCommand(target: Target.android));
runner.addCommand(BuildCommand(target: Target.ios));
runner.addCommand(BuildCommand(target: Target.linux));
runner.addCommand(BuildCommand(target: Target.windows));
runner.addCommand(BuildCommand(target: Target.macos));
await runner.run(args);
} catch (e) {
print("构建失败: $e");
exit(1);
}
}