-
Notifications
You must be signed in to change notification settings - Fork 61
/
configuration.dart
394 lines (363 loc) · 15.3 KB
/
configuration.dart
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
import 'dart:io';
import 'package:args/args.dart' show ArgParser, ArgResults;
import 'package:cli_util/cli_logging.dart' show Logger;
import 'package:get_it/get_it.dart';
import 'package:package_config/package_config.dart' show findPackageConfig;
import 'package:path/path.dart' show extension, basename;
import 'package:pub_semver/pub_semver.dart';
import 'package:yaml/yaml.dart' show YamlMap, loadYaml;
import 'extensions.dart';
/// Handles loading and validating the configuration values
class Configuration {
final List<String> _arguments;
final Logger _logger = GetIt.I<Logger>();
late ArgResults _args;
String msixAssetsPath = '';
String? appName;
String? publisherName;
String? identityName;
String? msixVersion;
String? appDescription;
String buildFilesFolder =
'${Directory.current.path}/build/windows/runner/Release';
String? certificatePath;
String? certificatePassword;
String? publisher;
String? displayName;
String? architecture;
String? capabilities;
String? logoPath;
String? executableFileName;
List<String>? signToolOptions;
late Iterable<String> protocolActivation;
String? executionAlias;
String? fileExtension;
String? toastActivatorCLSID;
String? toastActivatorArguments;
String? toastActivatorDisplayName;
String? outputPath;
String? outputName;
String? publishFolderPath;
int hoursBetweenUpdateChecks = 0;
bool automaticBackgroundTask = false;
bool updateBlocksActivation = false;
bool showPrompt = false;
bool forceUpdateFromAnyVersion = false;
bool store = false;
bool signMsix = true;
bool installCert = true;
bool buildWindows = true;
bool trimLogo = true;
bool createWithDebugBuildFiles = false;
bool enableAtStartup = false;
Iterable<String>? appUriHandlerHosts;
Iterable<String>? languages;
String get defaultsIconsFolderPath => '$msixAssetsPath/icons';
String get msixToolkitPath => '$msixAssetsPath/MSIX-Toolkit';
String get msixPath =>
'${outputPath ?? buildFilesFolder}/${outputName ?? appName}.msix';
String get appInstallerPath =>
'$publishFolderPath/${basename(msixPath).replaceAll('.msix', '.appinstaller')}';
String pubspecYamlPath = "pubspec.yaml";
String osMinVersion = '10.0.17763.0';
Configuration(this._arguments);
/// Gets the configuration values from from [_arguments] or pubspec.yaml file
Future<void> getConfigValues() async {
_parseCliArguments(_arguments);
await _getMsixAssetsFolderPath();
var pubspec = await _getPubspec();
appName = pubspec['name'];
appDescription = pubspec['description'];
var yaml = pubspec['msix_config'] ?? YamlMap();
msixVersion =
_args['version'] ?? yaml['msix_version'] ?? _getPubspecVersion(pubspec);
certificatePath = _args['certificate-path'] ?? yaml['certificate_path'];
certificatePassword = _args['certificate-password'] ??
yaml['certificate_password']?.toString();
outputPath = _args['output-path'] ?? yaml['output_path'];
outputName = _args['output-name'] ?? yaml['output_name'];
executionAlias = _args['execution-alias'] ?? yaml['execution_alias'];
if (_args['sign-msix'].toString() == 'false' ||
yaml['sign_msix']?.toString().toLowerCase() == 'false') {
signMsix = false;
}
if (_args['install-certificate'].toString() == 'false' ||
yaml['install_certificate']?.toString().toLowerCase() == 'false') {
installCert = false;
}
if (_args['build-windows'].toString() == 'false' ||
yaml['build_windows']?.toString().toLowerCase() == 'false') {
buildWindows = false;
}
if (_args['trim-logo'].toString() == 'false' ||
yaml['trim_logo']?.toString().toLowerCase() == 'false') {
trimLogo = false;
}
store = _args.wasParsed('store') ||
yaml['store']?.toString().toLowerCase() == 'true';
createWithDebugBuildFiles = _args.wasParsed('debug') ||
yaml['debug']?.toString().toLowerCase() == 'true';
if (createWithDebugBuildFiles) {
buildFilesFolder = buildFilesFolder.replaceFirst('Release', 'Debug');
}
displayName = _args['display-name'] ?? yaml['display_name'];
publisherName =
_args['publisher-display-name'] ?? yaml['publisher_display_name'];
publisher = _args['publisher'] ?? yaml['publisher'];
identityName = _args['identity-name'] ?? yaml['identity_name'];
logoPath = _args['logo-path'] ?? yaml['logo_path'];
signToolOptions = (_args['signtool-options'] ?? yaml['signtool_options'])
?.toString()
.split(' ')
.where((o) => o.trim().isNotEmpty)
.toList();
protocolActivation = _getProtocolsActivation(yaml);
fileExtension = _args['file-extension'] ?? yaml['file_extension'];
if (fileExtension != null && !fileExtension!.startsWith('.')) {
fileExtension = '.$fileExtension';
}
architecture = _args['architecture'] ?? yaml['architecture'];
capabilities = _args['capabilities'] ?? yaml['capabilities'];
languages = _getLanguages(yaml);
appUriHandlerHosts = _getAppUriHandlerHosts(yaml);
enableAtStartup = _args.wasParsed('enable-at-startup') ||
yaml['enable_at_startup']?.toString().toLowerCase() == 'true';
// toast activator configurations
var toastActivatorYaml = yaml['toast_activator'] ?? YamlMap();
toastActivatorCLSID = _args['toast-activator-clsid'] ??
toastActivatorYaml['clsid']?.toString();
toastActivatorArguments = _args['toast-activator-arguments'] ??
toastActivatorYaml['arguments']?.toString() ??
'----AppNotificationActivationServer';
toastActivatorDisplayName = _args['toast-activator-display-name'] ??
toastActivatorYaml['display_name']?.toString() ??
'Toast activator';
// app installer configurations
var installerYaml = yaml['app_installer'] ?? YamlMap();
publishFolderPath =
_args['publish-folder-path'] ?? installerYaml['publish_folder_path'];
hoursBetweenUpdateChecks = int.parse(_args['hours-between-update-checks'] ??
installerYaml['hours_between_update_checks']?.toString() ??
'0');
if (hoursBetweenUpdateChecks < 0) hoursBetweenUpdateChecks = 0;
automaticBackgroundTask = _args.wasParsed('automatic-background-task') ||
installerYaml['automatic_background_task']?.toString().toLowerCase() ==
'true';
updateBlocksActivation = _args.wasParsed('update-blocks-activation') ||
installerYaml['update_blocks_activation']?.toString().toLowerCase() ==
'true';
showPrompt = _args.wasParsed('show-prompt') ||
installerYaml['show_prompt']?.toString().toLowerCase() == 'true';
forceUpdateFromAnyVersion =
_args.wasParsed('force-update-from-any-version') ||
installerYaml['force_update_from_any_version']
?.toString()
.toLowerCase() ==
'true';
}
/// Validate the configuration values and set default values
Future<void> validateConfigValues() async {
_logger.trace('validating config values');
if (appName.isNull) {
throw 'App name is empty, check the general \'name:\' property at pubspec.yaml';
}
if (appDescription.isNull) appDescription = appName;
var cleanAppName = appName!.replaceAll('_', '');
if (displayName.isNull) displayName = cleanAppName;
if (identityName.isNull) {
if (store) {
_logger.stderr(
'identity name is empty, check "msix_config: identity_name" at pubspec.yaml');
throw 'you can find your store "identity_name" in https://partner.microsoft.com/en-us/dashboard > Product > Product identity > Package/Identity/Name';
} else {
identityName = 'com.flutter.$cleanAppName';
}
} else {
if (!RegExp(r'^[a-zA-Z0-9.-]{3,50}$').hasMatch(identityName!)) {
throw 'invalid identity name ("identity_name"): "$identityName". need to be a string between 3 and 50 characters in length that consists of alpha-numeric, period, and dash characters.';
}
}
if (publisherName.isNull) {
if (store) {
_logger.stderr(
'publisher display name is empty, check "msix_config: publisher_display_name" at pubspec.yaml');
throw 'you can find your store "publisher_display_name" in https://partner.microsoft.com/en-us/dashboard > Product > Product identity > Package/Properties/PublisherDisplayName';
} else {
publisherName = identityName;
}
}
if (signMsix == false && publisher.isNullOrEmpty) {
_logger.stderr(
'when sign_msix is false, you must provide the publisher value at "msix_config: publisher" in the pubspec.yaml file');
exit(-1);
}
if (store && publisher.isNullOrEmpty) {
_logger.stderr(
'publisher is empty, check "msix_config: publisher" at pubspec.yaml');
throw 'you can find your store "publisher" in https://partner.microsoft.com/en-us/dashboard > Product > Product identity > Package/Properties/Publisher';
}
if (msixVersion.isNull) msixVersion = '1.0.0.0';
if (architecture.isNull) architecture = 'x64';
languages ??= ['en-us'];
if (!RegExp(r'^(\*|\d+(\.\d+){3,3}(\.\*)?)$').hasMatch(msixVersion!)) {
throw 'msix version can be only in this format: "1.0.0.0"';
}
if (displayName != null && displayName!.length > 256) {
throw '"display name" is too long, it should be less than 256 characters';
}
if (publisherName != null && publisherName!.length > 256) {
throw '"publisher display name" is too long, it should be less than 256 characters';
}
if (!certificatePath.isNull || signToolOptions != null || store) {
if (!certificatePath.isNull) {
if (!(await File(certificatePath!).exists())) {
throw 'The file certificate not found in: $certificatePath, check "msix_config: certificate_path" at pubspec.yaml';
}
if (extension(certificatePath!) == '.pfx' &&
certificatePassword.isNull) {
throw 'Certificate password is empty, check "msix_config: certificate_password" at pubspec.yaml';
}
}
} else {
// if no certificate was chosen then use test certificate
certificatePath = '$msixAssetsPath/test_certificate.pfx';
certificatePassword = '1234';
}
if (!['x86', 'x64'].contains(architecture)) {
throw 'Architecture can be "x86" or "x64", check "msix_config: architecture" at pubspec.yaml';
}
}
/// Validate "flutter build windows" output files
Future<void> validateWindowsBuildFiles() async {
_logger.trace('validating build files');
if (!await Directory(buildFilesFolder).exists() ||
!await Directory(buildFilesFolder)
.list()
.any((file) => file.path.endsWith('.exe'))) {
throw 'Build files not found at $buildFilesFolder, first run "flutter build windows" then try again';
}
executableFileName = await Directory(buildFilesFolder)
.list()
.firstWhere((file) =>
file.path.endsWith('.exe') &&
!file.path.contains('PSFLauncher64.exe'))
.then((file) => basename(file.path));
}
/// Declare and parse the cli arguments
void _parseCliArguments(List<String> args) {
_logger.trace('parsing cli arguments');
var parser = ArgParser()
..addOption('certificate-password', abbr: 'p')
..addOption('certificate-path', abbr: 'c')
..addOption('version')
..addOption('display-name', abbr: 'd')
..addOption('publisher-display-name', abbr: 'u')
..addOption('identity-name', abbr: 'i')
..addOption('publisher', abbr: 'b')
..addOption('logo-path', abbr: 'l')
..addOption('output-path', abbr: 'o')
..addOption('output-name', abbr: 'n')
..addOption('signtool-options')
..addOption('protocol-activation')
..addOption('execution-alias')
..addOption('file-extension', abbr: 'f')
..addOption('architecture', abbr: 'h')
..addOption('capabilities', abbr: 'e')
..addOption('languages')
..addOption('sign-msix')
..addOption('install-certificate')
..addOption('trim-logo')
..addOption('toast-activator-clsid')
..addOption('toast-activator-arguments')
..addOption('toast-activator-display-name')
..addOption('publish-folder-path')
..addOption('hours-between-update-checks')
..addOption('build-windows')
..addOption('app-uri-handler-hosts')
..addFlag('store')
..addFlag('enable-at-startup')
..addFlag('debug')
..addFlag('release')
..addFlag('automatic-background-task')
..addFlag('update-blocks-activation')
..addFlag('show-prompt')
..addFlag('force-update-from-any-version');
// exclude -v (verbose) from the arguments
_args = parser.parse(args.where((arg) => arg != '-v'));
}
Future<void> validateAppInstallerConfigValues() async {
_logger.trace('validating app installer config values');
if (publishFolderPath.isNullOrEmpty ||
!await Directory(publishFolderPath!).exists()) {
_logger.stderr(
'publish folder path is not exists, check "app_installer: publish_folder_path" at pubspec.yaml'
.red);
exit(-1);
} else {
publishFolderPath = Uri.decodeFull(publishFolderPath!);
}
}
/// Get the assets folder path from the .packages file
Future<void> _getMsixAssetsFolderPath() async {
var packagesConfig = await findPackageConfig(Directory.current);
if (packagesConfig == null) {
throw 'Failed to locate or read package config.';
}
var msixPackage =
packagesConfig.packages.firstWhere((package) => package.name == "msix");
var path =
msixPackage.packageUriRoot.toString().replaceAll('file:///', '') +
'assets';
msixAssetsPath = Uri.decodeFull(path);
}
/// Get pubspec.yaml content
dynamic _getPubspec() async {
var pubspecString = await File(pubspecYamlPath).readAsString();
var pubspec = loadYaml(pubspecString);
return pubspec;
}
String? _getPubspecVersion(dynamic yaml) {
// Existing behavior is to put null if no version, so matching
if (yaml['version'] == null) return null;
try {
final pubspecVersion = Version.parse(yaml['version']);
return [
pubspecVersion.major,
pubspecVersion.minor,
pubspecVersion.patch,
0
].join('.');
} on FormatException {
_logger.stderr(
'Warning: Could not parse Pubspec version. No version provided.',
);
return null;
}
}
/// Get the languages list
Iterable<String>? _getLanguages(dynamic config) =>
((_args['languages'] ?? config['languages']) as String?)
?.split(',')
.map((e) => e.trim())
.where((element) => element.isNotEmpty);
/// Get the app uri handler hosts list
Iterable<String>? _getAppUriHandlerHosts(dynamic config) =>
((_args['app-uri-handler-hosts'] ?? config['app_uri_handler_hosts'])
as String?)
?.split(',')
.map((e) => e.trim())
.where((element) => element.isNotEmpty);
/// Get the protocol activation list
Iterable<String> _getProtocolsActivation(dynamic config) =>
((_args['protocol-activation'] ?? config['protocol_activation'])
as String?)
?.split(',')
.map((protocol) => protocol
.trim()
.toLowerCase()
.replaceAll('://', '')
.replaceAll(':/', '')
.replaceAll(':', ''))
.where((protocol) => protocol.isNotEmpty) ??
[];
}