引言
近期整理技术栈,将陆续总结分享一些项目实战中用到的实用工具。本篇分享开发流程中必不可缺的一个环节,提测。
闲聊一下
当然,对于打包,我们可以直接使用命令行直接打包例如:
dart
flutter build apk --verbose
只是,相比输入命令行,我更倾向于一键操作
,更倾向写一个打包脚本,我可以在脚本里编辑个性化操作,例如:瘦身、修改产物(apk、ipa)名称、指定打包成功后事务等等。
比如在项目里新建一个文件夹,如 script
, 当需要打包发布时,右键 Run 就 Ok 了。
下面,小编整理了基础款 dart 脚本,用于 打包
和 上传蒲公英
。有需要的同学可自行添加个性化处理。
Android 打包脚本
该脚本用于 apk 打包,apk 以当前时间戳名称,打包成功后可选直接打开文件夹或发布蒲公英。
dart
import 'dart:io';
import 'package:intl/intl.dart';
import 'package:yaml/yaml.dart' as yaml;
import 'pgy_tool.dart'; //蒲公英发布脚本,下面会给出
void main(List<String> args) async {
//是否上传蒲公英
bool uploadPGY = true;
// 获取项目根目录
final _projectPath = await Process.run(
'pwd',
[],
);
final projectPath = (_projectPath.stdout as String).replaceAll(
'\n',
'',
);
// 控制台打印项目目录
stdout.write('项目目录:$projectPath 开始编译\n');
final process = await Process.start(
'flutter',
[
'build',
'apk',
'--verbose',
],
workingDirectory: projectPath,
mode: ProcessStartMode.inheritStdio,
);
final buildResult = await process.exitCode;
if (buildResult != 0) {
stdout.write('打包失败,请查看日志');
return;
}
process.kill();
//开始重命名
final file = File('$projectPath/pubspec.yaml');
final fileContent = file.readAsStringSync();
final yamlMap = yaml.loadYaml(fileContent) as yaml.YamlMap;
//获取当前版本号
final version = (yamlMap['version'].toString()).replaceAll(
'+',
'_',
);
final appName = yamlMap['name'].toString();
// apk 的输出目录
final apkDirectory = '$projectPath/build/app/outputs/flutter-apk/';
const buildAppName = 'app-release.apk';
final timeStr = DateFormat('yyyyMMddHHmm').format(
DateTime.now(),
);
final resultNameList = [
appName,
version,
timeStr,
].where((element) => element.isNotEmpty).toList();
final resultAppName = '${resultNameList.join('_')}.apk';
final appPath = apkDirectory + resultAppName;
//重命名apk文件
final apkFile = File(apkDirectory + buildAppName);
await apkFile.rename(appPath);
stdout.write('apk 打包成功 >>>>> $appPath \n');
if (uploadPGY) {
// 上传蒲公英
final pgyPublisher = PGYTool(
apiKey: '蒲公英控制台内你的应用的apiKey',
buildType: 'android',
);
final uploadSuccess = await pgyPublisher.publish(appPath);
if (uploadSuccess) {
File(appPath).delete();
}
} else {
// 直接打开文件
await Process.run(
'open',
[apkDirectory],
);
}
}
Ipa 打包脚本
ipa 打包脚本和 apk 打包脚本类似,只是过程中多了一步操作,删除之前的构建文件,如下:
dart
import 'dart:io';
import 'package:yaml/yaml.dart' as yaml;
import 'package:intl/intl.dart';
import 'pgy_tool.dart';
void main() async {
const originIpaName = '你的应用名称';
//是否上传蒲公英
bool uploadPGY = true;
// 获取项目根目录
final _projectPath = await Process.run(
'pwd',
[],
);
final projectPath = (_projectPath.stdout as String).replaceAll(
'\n',
'',
);
// 控制台打印项目目录
stdout.write('项目目录:$projectPath 开始编译\n');
// 编译目录
final buildPath = '$projectPath/build/ios';
// 切换到项目目录
Directory.current = projectPath;
// 删除之前的构建文件
if (Directory(buildPath).existsSync()) {
Directory(buildPath).deleteSync(
recursive: true,
);
}
final process = await Process.start(
'flutter',
[
'build',
'ipa',
'--target=$projectPath/lib/main.dart',
'--verbose',
],
workingDirectory: projectPath,
mode: ProcessStartMode.inheritStdio,
);
final buildResult = await process.exitCode;
if (buildResult != 0) {
stdout.write('ipa 编译失败,请查看日志');
return;
}
process.kill();
stdout.write('ipa 编译成功!\n');
//开始重命名
final file = File('$projectPath/pubspec.yaml');
final fileContent = file.readAsStringSync();
final yamlMap = yaml.loadYaml(fileContent) as yaml.YamlMap;
//获取当前版本号
final version = (yamlMap['version'].toString()).replaceAll(
'+',
'_',
);
final appName = yamlMap['name'].toString();
// ipa 的输出目录
final ipaDirectory = '$projectPath/build/ios/ipa/';
const buildAppName = '$originIpaName.ipa';
final timeStr = DateFormat('yyyyMMddHHmm').format(
DateTime.now(),
);
final resultNameList = [
appName,
version,
timeStr,
].where((element) => element.isNotEmpty).toList();
final resultAppName = '${resultNameList.join('_')}.ipa';
final appPath = ipaDirectory + resultAppName;
//重命名ipa文件
final ipaFile = File(ipaDirectory + buildAppName);
await ipaFile.rename(appPath);
stdout.write('ipa 打包成功 >>>>> $appPath \n');
if (uploadPGY) {
// 上传蒲公英
final pgyPublisher = PGYTool(
apiKey: '蒲公英控制台内你的应用的apiKey',
buildType: 'ios',
);
pgyPublisher.publish(appPath);
} else {
// 直接打开文件
await Process.run(
'open',
[ipaDirectory],
);
}
}
蒲公英发布脚本
上面打包脚本中上传到蒲公英都调用了这句代码:
dart
// 上传蒲公英
final pgyPublisher = PGYTool(
apiKey: '蒲公英控制台内你的应用的apiKey',
buildType: 'ios',
);
pgyPublisher.publish(appPath);
appPath
:就是打包成功的 apk/ipa 本地路径buildType
:分别对应两个值 android、iosapiKey
:蒲公英控制台内你的应用对应的apiKey,如下所示
PGYTool 对应的发布脚本如下:
dart
import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:rxdart/rxdart.dart';
// 蒲公英工具类
class PGYTool {
final getTokenPath = 'https://www.pgyer.com/apiv2/app/getCOSToken';
final getAppInfoPath = 'https://www.pgyer.com/apiv2/app/buildInfo';
final String apiKey;
final String buildType; //android、ios
PGYTool({
required this.apiKey,
required this.buildType,
});
//发布应用
Future<bool> publish(String appFilePath) async {
final dio = new Dio();
stdout.write('开始获取蒲公英token');
final tokenResponse = await _getToken(dio);
if (tokenResponse == null) {
stdout.write('>>>>>> 获取token失败 \n');
return false;
}
stdout.write('>>>>>> 获取token成功 \n');
final endpoint = tokenResponse['data']['endpoint'] ?? '';
final params = tokenResponse['data']['params'] ?? {};
stdout.write('蒲公英上传地址:$endpoint\n');
Map<String, dynamic> map = {
...params,
};
map['file'] = await MultipartFile.fromFile(appFilePath);
final controller = StreamController<MapEntry<int, int>>();
controller.stream
.throttleTime(const Duration(seconds: 1), trailing: true)
.listen(
(event) => stdout.write(
'${event.key}/${event.value} ${(event.key.toDouble() / event.value.toDouble() * 100).toStringAsFixed(2)}% \n',
),
onDone: () {
controller.close();
},
onError: (e) {
controller.close();
},
);
final uploadRsp = await dio.post(
endpoint,
data: FormData.fromMap(map),
onSendProgress: (count, total) {
controller.sink.add(
MapEntry<int, int>(
count,
total,
),
);
},
);
await Future.delayed(const Duration(seconds: 1));
if (uploadRsp.statusCode != 204) {
stdout.write('>>>>> 蒲公英上传失败 \n');
return false;
}
stdout.write('>>>>> 蒲公英上传成功 \n');
await Future.delayed(const Duration(seconds: 3));
await _getAppInfo(dio, tokenResponse['data']['key']);
return true;
}
// 获取蒲公英token
Future<Map<String, dynamic>?> _getToken(Dio dio) async {
Response<Map<String, dynamic>>? tokenResponse;
try {
tokenResponse = await dio.post<Map<String, dynamic>>(
getTokenPath,
queryParameters: {
'_api_key': apiKey,
'buildType': buildType,
},
);
} catch (_) {
stdout.write('_getToken error : $_');
}
if (tokenResponse == null) return null;
final responseJson = tokenResponse.data ?? {};
final tokenCode = responseJson['code'] ?? 100;
if (tokenCode != 0) {
return null;
} else {
return responseJson;
}
}
// tokenKey 是获取token中的返回值Key
Future<void> _getAppInfo(Dio dio, String tokenKey, {int retryCount = 3}) async {
final response = await dio.get<Map<String, dynamic>>(
getAppInfoPath,
queryParameters: {
'_api_key': apiKey,
'buildKey': tokenKey,
},
).then((value) {
return value.data ?? {};
});
final responseCode = response['code'];
if (responseCode == 1247 && retryCount > 0) {
//应用正在发布中,间隔 3 秒重新获取
stdout.write('>>>>> 应用正在发布中,间隔 3 秒重新获取发布信息\n');
await Future.delayed(const Duration(seconds: 3));
return _getAppInfo(dio, tokenKey, retryCount: retryCount - 1);
}
final appName = response['data']['buildName'];
final appVersion = response['data']['buildVersion'];
final appUrl = response['data']['buildShortcutUrl'];
final updateTime = response['data']['buildUpdated'];
if (appName != null) {
stdout.write('$appName 版本更新($appVersion)\n');
stdout.write('下载地址:https://www.pgyer.com/$appUrl\n');
stdout.write('更新时间:$updateTime\n');
}
}
}
运行发布脚本后,控制台会将应用的上传成功后的下载地址打印出来。