引言
近期整理技術(shù)棧组哩,將陸續(xù)總結(jié)分享一些項目實戰(zhàn)中用到的實用工具漫贞。本篇分享開發(fā)流程中必不可缺的一個環(huán)節(jié),提測闽坡。
閑聊一下
當然栽惶,對于打包,我們可以直接使用命令行直接打包例如:
flutter build apk --verbose
只是疾嗅,相比輸入命令行外厂,我更傾向于一鍵操作
,更傾向?qū)懸粋€打包腳本代承,我可以在腳本里編輯個性化操作汁蝶,例如:瘦身、修改產(chǎn)物(apk论悴、ipa)名稱掖棉、指定打包成功后事務(wù)等等。
比如在項目里新建一個文件夾膀估,如 script
, 當需要打包發(fā)布時幔亥,右鍵 Run 就 Ok 了。
下面察纯,小編整理了基礎(chǔ)款 dart 腳本帕棉,用于 打包
和 上傳蒲公英
针肥。有需要的同學可自行添加個性化處理。
Android 打包腳本
該腳本用于 apk 打包笤昨,apk 以當前時間戳名稱祖驱,打包成功后可選直接打開文件夾或發(fā)布蒲公英握恳。
import 'dart:io';
import 'package:intl/intl.dart';
import 'package:yaml/yaml.dart' as yaml;
import 'pgy_tool.dart'; //蒲公英發(fā)布腳本瞒窒,下面會給出
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: '蒲公英控制臺內(nèi)你的應(yīng)用的apiKey',
buildType: 'android',
);
final uploadSuccess = await pgyPublisher.publish(appPath);
if (uploadSuccess) {
File(appPath).delete();
}
} else {
// 直接打開文件
await Process.run(
'open',
[apkDirectory],
);
}
}
Ipa 打包腳本
ipa 打包腳本和 apk 打包腳本類似乡洼,只是過程中多了一步操作崇裁,刪除之前的構(gòu)建文件妙蔗,如下:
import 'dart:io';
import 'package:yaml/yaml.dart' as yaml;
import 'package:intl/intl.dart';
import 'pgy_tool.dart';
void main() async {
const originIpaName = '你的應(yīng)用名稱';
//是否上傳蒲公英
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;
// 刪除之前的構(gòu)建文件
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: '蒲公英控制臺內(nèi)你的應(yīng)用的apiKey',
buildType: 'ios',
);
pgyPublisher.publish(appPath);
} else {
// 直接打開文件
await Process.run(
'open',
[ipaDirectory],
);
}
}
蒲公英發(fā)布腳本
上面打包腳本中上傳到蒲公英都調(diào)用了這句代碼:
// 上傳蒲公英
final pgyPublisher = PGYTool(
apiKey: '蒲公英控制臺內(nèi)你的應(yīng)用的apiKey',
buildType: 'ios',
);
pgyPublisher.publish(appPath);
-
appPath
:就是打包成功的 apk/ipa 本地路徑 -
buildType
:分別對應(yīng)兩個值 android薄辅、ios -
apiKey
:蒲公英控制臺內(nèi)你的應(yīng)用對應(yīng)的apiKey锹雏,如下所示
PGYTool 對應(yīng)的發(fā)布腳本如下:
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,
});
//發(fā)布應(yīng)用
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) {
//應(yīng)用正在發(fā)布中,間隔 3 秒重新獲取
stdout.write('>>>>> 應(yīng)用正在發(fā)布中礁遵,間隔 3 秒重新獲取發(fā)布信息\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');
}
}
}
運行發(fā)布腳本后轻绞,控制臺會將應(yīng)用的上傳成功后的下載地址打印出來。