From 88150d1a1009f0437cacfbe2b07e65856bb5e6f3 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Thu, 4 Jan 2024 09:12:02 -0500 Subject: [PATCH 1/7] Update dcm rules --- analysis_options.yaml | 27 +++++++++++++++++++++++++++ pubspec.lock | 8 ++++++++ pubspec.yaml | 1 + 3 files changed, 36 insertions(+) diff --git a/analysis_options.yaml b/analysis_options.yaml index 72bbe6e9..604e4671 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -5,3 +5,30 @@ analyzer: unused_local_variable: error dead_code: error avoid_void_async: error +linter: + rules: + public_member_api_docs: false + prefer_relative_imports: true +dart_code_metrics: + extends: + - package:dart_code_metrics_presets/recommended.yaml + metrics-exclude: + - test/** + rules-exclude: + - "test/**" + rules: + member-ordering: + order: + - public-fields + - private-fields + - constructors + - static-methods + - private-methods + - private-getters + - private-setters + - public-getters + - public-setters + - public-methods + - overridden-public-methods + - overridden-public-getters + - build-method \ No newline at end of file diff --git a/pubspec.lock b/pubspec.lock index a425adb7..87e539f4 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -129,6 +129,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.3" + dart_code_metrics_presets: + dependency: "direct dev" + description: + name: dart_code_metrics_presets + sha256: "06e1aea3e4c2beb555ed1ac92366fbc8040ad0b36a0dbd4ec501c11cdb3e57a8" + url: "https://pub.dev" + source: hosted + version: "2.7.0" dart_console: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 138979ae..dc717d8c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -35,4 +35,5 @@ dev_dependencies: lints: ^2.1.1 crypto: ^3.0.3 http: ^1.1.0 + dart_code_metrics_presets: ^2.7.0 From 3062fe095f25a34a63cbb8baa28cae8bec128b51 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Thu, 4 Jan 2024 09:12:58 -0500 Subject: [PATCH 2/7] dcm fix --- bin/main.dart | 16 +-- lib/constants.dart | 6 +- lib/exceptions.dart | 5 +- lib/src/commands/base_command.dart | 5 +- lib/src/commands/dart_command.dart | 4 +- lib/src/commands/doctor_command.dart | 82 +++++------- lib/src/commands/exec_command.dart | 11 +- lib/src/commands/global_command.dart | 6 +- lib/src/commands/install_command.dart | 14 +- lib/src/commands/list_command.dart | 8 +- lib/src/commands/releases_command.dart | 2 +- lib/src/commands/remove_command.dart | 18 +-- lib/src/commands/update_command.dart | 21 ++- lib/src/commands/use_command.dart | 6 +- .../models/cache_flutter_version_model.dart | 16 +-- lib/src/models/config_model.dart | 126 +++++++++--------- lib/src/models/flutter_version_model.dart | 6 +- lib/src/models/project_model.dart | 74 +++++----- lib/src/runner.dart | 106 +++++++-------- lib/src/services/cache_service.dart | 50 ++++--- lib/src/services/config_repository.dart | 6 +- lib/src/services/flutter_service.dart | 48 +++---- lib/src/services/global_version_service.dart | 7 +- lib/src/services/logger_service.dart | 37 +++-- lib/src/services/project_service.dart | 12 +- .../models/flutter_releases.model.dart | 31 ++--- .../models/release.model.dart | 62 ++++----- .../releases_service/releases_client.dart | 19 +-- lib/src/utils/change_case.dart | 28 ++-- lib/src/utils/commands.dart | 32 ++--- lib/src/utils/console_utils.dart | 12 +- lib/src/utils/context.dart | 39 +++--- lib/src/utils/deprecation_util.dart | 4 +- lib/src/utils/extensions.dart | 5 +- lib/src/utils/helpers.dart | 13 +- lib/src/utils/http.dart | 5 +- .../parsers/git_clone_update_printer.dart | 4 +- lib/src/utils/run_command.dart | 31 +++-- lib/src/utils/which.dart | 5 +- lib/src/workflows/ensure_cache.workflow.dart | 41 ++---- lib/src/workflows/setup_flutter.workflow.dart | 9 +- lib/src/workflows/use_version.workflow.dart | 73 +++------- tool/grind.dart | 8 +- tool/homebrew.dart | 13 +- 44 files changed, 477 insertions(+), 649 deletions(-) diff --git a/bin/main.dart b/bin/main.dart index d4706b32..1801a427 100755 --- a/bin/main.dart +++ b/bin/main.dart @@ -1,22 +1,14 @@ -#!/usr/bin/env dart - -import 'dart:io'; +#!/usr/bin/env dartimport 'dart:io'; import 'package:fvm/src/runner.dart'; import 'package:fvm/src/utils/context.dart'; import 'package:scope/scope.dart'; Future main(List args) async { - final scope = Scope() - ..value( - contextKey, - FVMContext.create(), - ); + final scope = Scope()..value(contextKey, FVMContext.create()); await _flushThenExit( - await scope.run( - () => FvmCommandRunner().run((args)), - ), + await scope.run(() => FvmCommandRunner().run((args))), ); } @@ -28,5 +20,5 @@ Future main(List args) async { /// after you've decided to exit. Future _flushThenExit(int status) { return Future.wait([stdout.close(), stderr.close()]) - .then((_) => exit(status)); + .then((_) => exit(status)); } diff --git a/lib/constants.dart b/lib/constants.dart index 7fdf963f..2372c2a1 100644 --- a/lib/constants.dart +++ b/lib/constants.dart @@ -47,11 +47,7 @@ final kAppDirHome = join(kUserHome, kPackageName); /// Flutter Channels const kFlutterChannels = ['master', 'stable', 'dev', 'beta']; -final kAppConfigFile = join( - _configHome, - kPackageName, - kFvmConfigFileName, -); +final kAppConfigFile = join(_configHome, kPackageName, kFvmConfigFileName); String get _configHome { if (Platform.isWindows) { diff --git a/lib/exceptions.dart b/lib/exceptions.dart index 3637b133..83b48053 100644 --- a/lib/exceptions.dart +++ b/lib/exceptions.dart @@ -18,10 +18,7 @@ class AppDetailedException extends AppException { final String info; /// Constructor - const AppDetailedException( - super.message, - this.info, - ); + const AppDetailedException(super.message, this.info); @override String toString() => message; diff --git a/lib/src/commands/base_command.dart b/lib/src/commands/base_command.dart index 07b74006..f4f97706 100644 --- a/lib/src/commands/base_command.dart +++ b/lib/src/commands/base_command.dart @@ -4,9 +4,6 @@ import 'package:args/command_runner.dart'; abstract class BaseCommand extends Command { BaseCommand(); - @override - String get invocation => 'fvm $name'; - /// Checks if the command-line option named [name] was parsed. bool wasParsed(String name) => argResults!.wasParsed(name); @@ -24,4 +21,6 @@ abstract class BaseCommand extends Command { /// Gets the parsed command-line option named [name] as `List`. List stringsArg(String name) => argResults![name] as List; + @override + String get invocation => 'fvm $name'; } diff --git a/lib/src/commands/dart_command.dart b/lib/src/commands/dart_command.dart index d4e46e13..c6fb5dc1 100644 --- a/lib/src/commands/dart_command.dart +++ b/lib/src/commands/dart_command.dart @@ -9,8 +9,6 @@ import 'base_command.dart'; /// Proxies Dart Commands class DartCommand extends BaseCommand { - DartCommand(); - @override final name = 'dart'; @override @@ -18,6 +16,8 @@ class DartCommand extends BaseCommand { @override final argParser = ArgParser.allowAnything(); + DartCommand(); + @override Future run() async { final version = ProjectService.fromContext.findVersion(); diff --git a/lib/src/commands/doctor_command.dart b/lib/src/commands/doctor_command.dart index 555f2d88..be817b9a 100644 --- a/lib/src/commands/doctor_command.dart +++ b/lib/src/commands/doctor_command.dart @@ -23,28 +23,11 @@ class DoctorCommand extends BaseCommand { final description = 'Shows information about environment, ' 'and project configuration.'; - /// Constructor - DoctorCommand(); - final console = Console(); - @override - Future run() async { - final project = ProjectService.fromContext.findAncestor(); - final flutterWhich = which('flutter'); - final dartWhich = which('dart'); - - console.writeLine('FVM Doctor:'); - console.writeLine('-' * console.windowWidth); - - _printProject(project); - _printIdeLinks(project); - _printEnvironmentDetails(flutterWhich, dartWhich); - - return ExitCode.success.code; - } + /// Constructor + DoctorCommand(); - void printFVMDetails(FVMContext context) {} void _printProject(Project project) { logger.info('Project:'); final table = createTable(['Project', project.name]); @@ -55,7 +38,7 @@ class DoctorCommand extends BaseCommand { ['Is Flutter Project', project.isFlutter ? 'Yes' : 'No'], [ 'Dart Tool Generator Version', - project.dartToolGeneratorVersion ?? 'Not available' + project.dartToolGeneratorVersion ?? 'Not available', ], ['Dart tool version', project.dartToolVersion ?? 'Not available'], ['.gitignore Present', project.gitignoreFile.existsSync() ? 'Yes' : 'No'], @@ -64,14 +47,11 @@ class DoctorCommand extends BaseCommand { ['Config path', relative(project.configPath, from: project.path)], [ 'Local cache dir', - relative(project.localVersionsCachePath, from: project.path) + relative(project.localVersionsCachePath, from: project.path), ], [ 'Version symlink', - relative( - project.localVersionSymlinkPath, - from: project.path, - ) + relative(project.localVersionSymlinkPath, from: project.path), ], ]); @@ -105,12 +85,14 @@ class DoctorCommand extends BaseCommand { table.insertRow(['dart.flutterSdkPath', sdkPath ?? 'None']); table.insertRow( - ['Matches pinned version:', sdkPath == relativeSymlinkPath]); + ['Matches pinned version:', sdkPath == relativeSymlinkPath], + ); } on FormatException { logger ..err('Error parsing Vscode settings.json on ${settingsFile.path}') ..err( - 'Please use a tool like https://jsonformatter.curiousconcept.com to validate and fix it'); + 'Please use a tool like https://jsonformatter.curiousconcept.com to validate and fix it', + ); throw AppException( 'Could not get vscode settings, please check settings.json', ); @@ -141,11 +123,12 @@ class DoctorCommand extends BaseCommand { } else { table.insertRow([ kIntelliJ, - 'No local.properties file found in android directory' + 'No local.properties file found in android directory', ]); } - final dartSdkFile = File(join(project.path, '.idea', 'libraries', 'Dart_SDK.xml')); + final dartSdkFile = + File(join(project.path, '.idea', 'libraries', 'Dart_SDK.xml')); if (dartSdkFile.existsSync()) { final dartSdk = dartSdkFile.readAsStringSync(); @@ -157,42 +140,36 @@ class DoctorCommand extends BaseCommand { if (containsSymLinkName) { table.insertRow([ 'SDK Path', - 'SDK Path points to project directory. $kIntelliJ will dynamically switch SDK when using "fvm use"' + 'SDK Path points to project directory. $kIntelliJ will dynamically switch SDK when using "fvm use"', ]); - } - else { + } else { table.insertRow([ 'SDK Path', - 'SDK Path points to project directory, but does not use the flutter_sdk symlink. Using "fvm use" will break the project. Please consult documentation.' + 'SDK Path points to project directory, but does not use the flutter_sdk symlink. Using "fvm use" will break the project. Please consult documentation.', ]); } } else { table.insertRow([ 'SDK Path', - 'SDK Path does not point to the project directory. "fvm use" will not make $kIntelliJ switch Flutter version. Please consult documentation.' + 'SDK Path does not point to the project directory. "fvm use" will not make $kIntelliJ switch Flutter version. Please consult documentation.', ]); } } else { table.insertRow([ kIntelliJ, - 'No .idea folder found' + 'No .idea folder found', ]); } logger.write(table.toString()); } - void _printEnvironmentDetails( - String? flutterWhich, - String? dartWhich, - ) { + void _printEnvironmentDetails(String? flutterWhich, String? dartWhich) { logger ..spacer ..info('Environment:'); - var table = createTable( - ['Environment Variables', 'Value'], - ); + var table = createTable(['Environment Variables', 'Value']); table.insertRows([ ['Flutter PATH', flutterWhich ?? 'Not found'], @@ -210,9 +187,7 @@ class DoctorCommand extends BaseCommand { logger.write(table.toString()); - table = createTable( - ['Platform', 'Value'], - ); + table = createTable(['Platform', 'Value']); table.insertRows([ ['OS', '${Platform.operatingSystem} ${Platform.operatingSystemVersion}'], @@ -222,4 +197,21 @@ class DoctorCommand extends BaseCommand { logger.write(table.toString()); } + + void printFVMDetails() {} + @override + Future run() async { + final project = ProjectService.fromContext.findAncestor(); + final flutterWhich = which('flutter'); + final dartWhich = which('dart'); + + console.writeLine('FVM Doctor:'); + console.writeLine('-' * console.windowWidth); + + _printProject(project); + _printIdeLinks(project); + _printEnvironmentDetails(flutterWhich, dartWhich); + + return ExitCode.success.code; + } } diff --git a/lib/src/commands/exec_command.dart b/lib/src/commands/exec_command.dart index 32fd02b5..12f0a114 100644 --- a/lib/src/commands/exec_command.dart +++ b/lib/src/commands/exec_command.dart @@ -25,10 +25,7 @@ class ExecCommand extends BaseCommand { final version = ProjectService.fromContext.findVersion(); if (argResults!.rest.isEmpty) { - throw UsageException( - 'No command was provided to be executed', - usage, - ); + throw UsageException('No command was provided to be executed', usage); } final cmd = argResults!.rest[0]; @@ -48,11 +45,7 @@ class ExecCommand extends BaseCommand { } // Runs exec command with pinned version - final results = await execCmd( - cmd, - execArgs, - cacheVersion, - ); + final results = await execCmd(cmd, execArgs, cacheVersion); return results.exitCode; } diff --git a/lib/src/commands/global_command.dart b/lib/src/commands/global_command.dart index 68813d4b..f9344e37 100644 --- a/lib/src/commands/global_command.dart +++ b/lib/src/commands/global_command.dart @@ -25,9 +25,6 @@ class GlobalCommand extends BaseCommand { /// Constructor GlobalCommand(); - @override - String get invocation => 'fvm global {version}'; - @override Future run() async { String? version; @@ -102,4 +99,7 @@ class GlobalCommand extends BaseCommand { } return ExitCode.success.code; } + + @override + String get invocation => 'fvm global {version}'; } diff --git a/lib/src/commands/install_command.dart b/lib/src/commands/install_command.dart index 2e772ce9..505cb3bd 100644 --- a/lib/src/commands/install_command.dart +++ b/lib/src/commands/install_command.dart @@ -16,13 +16,6 @@ class InstallCommand extends BaseCommand { @override final description = 'Installs Flutter SDK Version'; - @override - String get invocation => 'fvm install {version}, if no {version}' - ' is provided will install version configured in project.'; - - @override - List get aliases => ['i']; - /// Constructor InstallCommand() { argParser.addFlag( @@ -64,4 +57,11 @@ class InstallCommand extends BaseCommand { return ExitCode.success.code; } + + @override + String get invocation => 'fvm install {version}, if no {version}' + ' is provided will install version configured in project.'; + + @override + List get aliases => ['i']; } diff --git a/lib/src/commands/list_command.dart b/lib/src/commands/list_command.dart index 98c0425f..47b44945 100644 --- a/lib/src/commands/list_command.dart +++ b/lib/src/commands/list_command.dart @@ -18,9 +18,6 @@ class ListCommand extends BaseCommand { @override final description = 'Lists installed Flutter SDK Versions'; - @override - List get aliases => ['ls']; - /// Constructor ListCommand(); @@ -95,7 +92,7 @@ class ListCommand extends BaseCommand { version.dartSdkVersion ?? '', releaseDate, globalVersion == version ? green.wrap(dot)! : '', - ] + ], ]) ..borderStyle = BorderStyle.square ..borderColor = ConsoleColor.white @@ -106,4 +103,7 @@ class ListCommand extends BaseCommand { return ExitCode.success.code; } + + @override + List get aliases => ['ls']; } diff --git a/lib/src/commands/releases_command.dart b/lib/src/commands/releases_command.dart index 0d68b430..bd5a8b49 100644 --- a/lib/src/commands/releases_command.dart +++ b/lib/src/commands/releases_command.dart @@ -97,7 +97,7 @@ class ReleasesCommand extends BaseCommand { channelsTable.insertRow([ release.channel.name, release.version, - friendlyDate(release.releaseDate) + friendlyDate(release.releaseDate), ]); } diff --git a/lib/src/commands/remove_command.dart b/lib/src/commands/remove_command.dart index c3c5f82a..2a031c96 100644 --- a/lib/src/commands/remove_command.dart +++ b/lib/src/commands/remove_command.dart @@ -12,6 +12,12 @@ import 'base_command.dart'; /// Removes Flutter SDK class RemoveCommand extends BaseCommand { + @override + final name = 'remove'; + + @override + final description = 'Removes Flutter SDK Version'; + RemoveCommand() { argParser.addFlag( 'all', @@ -21,15 +27,6 @@ class RemoveCommand extends BaseCommand { ); } - @override - final name = 'remove'; - - @override - final description = 'Removes Flutter SDK Version'; - - @override - String get invocation => 'fvm remove {version}'; - /// Constructor @override @@ -85,4 +82,7 @@ class RemoveCommand extends BaseCommand { return ExitCode.success.code; } + + @override + String get invocation => 'fvm remove {version}'; } diff --git a/lib/src/commands/update_command.dart b/lib/src/commands/update_command.dart index 7074c0ae..6fa02fd2 100644 --- a/lib/src/commands/update_command.dart +++ b/lib/src/commands/update_command.dart @@ -8,24 +8,17 @@ import 'package:mason_logger/mason_logger.dart'; import 'package:pub_updater/pub_updater.dart'; class UpdateCommand extends Command { - UpdateCommand({ - PubUpdater? pubUpdater, - }) : _pubUpdater = pubUpdater ?? PubUpdater(); + static const String commandName = 'update'; final PubUpdater _pubUpdater; - @override - String get description => 'Update the CLI.'; - - static const String commandName = 'update'; - - @override - String get name => commandName; + UpdateCommand({PubUpdater? pubUpdater}) + : _pubUpdater = pubUpdater ?? PubUpdater(); @override Future run() async { final updateCheckProgress = logger.progress('Checking for updates'); - late final String latestVersion; + final String latestVersion; try { latestVersion = await _pubUpdater.getLatestVersion(kPackageName); } catch (error) { @@ -65,4 +58,10 @@ class UpdateCommand extends Command { return ExitCode.success.code; } + + @override + String get description => 'Update the CLI.'; + + @override + String get name => commandName; } diff --git a/lib/src/commands/use_command.dart b/lib/src/commands/use_command.dart index f358c810..17746a1d 100644 --- a/lib/src/commands/use_command.dart +++ b/lib/src/commands/use_command.dart @@ -19,9 +19,6 @@ class UseCommand extends BaseCommand { String description = 'Sets Flutter SDK Version you would like to use in a project'; - @override - String get invocation => 'fvm use {version}'; - /// Constructor UseCommand() { argParser @@ -123,4 +120,7 @@ class UseCommand extends BaseCommand { return ExitCode.success.code; } + + @override + String get invocation => 'fvm use {version}'; } diff --git a/lib/src/models/cache_flutter_version_model.dart b/lib/src/models/cache_flutter_version_model.dart index 55c94f85..91c971fc 100644 --- a/lib/src/models/cache_flutter_version_model.dart +++ b/lib/src/models/cache_flutter_version_model.dart @@ -11,11 +11,12 @@ import '../../constants.dart'; /// Cache Version model class CacheFlutterVersion extends FlutterVersion { + /// Directory of the cache version + final String directory; + /// Constructor - CacheFlutterVersion( - FlutterVersion version, { - required this.directory, - }) : super( + CacheFlutterVersion(FlutterVersion version, {required this.directory}) + : super( version.name, releaseFromChannel: version.releaseFromChannel, isChannel: version.isChannel, @@ -24,8 +25,7 @@ class CacheFlutterVersion extends FlutterVersion { isCustom: version.isCustom, ); - /// Directory of the cache version - final String directory; + String get _dartSdkCache => join(binPath, 'cache', 'dart-sdk'); /// Get version bin path String get binPath => join(directory, 'bin'); @@ -36,8 +36,6 @@ class CacheFlutterVersion extends FlutterVersion { return compareSemver(assignVersionWeight(version), '1.17.5') <= 0; } - String get _dartSdkCache => join(binPath, 'cache', 'dart-sdk'); - /// Returns dart exec file for cache version String get dartBinPath { /// Get old bin path @@ -70,7 +68,7 @@ class CacheFlutterVersion extends FlutterVersion { String command, { bool echoOutput = false, bool? throwOnError, - }) async { + }) { return runFlutter( command.split(' '), version: this, diff --git a/lib/src/models/config_model.dart b/lib/src/models/config_model.dart index 2a2f0617..f5a1559a 100644 --- a/lib/src/models/config_model.dart +++ b/lib/src/models/config_model.dart @@ -12,33 +12,21 @@ import 'package:fvm/src/utils/pretty_json.dart'; class ConfigKeys { final String key; - const ConfigKeys(this.key); - - @override - operator ==(other) => other is ConfigKeys && other.key == key; - - @override - int get hashCode => key.hashCode; - - ChangeCase get _recase => ChangeCase(key); - static const ConfigKeys cachePath = ConfigKeys('cache_path'); static const ConfigKeys useGitCache = ConfigKeys('git_cache'); static const ConfigKeys gitCachePath = ConfigKeys('git_cache_path'); static const ConfigKeys flutterUrl = ConfigKeys('flutter_url'); static const ConfigKeys priviledgedAccess = ConfigKeys('priviledged_access'); - String get envKey => 'FVM_${_recase.constantCase}'; - String get paramKey => _recase.paramCase; - String get propKey => _recase.camelCase; - static const values = [ cachePath, useGitCache, gitCachePath, - flutterUrl + flutterUrl, ]; + const ConfigKeys(this.key); + static ConfigKeys fromName(String name) { return values.firstWhere((e) => e.key == name); } @@ -92,13 +80,25 @@ class ConfigKeys { negatable: true, defaultsTo: true, ); - } + }, }; for (final key in values) { configKeysFuncs[key.key]?.call(); } } + + ChangeCase get _recase => ChangeCase(key); + + String get envKey => 'FVM_${_recase.constantCase}'; + String get paramKey => _recase.paramCase; + String get propKey => _recase.camelCase; + + @override + operator ==(other) => other is ConfigKeys && other.key == key; + + @override + int get hashCode => key.hashCode; } class Config { @@ -146,7 +146,7 @@ class Config { } Map toMap() { - return { + return { if (cachePath != null) ConfigKeys.cachePath.propKey: cachePath, if (useGitCache != null) ConfigKeys.useGitCache.propKey: useGitCache, if (gitCachePath != null) ConfigKeys.gitCachePath.propKey: gitCachePath, @@ -186,14 +186,6 @@ class AppConfig extends Config { ); } - static AppConfig? loadFromPath(String path) { - final configFile = File(path); - - return configFile.existsSync() - ? AppConfig.fromJson(configFile.readAsStringSync()) - : null; - } - factory AppConfig.fromMap(Map map) { final envConfig = Config.fromMap(map); return AppConfig( @@ -209,20 +201,18 @@ class AppConfig extends Config { ); } - @override - Map toMap() { - return { - ...super.toMap(), - if (disableUpdateCheck != null) 'disableUpdateCheck': disableUpdateCheck, - if (lastUpdateCheck != null) - 'lastUpdateCheck': lastUpdateCheck?.toIso8601String(), - }; - } - factory AppConfig.fromJson(String source) { return AppConfig.fromMap(json.decode(source) as Map); } + static AppConfig? loadFromPath(String path) { + final configFile = File(path); + + return configFile.existsSync() + ? AppConfig.fromJson(configFile.readAsStringSync()) + : null; + } + AppConfig copyWith({ String? cachePath, bool? useGitCache, @@ -270,6 +260,16 @@ class AppConfig extends Config { path.file.write(jsonContents); } + + @override + Map toMap() { + return { + ...super.toMap(), + if (disableUpdateCheck != null) 'disableUpdateCheck': disableUpdateCheck, + if (lastUpdateCheck != null) + 'lastUpdateCheck': lastUpdateCheck?.toIso8601String(), + }; + } } /// Project config @@ -318,21 +318,10 @@ class ProjectConfig extends Config { flutterSdkVersion: map['flutterSdkVersion'] ?? map['flutter'] as String?, updateVscodeSettings: map['updateVscodeSettings'] as bool?, runPubGetOnSdkChanges: map['runPubGetOnSdkChanges'] as bool?, - flavors: map['flavors'] != null - ? Map.from(map['flavors'] as Map) - : null, + flavors: map['flavors'] != null ? Map.from(map['flavors'] as Map) : null, ); } - /// Returns update vscode settings - bool? get updateVscodeSettings => _updateVscodeSettings; - - /// Returns update git ignore - bool? get updateGitIgnore => _updateGitIgnore; - - /// Returns run pub get on sdk changes - bool? get runPubGetOnSdkChanges => _runPubGetOnSdkChanges; - /// Returns ConfigDto from a json string factory ProjectConfig.fromJson(String source) => ProjectConfig.fromMap(json.decode(source) as Map); @@ -345,30 +334,20 @@ class ProjectConfig extends Config { : null; } - /// It checks each property for null prior to adding it to the map. - /// This is to ensure the returned map doesn't contain any null values. - /// Also, if [flavors] is not empty it adds it to the map. + /// Returns update vscode settings + bool? get updateVscodeSettings => _updateVscodeSettings; - @override - Map toMap() { - return { - ...super.toMap(), - if (flutterSdkVersion != null) 'flutter': flutterSdkVersion, - if (_updateVscodeSettings != null) - 'updateVscodeSettings': _updateVscodeSettings, - if (_updateGitIgnore != null) 'updateGitIgnore': _updateGitIgnore, - if (_runPubGetOnSdkChanges != null) - 'runPubGetOnSdkChanges': _runPubGetOnSdkChanges, - if (flavors != null && flavors!.isNotEmpty) 'flavors': flavors, - }; - } + /// Returns update git ignore + bool? get updateGitIgnore => _updateGitIgnore; + + /// Returns run pub get on sdk changes + bool? get runPubGetOnSdkChanges => _runPubGetOnSdkChanges; /// Copies current config and overrides with new values /// Returns a new ConfigDto ProjectConfig copyWith({ String? cachePath, - String? fvmVersionsDir, String? flutterSdkVersion, bool? useGitCache, bool? updateVscodeSettings, @@ -378,7 +357,6 @@ class ProjectConfig extends Config { String? gitCachePath, String? flutterUrl, Map? flavors, - bool? disableUpdate, }) { // merge map and override the keys final mergedFlavors = { @@ -420,4 +398,22 @@ class ProjectConfig extends Config { path.file.write(jsonContents); } + + /// It checks each property for null prior to adding it to the map. + /// This is to ensure the returned map doesn't contain any null values. + /// Also, if [flavors] is not empty it adds it to the map. + + @override + Map toMap() { + return { + ...super.toMap(), + if (flutterSdkVersion != null) 'flutter': flutterSdkVersion, + if (_updateVscodeSettings != null) + 'updateVscodeSettings': _updateVscodeSettings, + if (_updateGitIgnore != null) 'updateGitIgnore': _updateGitIgnore, + if (_runPubGetOnSdkChanges != null) + 'runPubGetOnSdkChanges': _runPubGetOnSdkChanges, + if (flavors != null && flavors!.isNotEmpty) 'flavors': flavors, + }; + } } diff --git a/lib/src/models/flutter_version_model.dart b/lib/src/models/flutter_version_model.dart index 34780d81..ecf9a424 100644 --- a/lib/src/models/flutter_version_model.dart +++ b/lib/src/models/flutter_version_model.dart @@ -61,10 +61,8 @@ class FlutterVersion { isChannel = false, isCustom = true; - const FlutterVersion.release( - this.name, { - this.releaseFromChannel, - }) : isRelease = true, + const FlutterVersion.release(this.name, {this.releaseFromChannel}) + : isRelease = true, isCommit = false, isChannel = false, isCustom = false; diff --git a/lib/src/models/project_model.dart b/lib/src/models/project_model.dart index e9671390..2449a5a4 100644 --- a/lib/src/models/project_model.dart +++ b/lib/src/models/project_model.dart @@ -24,16 +24,39 @@ class Project { final PubSpec? pubspec; + const + /// Creates a new instance of [Project]. /// /// The [config] parameter represents the configuration of the project. /// The [path] parameter is the directory path of the project. /// The [pubspec] parameter represents the pubspec.yaml file of the project. - Project({ - required this.config, - required this.path, - required this.pubspec, - }); + Project({required this.config, required this.path, required this.pubspec}); + + /// Loads the Flutter project from the given [path]. + /// + /// The project is loaded by locating the FVM config file and the pubspec.yaml file. + static Project loadFromPath(String path) { + final configFile = _fvmConfigPath(path); + final legacyConfigFile = _legacyFvmConfigPath(path); + + // Used for migration of config files + final legacyConfig = ProjectConfig.loadFromPath(legacyConfigFile); + + if (legacyConfig != null) { + legacyConfig.save(configFile); + legacyConfigFile.file.deleteSync(); + } + + final config = ProjectConfig.loadFromPath(configFile); + + final pubspecFile = File(join(path, 'pubspec.yaml')); + final pubspec = pubspecFile.existsSync() + ? PubSpec.fromYamlString(pubspecFile.readAsStringSync()) + : null; + + return Project(path: path, pubspec: pubspec, config: config); + } /// Retrieves the name of the project. String get name => basename(path); @@ -86,10 +109,7 @@ class Project { /// Returns the path of the Flutter SDK symlink within the project. String get localVersionSymlinkPath { - return join( - localVersionsCachePath, - pinnedVersion?.name, - ); + return join(localVersionsCachePath, pinnedVersion?.name); } /// Indicates whether the project has `.gitignore` file. @@ -111,35 +131,6 @@ class Project { /// /// Returns `null` if the constraint is not defined. VersionConstraint? get sdkConstraint => pubspec?.environment?.sdkConstraint; - - /// Loads the Flutter project from the given [path]. - /// - /// The project is loaded by locating the FVM config file and the pubspec.yaml file. - static Project loadFromPath(String path) { - final configFile = _fvmConfigPath(path); - final legacyConfigFile = _legacyFvmConfigPath(path); - - // Used for migration of config files - final legacyConfig = ProjectConfig.loadFromPath(legacyConfigFile); - - if (legacyConfig != null) { - legacyConfig.save(configFile); - legacyConfigFile.file.deleteSync(); - } - - final config = ProjectConfig.loadFromPath(configFile); - - final pubspecFile = File(join(path, 'pubspec.yaml')); - final pubspec = pubspecFile.existsSync() - ? PubSpec.fromYamlString(pubspecFile.readAsStringSync()) - : null; - - return Project( - path: path, - pubspec: pubspec, - config: config, - ); - } } String _fvmPath(String path) { @@ -158,13 +149,12 @@ String _dartToolPath(String projectPath) { return join(projectPath, '.dart_tool'); } -String? _dartToolGeneratorVersion(String projectPath) { +String _dartToolGeneratorVersion(String projectPath) { final file = File(join(_dartToolPath(projectPath), 'package_config.json')); return file.existsSync() - ? (jsonDecode( - file.readAsStringSync(), - ) as Map)['generatorVersion'] + ? (jsonDecode(file.readAsStringSync()) + as Map)['generatorVersion'] : null; } diff --git a/lib/src/runner.dart b/lib/src/runner.dart index a8c40108..c9b45091 100644 --- a/lib/src/runner.dart +++ b/lib/src/runner.dart @@ -30,20 +30,14 @@ import 'version.g.dart'; /// Command Runner for FVM class FvmCommandRunner extends CommandRunner { + final PubUpdater _pubUpdater; + /// Constructor - FvmCommandRunner({ - PubUpdater? pubUpdater, - }) : _pubUpdater = pubUpdater ?? PubUpdater(), - super( - kPackageName, - kDescription, - ) { + FvmCommandRunner({PubUpdater? pubUpdater}) + : _pubUpdater = pubUpdater ?? PubUpdater(), + super(kPackageName, kDescription) { argParser - ..addFlag( - 'verbose', - help: 'Print verbose output.', - negatable: false, - ) + ..addFlag('verbose', help: 'Print verbose output.', negatable: false) ..addFlag( 'version', abbr: 'v', @@ -65,7 +59,48 @@ class FvmCommandRunner extends CommandRunner { addCommand(GlobalCommand()); } - final PubUpdater _pubUpdater; + /// Checks if the current version (set by the build runner on the + /// version.dart file) is the most recent one. If not, show a prompt to the + /// user. + Future _checkForUpdates() async { + try { + if (ctx.updateCheckDisabled) return null; + final oneDayAgo = DateTime.now().subtract(const Duration(days: 1)); + if (ctx.lastUpdateCheck?.isBefore(oneDayAgo) ?? false) { + return null; + } + + ConfigRepository.update(lastUpdateCheck: DateTime.now()); + + final isUpToDate = await _pubUpdater.isUpToDate( + packageName: kPackageName, + currentVersion: packageVersion, + ); + + if (isUpToDate) return null; + + final latestVersion = await _pubUpdater.getLatestVersion(kPackageName); + + return () { + final updateAvailableLabel = lightYellow.wrap('Update available!'); + final currentVersionLabel = lightCyan.wrap(packageVersion); + final latestVersionLabel = lightCyan.wrap(latestVersion); + final updateCommandLabel = lightCyan.wrap('$executableName update'); + + logger + ..spacer + ..info( + '$updateAvailableLabel $currentVersionLabel \u2192 $latestVersionLabel', + ) + ..info('Run $updateCommandLabel to update') + ..spacer; + }; + } catch (_) { + return () { + logger.detail("Failed to check for updates."); + }; + } + } @override void printUsage() => logger.info(usage); @@ -209,51 +244,6 @@ class FvmCommandRunner extends CommandRunner { return exitCode; } - - /// Checks if the current version (set by the build runner on the - /// version.dart file) is the most recent one. If not, show a prompt to the - /// user. - Future _checkForUpdates() async { - try { - if (ctx.updateCheckDisabled) return null; - final oneDayAgo = DateTime.now().subtract(const Duration(days: 1)); - if (ctx.lastUpdateCheck?.isBefore(oneDayAgo) ?? false) { - return null; - } - - ConfigRepository.update( - lastUpdateCheck: DateTime.now(), - ); - - final isUpToDate = await _pubUpdater.isUpToDate( - packageName: kPackageName, - currentVersion: packageVersion, - ); - - if (isUpToDate) return null; - - final latestVersion = await _pubUpdater.getLatestVersion(kPackageName); - - return () { - final updateAvailableLabel = lightYellow.wrap('Update available!'); - final currentVersionLabel = lightCyan.wrap(packageVersion); - final latestVersionLabel = lightCyan.wrap(latestVersion); - final updateCommandLabel = lightCyan.wrap('$executableName update'); - - logger - ..spacer - ..info( - '$updateAvailableLabel $currentVersionLabel \u2192 $latestVersionLabel', - ) - ..info('Run $updateCommandLabel to update') - ..spacer; - }; - } catch (_) { - return () { - logger.detail("Failed to check for updates."); - }; - } - } } void _printTrace(StackTrace stackTrace) { diff --git a/lib/src/services/cache_service.dart b/lib/src/services/cache_service.dart index d8e40c3a..6f970791 100644 --- a/lib/src/services/cache_service.dart +++ b/lib/src/services/cache_service.dart @@ -18,22 +18,34 @@ enum CacheIntegrity { /// Service to interact with FVM Cache class CacheService extends ContextService { - CacheService(super.context); + const CacheService(super.context); + + /// Verifies that cache is correct + /// returns 'true' if cache is correct 'false' if its not + Future _verifyIsExecutable(CacheFlutterVersion version) async { + final binExists = File(version.flutterExec).existsSync(); + + return binExists && await isExecutable(version.flutterExec); + } + + // Verifies that the cache version name matches the flutter version + bool _verifyVersionMatch(CacheFlutterVersion version) { + // If its a channel return true + if (version.isChannel) return true; + // If sdkVersion is not available return true + if (version.flutterSdkVersion == null) return true; + return version.flutterSdkVersion == version.version; + } /// Directory where local versions are cached - static CacheService get fromContext => getProvider(); + static CacheService get fromContext => getProvider(); /// Returns a [CacheFlutterVersion] from a [version] - CacheFlutterVersion? getVersion( - FlutterVersion version, - ) { + CacheFlutterVersion? getVersion(FlutterVersion version) { final versionDir = getVersionCacheDir(version.name); // Return null if version does not exist if (!versionDir.existsSync()) return null; - return CacheFlutterVersion( - version, - directory: versionDir.path, - ); + return CacheFlutterVersion(version, directory: versionDir.path); } /// Lists Installed Flutter SDK Version @@ -68,30 +80,14 @@ class CacheService extends ContextService { if (versionDir.existsSync()) versionDir.deleteSync(recursive: true); } - /// Verifies that cache is correct - /// returns 'true' if cache is correct 'false' if its not - Future _verifyIsExecutable(CacheFlutterVersion version) async { - final binExists = File(version.flutterExec).existsSync(); - - return binExists && await isExecutable(version.flutterExec); - } - - // Verifies that the cache version name matches the flutter version - bool _verifyVersionMatch(CacheFlutterVersion version) { - // If its a channel return true - if (version.isChannel) return true; - // If sdkVersion is not available return true - if (version.flutterSdkVersion == null) return true; - return version.flutterSdkVersion == version.version; - } - Directory getVersionCacheDir(String version) { return Directory(path.join(context.versionsCachePath, version)); } // Verifies that cache can be executed and matches version Future verifyCacheIntegrity( - CacheFlutterVersion version) async { + CacheFlutterVersion version, + ) async { final isExecutable = await _verifyIsExecutable(version); final versionsMatch = _verifyVersionMatch(version); diff --git a/lib/src/services/config_repository.dart b/lib/src/services/config_repository.dart index 7ecc601d..adaf0324 100644 --- a/lib/src/services/config_repository.dart +++ b/lib/src/services/config_repository.dart @@ -7,9 +7,7 @@ import '../../fvm.dart'; /// Service to manage FVM Config class ConfigRepository { - ConfigRepository._(); - - static String get _configPath => kAppConfigFile; + const ConfigRepository._(); static AppConfig loadFile() { final appConfig = AppConfig.loadFromPath(_configPath); @@ -90,4 +88,6 @@ class ConfigRepository { priviledgedAccess: priviledgedAccess, ); } + + static String get _configPath => kAppConfigFile; } diff --git a/lib/src/services/flutter_service.dart b/lib/src/services/flutter_service.dart index a7b5c5cb..ebab641e 100644 --- a/lib/src/services/flutter_service.dart +++ b/lib/src/services/flutter_service.dart @@ -18,9 +18,19 @@ import '../utils/commands.dart'; /// Helpers and tools to interact with Flutter sdk class FlutterService extends ContextService { - FlutterService(super.context); + const FlutterService(super.context); - static FlutterService get fromContext => getProvider(); + // Ensures cache.dir exists and its up to date + Future _ensureCacheDir() async { + final isGitDir = await GitDir.isGitDir(context.gitCachePath); + + // If cache file does not exists create it + if (!isGitDir) { + await updateLocalMirror(); + } + } + + static FlutterService get fromContext => getProvider(); /// Upgrades a cached channel Future runUpgrade(CacheFlutterVersion version) async { @@ -59,10 +69,7 @@ class FlutterService extends ContextService { channel ?? version.name, ]; - final useMirrorParams = [ - '--reference', - context.gitCachePath, - ]; + final useMirrorParams = ['--reference', context.gitCachePath]; final cloneArgs = [ //if its a git hash @@ -71,16 +78,13 @@ class FlutterService extends ContextService { ]; try { - final result = await runGit( - [ - 'clone', - '--progress', - ...cloneArgs, - context.flutterUrl, - versionDir.path, - ], - echoOutput: context.isTest || !logger.isVerbose ? false : true, - ); + final result = await runGit([ + 'clone', + '--progress', + ...cloneArgs, + context.flutterUrl, + versionDir.path, + ], echoOutput: !(context.isTest || !logger.isVerbose)); final gitVersionDir = CacheService(context).getVersionCacheDir(version.name); @@ -108,8 +112,6 @@ class FlutterService extends ContextService { CacheService(context).remove(version); rethrow; } - - return; } /// Updates local Flutter repo mirror @@ -143,16 +145,6 @@ class FlutterService extends ContextService { } } - // Ensures cache.dir exists and its up to date - Future _ensureCacheDir() async { - final isGitDir = await GitDir.isGitDir(context.gitCachePath); - - // If cache file does not exists create it - if (!isGitDir) { - await updateLocalMirror(); - } - } - /// Gets a commit for the Flutter repo /// If commit does not exist returns null Future isCommit(String commit) async { diff --git a/lib/src/services/global_version_service.dart b/lib/src/services/global_version_service.dart index de0be2b2..f8b40ec8 100644 --- a/lib/src/services/global_version_service.dart +++ b/lib/src/services/global_version_service.dart @@ -11,16 +11,15 @@ import 'package:path/path.dart' as path; class GlobalVersionService extends ContextService { const GlobalVersionService(super.context); - static GlobalVersionService get fromContext => - getProvider(); + Link get _globalCacheLink => Link(context.globalCacheLink); + + static GlobalVersionService get fromContext => getProvider(); /// Sets a [CacheFlutterVersion] as global void setGlobal(CacheFlutterVersion version) { context.globalCacheLink.link.createLink(version.directory); } - Link get _globalCacheLink => Link(context.globalCacheLink); - /// Returns a global [CacheFlutterVersion] if exists CacheFlutterVersion? getGlobal() { if (!_globalCacheLink.existsSync()) return null; diff --git a/lib/src/services/logger_service.dart b/lib/src/services/logger_service.dart index e832df5b..b17e093b 100644 --- a/lib/src/services/logger_service.dart +++ b/lib/src/services/logger_service.dart @@ -8,26 +8,34 @@ import 'package:mason_logger/mason_logger.dart'; import 'package:tint/tint.dart'; /// Sets default logger mode -LoggerService get logger => getProvider(); +LoggerService get logger => getProvider(); class LoggerService extends ContextService { final Logger _logger; /// Constructor - LoggerService({ - Level? level, - FVMContext? context, - }) : _logger = Logger(level: level ?? Level.info), + LoggerService({Level? level, FVMContext? context}) + : _logger = Logger(level: level ?? Level.info), super(context); void get spacer => _logger.info(''); bool get isVerbose => _logger.level == Level.verbose; - set level(Level level) => _logger.level = level; - Level get level => _logger.level; + String get stdout { + return logger.stdout; + } + + void get divider { + _logger.info( + '------------------------------------------------------------', + ); + } + + set level(Level level) => _logger.level = level; + void success(String message) { _logger.info('${Icons.success.green()} $message'); } @@ -61,14 +69,7 @@ class LoggerService extends ContextService { .interact(); } - String get stdout { - return logger.stdout; - } - - String select( - String? message, { - required List options, - }) { + String select(String? message, {required List options}) { final selection = interact.Select( prompt: message ?? '', options: options, @@ -105,12 +106,6 @@ class LoggerService extends ContextService { _logger.write(table.toString()); } - - void get divider { - _logger.info( - '------------------------------------------------------------', - ); - } } final dot = '\u{25CF}'; // ● diff --git a/lib/src/services/project_service.dart b/lib/src/services/project_service.dart index 3fc4ae26..e730c9b1 100644 --- a/lib/src/services/project_service.dart +++ b/lib/src/services/project_service.dart @@ -13,10 +13,10 @@ import 'package:path/path.dart' as path; /// /// This class provides methods for interacting with local Flutter projects. class ProjectService extends ContextService { - ProjectService(super.context); + const ProjectService(super.context); /// Gets project service from context - static ProjectService get fromContext => getProvider(); + static ProjectService get fromContext => getProvider(); /// Recursive look up to find nested project directory /// Can start at a specific [directory] if provided @@ -27,9 +27,7 @@ class ProjectService extends ContextService { /// current working directory. /// /// Returns the [Project] instance for the found project. - Project findAncestor({ - Directory? directory, - }) { + Project findAncestor({Directory? directory}) { // Get directory, defined root or current directory ??= Directory(context.workingDirectory); @@ -48,9 +46,7 @@ class ProjectService extends ContextService { // Return working directory if has reached root if (isRootDir) return Project.loadFromPath(context.workingDirectory); - return findAncestor( - directory: directory.parent, - ); + return findAncestor(directory: directory.parent); } /// Search for version configured diff --git a/lib/src/services/releases_service/models/flutter_releases.model.dart b/lib/src/services/releases_service/models/flutter_releases.model.dart index f5a1e317..df01018a 100644 --- a/lib/src/services/releases_service/models/flutter_releases.model.dart +++ b/lib/src/services/releases_service/models/flutter_releases.model.dart @@ -3,24 +3,10 @@ import 'dart:io'; import 'release.model.dart'; -const _flutterChannels = [ - 'stable', - 'beta', - 'dev', - 'master', -]; +const _flutterChannels = ['stable', 'beta', 'dev', 'master']; /// Flutter Releases class Releases { - /// Constructor - Releases({ - required this.baseUrl, - required this.channels, - required this.releases, - required this.hashReleaseMap, - required this.versionReleaseMap, - }); - /// Base url for Flutter /// Channels in Flutter releases final String baseUrl; @@ -36,6 +22,17 @@ class Releases { /// Hash release map final Map hashReleaseMap; + const + + /// Constructor + Releases({ + required this.baseUrl, + required this.channels, + required this.releases, + required this.hashReleaseMap, + required this.versionReleaseMap, + }); + /// Creates a FlutterRelease from a [json] string factory Releases.fromJson(String json) { return Releases.fromMap(jsonDecode(json) as Map); @@ -47,9 +44,7 @@ class Releases { } /// Returns a [FlutterVersion] release from channel [version] - Release getLatestChannelRelease( - String channelName, - ) { + Release getLatestChannelRelease(String channelName) { if (!_flutterChannels.contains(channelName)) { throw Exception('Can only infer release on valid channel'); } diff --git a/lib/src/services/releases_service/models/release.model.dart b/lib/src/services/releases_service/models/release.model.dart index 091f611f..9316f885 100644 --- a/lib/src/services/releases_service/models/release.model.dart +++ b/lib/src/services/releases_service/models/release.model.dart @@ -3,19 +3,6 @@ import 'channels.model.dart'; /// Release Model class Release { - /// Constructor - Release({ - required this.hash, - required this.channel, - required this.version, - required this.releaseDate, - required this.archive, - required this.sha256, - required this.dartSdkArch, - required this.dartSdkVersion, - this.activeChannel = false, - }); - /// Release hash final String hash; @@ -43,6 +30,21 @@ class Release { /// Dart SDK architecture final String? dartSdkArch; + const + + /// Constructor + Release({ + required this.hash, + required this.channel, + required this.version, + required this.releaseDate, + required this.archive, + required this.sha256, + required this.dartSdkArch, + required this.dartSdkVersion, + this.activeChannel = false, + }); + /// Creates a release from a map of values factory Release.fromMap(Map map) => Release( hash: map['hash'] as String, @@ -56,6 +58,14 @@ class Release { activeChannel: map['active_channel'] as bool? ?? false, ); + /// Returns channel name of the release + String get channelName => channel.name; + + /// Returns archive url of the release + String get archiveUrl { + return '$storageUrl/flutter_infra_release/releases/$archive'; + } + /// Turns Release model into a map of values Map toMap() => { 'hash': hash, @@ -68,25 +78,10 @@ class Release { 'dart_sdk_version': dartSdkVersion, 'active_channel': activeChannel, }; - - /// Returns channel name of the release - String get channelName => channel.name; - - /// Returns archive url of the release - String get archiveUrl { - return '$storageUrl/flutter_infra_release/releases/$archive'; - } } /// Release channels model class Channels { - /// Channel model contructor - Channels({ - required this.beta, - required this.dev, - required this.stable, - }); - /// Beta channel release final Release beta; @@ -96,6 +91,14 @@ class Channels { /// Stable channel release final Release stable; + const + + /// Channel model contructor + Channels({required this.beta, required this.dev, required this.stable}); + + /// Returns a list of all releases + List get toList => [dev, beta, stable]; + /// Returns channel by name Release operator [](String channelName) { if (channelName == 'beta') return beta; @@ -117,7 +120,4 @@ class Channels { dev.hash: 'dev', stable.hash: 'stable', }; - - /// Returns a list of all releases - List get toList => [dev, beta, stable]; } diff --git a/lib/src/services/releases_service/releases_client.dart b/lib/src/services/releases_service/releases_client.dart index 2d596983..b980b7ea 100644 --- a/lib/src/services/releases_service/releases_client.dart +++ b/lib/src/services/releases_service/releases_client.dart @@ -28,41 +28,36 @@ String getReleasesUrl(String platform) { } class FlutterReleases { - FlutterReleases._(); - static Releases? _cacheReleasesRes; + const FlutterReleases._(); + /// Gets Flutter SDK Releases /// Can use memory [cache] if it exists. - static Future get({ - bool cache = true, - String? platform, - }) async { + static Future get({bool cache = true, String? platform}) async { platform ??= Platform.operatingSystem; final releasesUrl = getReleasesUrl(platform); try { // If has been cached return if (_cacheReleasesRes != null && cache) { - return Future.value(_cacheReleasesRes); + return await Future.value(_cacheReleasesRes); } final response = await fetch(releasesUrl); _cacheReleasesRes = Releases.fromJson(response); - return Future.value(_cacheReleasesRes); + return await Future.value(_cacheReleasesRes); } on Exception catch (err) { logger.detail(err.toString()); return _getFromFlutterUrl(platform); } } - static Future _getFromFlutterUrl( - String platform, - ) async { + static Future _getFromFlutterUrl(String platform) async { try { final response = await fetch(getFlutterReleasesUrl(platform)); _cacheReleasesRes = Releases.fromJson(response); - return Future.value(_cacheReleasesRes); + return await Future.value(_cacheReleasesRes); } on Exception { throw AppException( 'Failed to retrieve the Flutter SDK from: ${getFlutterReleasesUrl(platform)}\n' diff --git a/lib/src/utils/change_case.dart b/lib/src/utils/change_case.dart index cc38717d..767ea8cc 100644 --- a/lib/src/utils/change_case.dart +++ b/lib/src/utils/change_case.dart @@ -15,8 +15,6 @@ class ChangeCase { const ChangeCase(this.text); - List get _words => _groupWords(text); - List _groupWords(String text) { final sb = StringBuffer(); final words = []; @@ -45,18 +43,6 @@ class ChangeCase { return words; } - /// camelCase - String get camelCase => _getCamelCase(); - - /// CONSTANT_CASE - String get constantCase => _uppercase(_snakeCaseSeparator); - - /// snake_case - String get snakeCase => _lowerCase(_snakeCaseSeparator); - - /// param-case - String get paramCase => _lowerCase(_paramCaseSeparator); - String _getCamelCase() { final words = _words.map(_upperCaseFirstLetter).toList(); if (_words.isNotEmpty) { @@ -74,6 +60,20 @@ class ChangeCase { if (word.isEmpty) return ''; return word.capitalize; } + + List get _words => _groupWords(text); + + /// camelCase + String get camelCase => _getCamelCase(); + + /// CONSTANT_CASE + String get constantCase => _uppercase(_snakeCaseSeparator); + + /// snake_case + String get snakeCase => _lowerCase(_snakeCaseSeparator); + + /// param-case + String get paramCase => _lowerCase(_paramCaseSeparator); } extension on String { diff --git a/lib/src/utils/commands.dart b/lib/src/utils/commands.dart index 156e622e..f1410515 100644 --- a/lib/src/utils/commands.dart +++ b/lib/src/utils/commands.dart @@ -15,7 +15,7 @@ Future runFlutter( CacheFlutterVersion? version, bool? echoOutput, bool? throwOnError, -}) async { +}) { if (version == null) { return _runCmd(_flutterCmd, args: args); } @@ -34,7 +34,7 @@ Future runDart( CacheFlutterVersion? version, bool? echoOutput, bool? throwOnError, -}) async { +}) { if (version == null) { return _runCmd(_dartCmd, args: args); } @@ -60,10 +60,13 @@ Future _runOnVersion( final execPath = isFlutter ? version.flutterExec : version.dartExec; // Update environment - final environment = updateEnvironmentVariables([ - version.binPath, - version.dartBinPath, - ], ctx.environment); + final environment = updateEnvironmentVariables( + [ + version.binPath, + version.dartBinPath, + ], + ctx.environment, + ); // Run command return await _runCmd( @@ -85,18 +88,17 @@ Future execCmd( // If execPath is not provided will get the path configured version var environment = ctx.environment; if (version != null) { - environment = updateEnvironmentVariables([ - version.binPath, - version.dartBinPath, - ], ctx.environment); + environment = updateEnvironmentVariables( + [ + version.binPath, + version.dartBinPath, + ], + ctx.environment, + ); } // Run command - return await _runCmd( - execPath, - args: args, - environment: environment, - ); + return await _runCmd(execPath, args: args, environment: environment); } Future _runCmd( diff --git a/lib/src/utils/console_utils.dart b/lib/src/utils/console_utils.dart index 12b01369..12473d21 100644 --- a/lib/src/utils/console_utils.dart +++ b/lib/src/utils/console_utils.dart @@ -12,16 +12,13 @@ Table createTable([List columns = const []]) { ..headerStyle = FontStyle.bold; for (final column in columns) { - table.insertColumn( - header: column, - alignment: TextAlignment.left, - ); + table.insertColumn(header: column, alignment: TextAlignment.left); } return table; } /// Allows to select from cached sdks. -Future cacheVersionSelector(List versions) async { +String cacheVersionSelector(List versions) { // Return message if no cached versions if (versions.isEmpty) { throw const AppException( @@ -34,10 +31,7 @@ Future cacheVersionSelector(List versions) async { final versionsList = versions.map((version) => version.name).toList(); - final choise = logger.select( - 'Select a version:', - options: versionsList, - ); + final choise = logger.select('Select a version:', options: versionsList); return choise; } diff --git a/lib/src/utils/context.dart b/lib/src/utils/context.dart index e0b7e4f3..e4e2426f 100644 --- a/lib/src/utils/context.dart +++ b/lib/src/utils/context.dart @@ -21,10 +21,29 @@ typedef Generator = dynamic Function(FVMContext context); FVMContext get ctx => use(contextKey, withDefault: () => FVMContext.main); -T getProvider() => ctx.get(); +T getProvider() => ctx.get(); class FVMContext { static FVMContext main = FVMContext.create(); + + /// Name of the context + final String id; + + /// Working Directory for FVM + final String workingDirectory; + + /// Flag to determine if context is running in a test + final bool isTest; + + /// App config + final AppConfig config; + + /// Generators for dependencies + final Map? generators; + + /// Generated values + final Map _dependencies = {}; + factory FVMContext.create({ String? id, AppConfig? configOverrides, @@ -75,24 +94,6 @@ class FVMContext { this.isTest = false, }); - /// Name of the context - final String id; - - /// Working Directory for FVM - final String workingDirectory; - - /// Flag to determine if context is running in a test - final bool isTest; - - /// App config - final AppConfig config; - - /// Generators for dependencies - final Map? generators; - - /// Generated values - final Map _dependencies = {}; - /// Environment variables Map get environment => Platform.environment; diff --git a/lib/src/utils/deprecation_util.dart b/lib/src/utils/deprecation_util.dart index d96d08dc..618ecb4e 100644 --- a/lib/src/utils/deprecation_util.dart +++ b/lib/src/utils/deprecation_util.dart @@ -95,7 +95,5 @@ void _warnDeprecatedEnvVars() { logger.info('Please use ${ConfigKeys.cachePath.envKey} instead'); } - if (flutterRoot == null || fvmHome == null) { - return; - } + if (flutterRoot == null || fvmHome == null) {} } diff --git a/lib/src/utils/extensions.dart b/lib/src/utils/extensions.dart index 30b76770..b8a4a737 100644 --- a/lib/src/utils/extensions.dart +++ b/lib/src/utils/extensions.dart @@ -67,10 +67,7 @@ extension LinkExtensions on Link { deleteSync(); } - createSync( - target.path, - recursive: true, - ); + createSync(target.path, recursive: true); } } diff --git a/lib/src/utils/helpers.dart b/lib/src/utils/helpers.dart index abfd2a06..83fea55e 100644 --- a/lib/src/utils/helpers.dart +++ b/lib/src/utils/helpers.dart @@ -84,7 +84,7 @@ class FlutterVersionOutput { final String? dartVersion; final String? dartBuildVersion; - FlutterVersionOutput({ + const FlutterVersionOutput({ this.flutterVersion, this.channel, this.dartVersion, @@ -117,9 +117,7 @@ FlutterVersionOutput extractFlutterVersionOutput(String content) { final filteredContent = _extractFlutterInfoBlock(content); final flutterRegex = RegExp(r'Flutter (\S+)'); final channelRegex = RegExp(r' channel (\w+)'); - final dartRegex = RegExp( - r'Dart (\S+)', - ); + final dartRegex = RegExp(r'Dart (\S+)'); final dartBuildRegex = RegExp(r'Dart (\S+) \(build (\S+)\)'); final flutterMatch = flutterRegex.firstMatch(filteredContent); @@ -169,11 +167,10 @@ String extractDartVersionOutput(String input) { final match = regExp.firstMatch(input); if (match != null) { return match.group(1)!.trim(); // Returns the version number - } else { - throw FormatException( - 'No Dart version found in the input string. \n\n $input', - ); } + throw FormatException( + 'No Dart version found in the input string. \n\n $input', + ); } bool isValidGitUrl(String url) { diff --git a/lib/src/utils/http.dart b/lib/src/utils/http.dart index c159c9f0..4bd691b4 100644 --- a/lib/src/utils/http.dart +++ b/lib/src/utils/http.dart @@ -2,10 +2,7 @@ import 'dart:convert'; import 'dart:io'; /// Does a simple get request on [url] -Future fetch( - String url, { - Map? headers, -}) async { +Future fetch(String url, {Map? headers}) async { final client = HttpClient(); // Add headers to request diff --git a/lib/src/utils/parsers/git_clone_update_printer.dart b/lib/src/utils/parsers/git_clone_update_printer.dart index c8bca3ed..1905fdfa 100644 --- a/lib/src/utils/parsers/git_clone_update_printer.dart +++ b/lib/src/utils/parsers/git_clone_update_printer.dart @@ -58,9 +58,7 @@ void printProgressBar(String label, int percentage) { } // Create a custom Process.start, that prints using the progress bar -Future runGitCloneUpdate( - List args, -) async { +Future runGitCloneUpdate(List args) async { final process = await Process.start('git', args); process.stderr.transform(utf8.decoder).listen((line) { diff --git a/lib/src/utils/run_command.dart b/lib/src/utils/run_command.dart index 09616e91..91531bb6 100644 --- a/lib/src/utils/run_command.dart +++ b/lib/src/utils/run_command.dart @@ -31,23 +31,22 @@ Future runCommand( _throwIfProcessFailed(processResult, command, args); } return processResult; - } else { - final process = await Process.start( - command, - args, - environment: environment, - runInShell: true, - workingDirectory: workingDirectory, - mode: ProcessStartMode.inheritStdio, - ); - - processResult = ProcessResult( - process.pid, - await process.exitCode, - null, - null, - ); } + final process = await Process.start( + command, + args, + environment: environment, + runInShell: true, + workingDirectory: workingDirectory, + mode: ProcessStartMode.inheritStdio, + ); + + processResult = ProcessResult( + process.pid, + await process.exitCode, + null, + null, + ); if (throwOnError) { _throwIfProcessFailed(processResult, command, args); } diff --git a/lib/src/utils/which.dart b/lib/src/utils/which.dart index b81fca21..d2f93bf0 100644 --- a/lib/src/utils/which.dart +++ b/lib/src/utils/which.dart @@ -2,10 +2,7 @@ import 'dart:io'; import 'package:path/path.dart'; -String? which( - String command, { - bool binDir = false, -}) { +String? which(String command, {bool binDir = false}) { String? pathEnv = Platform.environment['PATH']; String? pathExtEnv = Platform.isWindows ? Platform.environment['PATHEXT'] : null; diff --git a/lib/src/workflows/ensure_cache.workflow.dart b/lib/src/workflows/ensure_cache.workflow.dart index 01a1a53e..3ed04895 100644 --- a/lib/src/workflows/ensure_cache.workflow.dart +++ b/lib/src/workflows/ensure_cache.workflow.dart @@ -29,14 +29,14 @@ Future ensureCacheWorkflow( await CacheService.fromContext.verifyCacheIntegrity(cacheVersion); if (integrity == CacheIntegrity.invalid) { - return _handleNonExecutable( + return await _handleNonExecutable( cacheVersion, shouldInstall: shouldInstall, ); } if (integrity == CacheIntegrity.versionMismatch) { - return _handleVersionMismatch( + return await _handleVersionMismatch( cacheVersion, shouldInstall: shouldInstall, ); @@ -53,9 +53,7 @@ Future ensureCacheWorkflow( } if (validVersion.isCustom) { - throw AppException( - 'Custom Flutter SDKs must be installed manually.', - ); + throw AppException('Custom Flutter SDKs must be installed manually.'); } if (!shouldInstall) { @@ -114,18 +112,16 @@ Future _handleNonExecutable( ..spacer; final shouldReinstall = logger.confirm( - 'Would you like to reinstall this version to resolve the issue?', - defaultValue: true); + 'Would you like to reinstall this version to resolve the issue?', + defaultValue: true, + ); if (shouldReinstall) { CacheService.fromContext.remove(version); logger.info( 'The corrupted SDK version is now being removed and a reinstallation will follow...', ); - return ensureCacheWorkflow( - version.name, - shouldInstall: shouldInstall, - ); + return ensureCacheWorkflow(version.name, shouldInstall: shouldInstall); } throw AppException('Flutter SDK: ${version.name} is not executable.'); @@ -135,13 +131,14 @@ Future _handleNonExecutable( Future _handleVersionMismatch( CacheFlutterVersion version, { required bool shouldInstall, -}) async { +}) { logger ..notice( 'Version mismatch detected: cache version is ${version.flutterSdkVersion}, but expected ${version.name}.', ) ..info( - 'This can occur if you manually run "flutter upgrade" on a cached SDK.') + 'This can occur if you manually run "flutter upgrade" on a cached SDK.', + ) ..spacer; final firstOption = @@ -151,10 +148,7 @@ Future _handleVersionMismatch( final selectedOption = logger.select( 'How would you like to resolve this?', - options: [ - firstOption, - secondOption, - ], + options: [firstOption, secondOption], ); if (selectedOption == firstOption) { @@ -165,10 +159,7 @@ Future _handleVersionMismatch( logger.info('Removing incorrect SDK version...'); CacheService.fromContext.remove(version); - return ensureCacheWorkflow( - version.name, - shouldInstall: true, - ); + return ensureCacheWorkflow(version.name, shouldInstall: true); } Future validateFlutterVersion(String version) async { @@ -199,9 +190,7 @@ Future validateFlutterVersion(String version) async { } } - logger.notice( - 'Flutter SDK: ($version) is not valid Flutter version', - ); + logger.notice('Flutter SDK: ($version) is not valid Flutter version'); final askConfirmation = logger.confirm( 'Do you want to continue?', @@ -213,9 +202,7 @@ Future validateFlutterVersion(String version) async { return flutterVersion; } - throw AppException( - '$version is not a valid Flutter version', - ); + throw AppException('$version is not a valid Flutter version'); } void _validateContext() { diff --git a/lib/src/workflows/setup_flutter.workflow.dart b/lib/src/workflows/setup_flutter.workflow.dart index 3a83abed..e997180d 100644 --- a/lib/src/workflows/setup_flutter.workflow.dart +++ b/lib/src/workflows/setup_flutter.workflow.dart @@ -1,17 +1,12 @@ import 'package:fvm/src/models/cache_flutter_version_model.dart'; import 'package:fvm/src/services/logger_service.dart'; -Future setupFlutterWorkflow( - CacheFlutterVersion version, -) async { +Future setupFlutterWorkflow(CacheFlutterVersion version) async { logger ..info('Setting up Flutter SDK: ${version.name}') ..spacer; - await version.run( - '--version', - echoOutput: true, - ); + await version.run('--version', echoOutput: true); logger ..spacer diff --git a/lib/src/workflows/use_version.workflow.dart b/lib/src/workflows/use_version.workflow.dart index f247ebf6..a4beee47 100644 --- a/lib/src/workflows/use_version.workflow.dart +++ b/lib/src/workflows/use_version.workflow.dart @@ -33,12 +33,8 @@ Future useVersionWorkflow({ if (!project.isFlutter && !force) { logger ..spacer - ..info( - 'This does not seem to be a Flutter project directory', - ); - final proceed = logger.confirm( - 'Would you like to continue?', - ); + ..info('This does not seem to be a Flutter project directory'); + final proceed = logger.confirm('Would you like to continue?'); if (!proceed) exit(ExitCode.success.code); } @@ -59,26 +55,18 @@ Future useVersionWorkflow({ final updatedProject = ProjectService.fromContext.update( project, - flavors: { - if (flavor != null) flavor: version.name, - }, + flavors: {if (flavor != null) flavor: version.name}, flutterSdkVersion: version.name, ); await _checkGitignore(updatedProject); - await resolveDependenciesWorkflow( - updatedProject, - version, - ); + await resolveDependenciesWorkflow(updatedProject, version); - _updateLocalSdkReference( - updatedProject, - version, - ); + _updateLocalSdkReference(updatedProject, version); _updateCurrentSdkReference( updatedProject, - version + version, ); _manageVscodeSettings(updatedProject); @@ -90,9 +78,7 @@ Future useVersionWorkflow({ 'Project now uses Flutter SDK: $versionLabel on [$flavor] flavor.', ); } else { - logger.success( - 'Project now uses Flutter SDK : $versionLabel', - ); + logger.success('Project now uses Flutter SDK : $versionLabel'); } if (version.flutterExec == which('flutter')) { @@ -107,8 +93,6 @@ Future useVersionWorkflow({ ) ..info('You can then use "flutter" command within the VsCode terminal.'); } - - return; } /// Adds to .gitignore paths that should be ignored for fvm @@ -126,9 +110,7 @@ Future _checkGitignore(Project project) async { logger.detail('Update gitignore: $updateGitIgnore'); if (!await GitDir.isGitDir(project.path)) { - logger.detail( - 'Project is not a git repository.', - ); + logger.detail('Project is not a git repository.'); return; } @@ -150,9 +132,7 @@ Future _checkGitignore(Project project) async { List lines = ignoreFile.readAsLinesSync(); if (lines.any((line) => line.trim() == pathToAdd)) { - logger.detail( - '$pathToAdd already exists in .gitignore', - ); + logger.detail('$pathToAdd already exists in .gitignore'); return; } @@ -181,14 +161,8 @@ Future _checkGitignore(Project project) async { 'You should add the $kPackageName version directory "${cyan.wrap(pathToAdd)}" to .gitignore?', ); - if (logger.confirm( - 'Would you like to do that now?', - defaultValue: true, - )) { - ignoreFile.writeAsStringSync( - lines.join('\n'), - mode: FileMode.write, - ); + if (logger.confirm('Would you like to do that now?', defaultValue: true)) { + ignoreFile.writeAsStringSync(lines.join('\n'), mode: FileMode.write); logger ..success('Added $pathToAdd to .gitignore') ..spacer; @@ -215,9 +189,7 @@ void _checkProjectVersionConstraints( try { dartSdkVersion = Version.parse(sdkVersion); } on FormatException { - logger.warn( - 'Could not parse Flutter SDK version $sdkVersion', - ); + logger.warn('Could not parse Flutter SDK version $sdkVersion'); return; } @@ -233,14 +205,12 @@ void _checkProjectVersionConstraints( logger ..info( - '$message does not meet the project constraints of $constraints.') + '$message does not meet the project constraints of $constraints.', + ) ..info('This could cause unexpected behavior or issues.') ..spacer; - if (!logger.confirm( - 'Would you like to proceed?', - defaultValue: true, - )) { + if (!logger.confirm('Would you like to proceed?', defaultValue: true)) { throw AppException( 'The Flutter SDK version $sdkVersion is not compatible with the project constraints. You may need to adjust the version to avoid potential issues.', ); @@ -273,9 +243,7 @@ void _updateLocalSdkReference(Project project, CacheFlutterVersion version) { ..deleteIfExists() ..createSync(recursive: true); - project.localVersionSymlinkPath.link.createLink( - version.directory, - ); + project.localVersionSymlinkPath.link.createLink(version.directory); } /// Updates the `flutter_sdk` link to ensure it always points to the pinned SDK version. @@ -284,10 +252,7 @@ void _updateLocalSdkReference(Project project, CacheFlutterVersion version) { /// /// Throws an [AppException] if the project doesn't have a pinned Flutter SDK version. void _updateCurrentSdkReference(Project project, CacheFlutterVersion version) { - final currentSdkLink = join( - project.localFvmPath, - 'flutter_sdk', - ); + final currentSdkLink = join(project.localFvmPath, 'flutter_sdk'); if (currentSdkLink.link.existsSync()) { currentSdkLink.link.deleteSync(); @@ -295,9 +260,7 @@ void _updateCurrentSdkReference(Project project, CacheFlutterVersion version) { if (!ctx.priviledgedAccess) return; - currentSdkLink.link.createLink( - version.directory, - ); + currentSdkLink.link.createLink(version.directory); } /// Updates VS Code configuration for the project diff --git a/tool/grind.dart b/tool/grind.dart index 09498e22..1eb37c2d 100644 --- a/tool/grind.dart +++ b/tool/grind.dart @@ -82,16 +82,14 @@ Future getReleases() async { stringBuffer.writeln('Release: $tagName, Date: $date'); } - final file = File( - path.join(Directory.current.path, 'releases.txt'), - ); + final file = File(path.join(Directory.current.path, 'releases.txt')); file.writeAsStringSync(stringBuffer.toString()); } @Task('Prepare test environment') @Depends(buildVersion) -Future testSetup() async { +void testSetup() { final testDir = Directory(getTempTestDir()); if (testDir.existsSync()) { testDir.deleteSync(recursive: true); @@ -122,7 +120,7 @@ Future coverage() async { '--packages=.dart_tool/package_config.json', '--report-on=lib/', '--in=coverage', - '--out=coverage/lcov.info' + '--out=coverage/lcov.info', ], ); diff --git a/tool/homebrew.dart b/tool/homebrew.dart index b6fca31d..07dafd66 100644 --- a/tool/homebrew.dart +++ b/tool/homebrew.dart @@ -24,7 +24,8 @@ Future _homebrewFormula() async { } final url = Uri.parse( - 'https://api.github.com/repos/$owner/$repo/releases/tags/$versionArg'); + 'https://api.github.com/repos/$owner/$repo/releases/tags/$versionArg', + ); final headers = { if (githubToken.isNotEmpty) 'Authorization': 'token $githubToken', 'Accept': 'application/vnd.github.v3+json', @@ -64,10 +65,7 @@ Future _homebrewFormula() async { .replaceAll('{{MACOS_X64_URL}}', macosX64['url']) .replaceAll('{{MACOS_X64_SHA256}}', macosX64['sha256']) .replaceAll('{{MACOS_ARM64_URL}}', macosArm64['url']) - .replaceAll( - '{{MACOS_ARM64_SHA256}}', - macosArm64['sha256'], - ); + .replaceAll('{{MACOS_ARM64_SHA256}}', macosArm64['sha256']); final file = File('fvm.rb'); file.writeAsStringSync(formula); @@ -88,8 +86,7 @@ Future _downloadFile( final sha256Hash = sha256.convert(bytes).toString(); print('SHA-256 Hash: $sha256Hash'); return sha256Hash; - } else { - print('Failed to download $filename: ${response.statusCode}'); - return ''; } + print('Failed to download $filename: ${response.statusCode}'); + return ''; } From a30da5a33b248010f5f558ec5806d0adf2d32b29 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Thu, 4 Jan 2024 09:16:36 -0500 Subject: [PATCH 3/7] Added dcm action --- .github/actions/prepare/action.yml | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/.github/actions/prepare/action.yml b/.github/actions/prepare/action.yml index ef480876..07885410 100644 --- a/.github/actions/prepare/action.yml +++ b/.github/actions/prepare/action.yml @@ -21,9 +21,13 @@ runs: run: dart pub get shell: bash - - run: dart format --output=none --set-exit-if-changed . - shell: bash + - name: Install DCM + uses: CQLabs/setup-dcm@v1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} - - name: Analyze - run: dart analyze --fatal-infos --fatal-warnings . - shell: bash + - name: Run DCM + uses: CQLabs/dcm-action@v1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + folders: lib From 10273377bfc7bfc25285c9bef95c392db47051d7 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Thu, 4 Jan 2024 09:21:28 -0500 Subject: [PATCH 4/7] Update test action for dcm --- .github/actions/prepare/action.yml | 12 ------------ .github/workflows/test.yml | 13 +++++++++++++ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/.github/actions/prepare/action.yml b/.github/actions/prepare/action.yml index 07885410..dfa57acf 100644 --- a/.github/actions/prepare/action.yml +++ b/.github/actions/prepare/action.yml @@ -11,7 +11,6 @@ inputs: runs: using: "composite" steps: - - name: Setup Dart uses: dart-lang/setup-dart@v1 with: @@ -20,14 +19,3 @@ runs: - name: Get dependencies run: dart pub get shell: bash - - - name: Install DCM - uses: CQLabs/setup-dcm@v1 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - - - name: Run DCM - uses: CQLabs/dcm-action@v1 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - folders: lib diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7421210f..75966172 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -57,3 +57,16 @@ jobs: if: matrix.os == 'ubuntu-latest' env: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + + - name: Install DCM + uses: CQLabs/setup-dcm@v1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + + - name: Run DCM + uses: CQLabs/dcm-action@v1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + ci_key: ${{ secrets.DCM_CI_KEY }} + email: ${{ secrets.DCM_EMAIL }} + folders: lib From 8532f2167cefadd0b90c5235905badf84e5e87ed Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Thu, 4 Jan 2024 09:26:49 -0500 Subject: [PATCH 5/7] fix main.dart --- bin/main.dart | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/bin/main.dart b/bin/main.dart index 1801a427..9408b5ae 100755 --- a/bin/main.dart +++ b/bin/main.dart @@ -1,4 +1,6 @@ -#!/usr/bin/env dartimport 'dart:io'; +#!/usr/bin/env dart + +import 'dart:io'; import 'package:fvm/src/runner.dart'; import 'package:fvm/src/utils/context.dart'; From a69b83eedaf67375a43f26ada1337d3ebe72b5e3 Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Thu, 4 Jan 2024 09:33:53 -0500 Subject: [PATCH 6/7] Updated model --- lib/src/models/project_model.dart | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/src/models/project_model.dart b/lib/src/models/project_model.dart index 2449a5a4..3b5ad744 100644 --- a/lib/src/models/project_model.dart +++ b/lib/src/models/project_model.dart @@ -1,14 +1,14 @@ import 'dart:convert'; import 'dart:io'; -import 'package:fvm/constants.dart'; -import 'package:fvm/src/models/flutter_version_model.dart'; -import 'package:fvm/src/utils/extensions.dart'; import 'package:path/path.dart'; import 'package:pub_semver/pub_semver.dart'; import 'package:pubspec/pubspec.dart'; +import '../../constants.dart'; +import '../utils/extensions.dart'; import 'config_model.dart'; +import 'flutter_version_model.dart'; /// Represents a Flutter project. /// @@ -149,7 +149,7 @@ String _dartToolPath(String projectPath) { return join(projectPath, '.dart_tool'); } -String _dartToolGeneratorVersion(String projectPath) { +String? _dartToolGeneratorVersion(String projectPath) { final file = File(join(_dartToolPath(projectPath), 'package_config.json')); return file.existsSync() From cd1d1516a60abde5f29e808b8e6e71f5f5c133fa Mon Sep 17 00:00:00 2001 From: Leo Farias Date: Thu, 4 Jan 2024 09:40:12 -0500 Subject: [PATCH 7/7] update actions --- .github/workflows/test.yml | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 75966172..78dbe77e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -37,6 +37,18 @@ jobs: with: sdk-version: ${{ github.event.inputs.sdk-version }} + # - name: Install DCM + # uses: CQLabs/setup-dcm@v1 + # with: + # github_token: ${{ secrets.GITHUB_TOKEN }} + + # - name: Run DCM + # uses: CQLabs/dcm-action@v1 + # with: + # github_token: ${{ secrets.GITHUB_TOKEN }} + # folders: lib + + - name: Tests uses: ./.github/actions/test if: matrix.os != 'ubuntu-latest' @@ -56,17 +68,4 @@ jobs: uses: codecov/codecov-action@v3 if: matrix.os == 'ubuntu-latest' env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - - - name: Install DCM - uses: CQLabs/setup-dcm@v1 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - - - name: Run DCM - uses: CQLabs/dcm-action@v1 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - ci_key: ${{ secrets.DCM_CI_KEY }} - email: ${{ secrets.DCM_EMAIL }} - folders: lib + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} \ No newline at end of file