import 'dart:convert'; import 'dart:io'; Map parseLocalEnvironment(String source) { final values = {}; final lines = const LineSplitter().convert( source.replaceFirst(RegExp(r'^\uFEFF'), ''), ); final assignment = RegExp( r'^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$', ); for (var index = 0; index < lines.length; index++) { final line = lines[index].trim(); if (line.isEmpty || line.startsWith('#')) continue; final match = assignment.firstMatch(line); if (match == null) { throw FormatException( 'Invalid .env.local assignment on line ${index + 1}.', ); } final key = match[1]!; if (values.containsKey(key)) { throw FormatException('Duplicate .env.local key on line ${index + 1}.'); } var value = match[2]!; if (value.startsWith('"') || value.startsWith("'")) { final end = value.indexOf(value[0], 1); if (end == -1 || (value.substring(end + 1).trim().isNotEmpty && !value.substring(end + 1).trim().startsWith('#'))) { throw FormatException( 'Invalid .env.local quotes on line ${index + 1}.', ); } value = value.substring(1, end); } else { value = value.split(RegExp(r'\s+#')).first.trimRight(); } values[key] = value; } return values; } bool isContinuousIntegration(Map environment) => [ 'CI', 'GITEA_ACTIONS', 'GITHUB_ACTIONS', ].any((key) => ['true', '1', 'yes'].contains(environment[key]?.toLowerCase())); Map mergeLocalEnvironment( Map inherited, Map local, { required bool windows, }) { final result = Map.of(inherited); final existing = inherited.keys .map((key) => windows ? key.toUpperCase() : key) .toSet(); for (final entry in local.entries) { final key = windows ? entry.key.toUpperCase() : entry.key; if (existing.add(key)) result[entry.key] = entry.value; } return result; } Map loadLocalEnvironment( Directory root, Map inherited, { required bool windows, }) { // Check the parent environment before opening any local file in CI. if (isContinuousIntegration(inherited)) return Map.of(inherited); final file = File.fromUri(root.uri.resolve('.env.local')); return mergeLocalEnvironment( inherited, file.existsSync() ? parseLocalEnvironment(file.readAsStringSync()) : {}, windows: windows, ); } Future runLocalFlutter( List arguments, { required Directory root, required Map inherited, }) async { return runProjectTool('flutter', arguments, root: root, inherited: inherited); } Directory projectSdkBin(Directory root, {bool allowCiSdk = false}) { final bin = allowCiSdk && isContinuousIntegration(Platform.environment) ? File(Platform.resolvedExecutable).parent.parent.parent.parent : Directory.fromUri(root.uri.resolve('.fvm/flutter_sdk/bin/')); if (!File.fromUri( bin.uri.resolve(Platform.isWindows ? 'flutter.bat' : 'flutter'), ).existsSync() || !File.fromUri( bin.uri.resolve( 'cache/dart-sdk/bin/${Platform.isWindows ? 'dart.exe' : 'dart'}', ), ).existsSync()) { throw StateError( 'Project Flutter SDK is missing. Run fvm use first; CI requires a complete Flutter SDK.', ); } return bin; } Map projectEnvironment( Directory root, Map inherited, Directory sdkBin, ) { final environment = loadLocalEnvironment( root, inherited, windows: Platform.isWindows, ); final pathKey = environment.keys .where( (key) => Platform.isWindows ? key.toUpperCase() == 'PATH' : key == 'PATH', ) .firstOrNull; final path = pathKey == null ? '' : environment.remove(pathKey)!; environment['PATH'] = '${sdkBin.path}${Platform.isWindows ? ';' : ':'}$path'; return environment; } Future runProjectTool( String tool, List arguments, { required Directory root, required Map inherited, Directory? workingDirectory, bool allowCiSdk = false, }) async { final bin = projectSdkBin(root, allowCiSdk: allowCiSdk); final environment = projectEnvironment(root, inherited, bin); final String executable; switch (tool) { case 'flutter': executable = File.fromUri( bin.uri.resolve(Platform.isWindows ? 'flutter.bat' : 'flutter'), ).path; case 'dart': executable = File.fromUri( bin.uri.resolve( 'cache/dart-sdk/bin/${Platform.isWindows ? 'dart.exe' : 'dart'}', ), ).path; case 'exec': if (arguments.isEmpty) { throw const FormatException('exec requires a command.'); } executable = arguments.first; arguments = arguments.sublist(1); default: throw const FormatException('Expected flutter, dart or exec.'); } var command = executable; var commandArguments = arguments; if (Platform.isWindows && (executable.toLowerCase().endsWith('.bat') || executable.toLowerCase().endsWith('.cmd'))) { // cmd expands this variable once. Keeping the quoted command in the // environment avoids expanding literal %VAR% in Flutter arguments. environment['CUTDEX_LOCAL_FLUTTER_COMMAND'] = [ executable, ...arguments, ].map(_quoteWindowsBatchArgument).join(' '); command = 'cmd.exe'; commandArguments = ['/d', '/v:off', '/c', '%CUTDEX_LOCAL_FLUTTER_COMMAND%']; } final process = await Process.start( command, commandArguments, workingDirectory: (workingDirectory ?? root).path, environment: environment, includeParentEnvironment: false, mode: ProcessStartMode.inheritStdio, ); return process.exitCode; } String _quoteWindowsBatchArgument(String argument) { if (argument.contains('\n') || argument.contains('\r')) { throw const FormatException('Flutter arguments cannot contain newlines.'); } // Always quote, including shell metacharacters and empty arguments. Inside // quotes Windows' C argument parser accepts doubled quotes as literal quotes. final escaped = argument .replaceAllMapped(RegExp(r'(\\*)"'), (match) => '${match[1]! * 2}""') .replaceAllMapped(RegExp(r'(\\+)$'), (match) => match[1]! * 2); return '"$escaped"'; }