From 9d5bb6ed05381ab51011ef44d00af52679564634 Mon Sep 17 00:00:00 2001 From: Brett Sutton Date: Mon, 18 Jul 2022 08:52:41 +1000 Subject: [PATCH] applied lint_hard --- analysis_options.yaml | 6 +- bin/onepub.dart | 2 +- bin/opub.dart | 2 +- lib/src/commands/doctor.dart | 2 +- lib/src/commands/export.dart | 4 +- lib/src/commands/import.dart | 24 ++-- lib/src/commands/login.dart | 12 +- lib/src/commands/pub.dart | 9 +- lib/src/commands/pub/add_dep.dart | 6 +- lib/src/commands/pub/global.dart | 11 +- lib/src/commands/pub/global/activate.dart | 13 +- lib/src/commands/pub/global/deactivate.dart | 10 +- lib/src/commands/pub/private.dart | 2 +- lib/src/entry_point.dart | 13 +- lib/src/my_runner.dart | 115 ++++++++-------- lib/src/onepub_paths.dart | 4 +- lib/src/onepub_settings.dart | 6 +- lib/src/util/bread_butter_auth.dart | 139 ++++++++++---------- lib/src/util/one_pub_token_store.dart | 4 +- pubspec.yaml | 32 +++-- test/src/commands/doctor_test.dart | 6 +- test/src/commands/export_test.dart | 20 +-- test/src/commands/import_test.dart | 10 +- test/src/commands/login_test.dart | 2 +- test/src/commands/logout_test.dart | 2 +- test/src/commands/pub/add_dep_test.dart | 6 +- test/src/commands/pub/private_test.dart | 15 ++- test/src/commands/publish_test.dart | 2 +- test/src/commands/test_utils.dart | 16 +-- test/src/test_settings.dart | 2 +- tool/critical_test/pre_hook/auth.dart | 14 +- 31 files changed, 255 insertions(+), 256 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index e7ea39e..b6b80c8 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1 +1,5 @@ -# include: package:lint_hard/all.yaml +include: package:lint_hard/all.yaml + +analyzer: + exclude: + - lib/src/pub diff --git a/bin/onepub.dart b/bin/onepub.dart index 2a62727..40ca2c6 100755 --- a/bin/onepub.dart +++ b/bin/onepub.dart @@ -14,5 +14,5 @@ void main(List arguments) async { print(''); - await entrypoint(arguments, CommandSet.ONEPUB, 'onepub'); + await entrypoint(arguments, CommandSet.onepub, 'onepub'); } diff --git a/bin/opub.dart b/bin/opub.dart index a874fb8..fd33533 100755 --- a/bin/opub.dart +++ b/bin/opub.dart @@ -8,5 +8,5 @@ import 'package:onepub/src/entry_point.dart'; import 'package:onepub/src/my_runner.dart'; void main(List arguments) async { - await entrypoint(arguments, CommandSet.OPUB, 'onepub'); + await entrypoint(arguments, CommandSet.opub, 'onepub'); } diff --git a/lib/src/commands/doctor.dart b/lib/src/commands/doctor.dart index ac03cb7..b8e8ba6 100644 --- a/lib/src/commands/doctor.dart +++ b/lib/src/commands/doctor.dart @@ -94,7 +94,7 @@ run: onepub login''')); void tokenStatus() { print(blue('\nRepository tokens')); - var store = OnePubTokenStore(); + final store = OnePubTokenStore(); if (!store.isLoggedIn) { print(red('No tokens found.')); return; diff --git a/lib/src/commands/export.dart b/lib/src/commands/export.dart index 45f4c76..925a945 100644 --- a/lib/src/commands/export.dart +++ b/lib/src/commands/export.dart @@ -18,7 +18,7 @@ class ExportCommand extends Command { /// ExportCommand() { argParser - ..addFlag('file', abbr: 'f', defaultsTo: false, help: ''' + ..addFlag('file', abbr: 'f', help: ''' Save the OnePub token to a file. Pass in a filename or leave blank to use the default filename.''') ..addOption('user', @@ -84,7 +84,7 @@ Pass in a filename or leave blank to use the default filename.''') var pathToFile = TokenExportFile.exportFilename; if (argResults!.rest.length == 1) { pathToFile = argResults!.rest[0]; - } else if (argResults!.rest.length != 0) { + } else if (argResults!.rest.isNotEmpty) { throw ExitException( exitCode: 1, message: 'You may only pass one argument to --file.'); } diff --git a/lib/src/commands/import.dart b/lib/src/commands/import.dart index e3d921f..fea3965 100644 --- a/lib/src/commands/import.dart +++ b/lib/src/commands/import.dart @@ -56,8 +56,8 @@ Use `onepub export` to obtain the OnePub token. if (OnePubTokenStore().isLoggedIn) { throw ExitException( exitCode: -1, - message: - 'You may not import a token when you are logged in to the OnePub CLI.'); + message: 'You may not import a token when you are logged in ' + 'to the OnePub CLI.'); } final file = argResults!['file'] as bool; final ask = argResults!['ask'] as bool; @@ -82,8 +82,7 @@ Use `onepub export` to obtain the OnePub token. // because the [sendCommand] expects the token to be // in the token store which it isn't // So we paass the auth header directly. - final headers = {}; - headers.addAll({'authorization': onepubToken}); + final headers = {}..addAll({'authorization': onepubToken}); final response = await sendCommand( command: '/organisation/token', authorised: false, headers: headers); @@ -101,7 +100,7 @@ Use `onepub export` to obtain the OnePub token. obfuscatedOrganisationId: organisationObfuscatedId, operatorEmail: 'not set during import'); - print('${blue('Successfully logged into $organisationName.')}'); + print(blue('Successfully logged into $organisationName.')); } /// pull the secret from onepub.export.yaml @@ -141,13 +140,10 @@ Found: ${argResults!.rest.join(',')}'''); return env[OnePubTokenStore.onepubSecretEnvKey]!; } - String fromUser() { - return ask('ONEPUB_SECRET:', - required: true, - validator: Ask.all([ - Ask.regExp(r'[a-zA-Z0-9-]*', - error: 'The secret contains invalid characters.'), - Ask.lengthRange(36, 36), - ])); - } + String fromUser() => ask('ONEPUB_SECRET:', + validator: Ask.all([ + Ask.regExp('[a-zA-Z0-9-]*', + error: 'The secret contains invalid characters.'), + Ask.lengthRange(36, 36), + ])); } diff --git a/lib/src/commands/login.dart b/lib/src/commands/login.dart index cf38f48..b917a9b 100644 --- a/lib/src/commands/login.dart +++ b/lib/src/commands/login.dart @@ -55,7 +55,8 @@ ${green('onepub import --ask')} } try { - final tempAuthTokenResponse = await breadButterAuth(); + final bb = BreadButter(); + final tempAuthTokenResponse = await bb.auth(); if (tempAuthTokenResponse == null) { throw ExitException( exitCode: 1, message: 'Invalid response. onePubToken not returned'); @@ -108,11 +109,10 @@ ${green('onepub import --ask')} print(red(error)); } - bool inSSH() { - return Env().exists('SSH_CLIENT') || - Env().exists('SSH_CONNECTION') || - Env().exists('SSH_TTY'); - } + bool inSSH() => + Env().exists('SSH_CLIENT') || + Env().exists('SSH_CONNECTION') || + Env().exists('SSH_TTY'); } void showWelcome( diff --git a/lib/src/commands/pub.dart b/lib/src/commands/pub.dart index a1a9278..69663db 100644 --- a/lib/src/commands/pub.dart +++ b/lib/src/commands/pub.dart @@ -13,15 +13,14 @@ import 'pub/private.dart'; /// Provides the abilty to work with global packages that are hosted /// as private packages on OnePub class PubCommand extends Command { - @override - String get name => 'pub'; - @override - String get description => blue('Work with packages.'); - /// PubCommand() : super() { addSubcommand(GlobalCommand()); addSubcommand(AddPrivateCommand()); addSubcommand(PrivateCommand()); } + @override + String get name => 'pub'; + @override + String get description => blue('Work with packages.'); } diff --git a/lib/src/commands/pub/add_dep.dart b/lib/src/commands/pub/add_dep.dart index 0946d0b..01a5da5 100644 --- a/lib/src/commands/pub/add_dep.dart +++ b/lib/src/commands/pub/add_dep.dart @@ -5,10 +5,10 @@ // BSD-style license that can be found in the LICENSE file. import 'package:dcli/dcli.dart'; -import 'package:onepub/src/pub/command/add.dart'; import '../../exceptions.dart'; import '../../onepub_settings.dart'; +import '../../pub/command/add.dart'; import '../../util/one_pub_token_store.dart'; /// Handles the `add` pub command. Adds a dependency to `pubspec.yaml` and gets @@ -20,6 +20,7 @@ import '../../util/one_pub_token_store.dart'; /// /// Currently supports only adding one dependency at a time. class AddPrivateCommand extends AddCommand { + AddPrivateCommand() : super(includeSourceOptions: false); @override String get name => 'add'; @override @@ -40,10 +41,9 @@ class AddPrivateCommand extends AddCommand { @override bool get isOffline => false; + @override bool get hasHostOptions => hostUrl != null; - AddPrivateCommand() : super(includeSourceOptions: false); - @override Future runProtected() async { OnePubSettings.load(); diff --git a/lib/src/commands/pub/global.dart b/lib/src/commands/pub/global.dart index f0d88c5..f364d78 100644 --- a/lib/src/commands/pub/global.dart +++ b/lib/src/commands/pub/global.dart @@ -6,20 +6,19 @@ import 'package:args/command_runner.dart'; import 'package:dcli/dcli.dart'; -import 'global/deactivate.dart'; import 'global/activate.dart'; +import 'global/deactivate.dart'; /// Provides the abilty to work with global packages that are hosted /// as private packages on OnePub class GlobalCommand extends Command { - @override - String get name => 'global'; - @override - String get description => blue('Work with private global packages.'); - /// GlobalCommand() : super() { addSubcommand(ActivateCommand()); addSubcommand(DeactivateCommand()); } + @override + String get name => 'global'; + @override + String get description => blue('Work with private global packages.'); } diff --git a/lib/src/commands/pub/global/activate.dart b/lib/src/commands/pub/global/activate.dart index be6b28e..2b02f44 100644 --- a/lib/src/commands/pub/global/activate.dart +++ b/lib/src/commands/pub/global/activate.dart @@ -17,7 +17,7 @@ import '../../../util/one_pub_token_store.dart'; /// and then addes it class ActivateCommand extends PubCommand { /// - ActivateCommand() : super() {} + ActivateCommand() : super(); @override String get description => @@ -27,8 +27,11 @@ class ActivateCommand extends PubCommand { String get name => 'activate'; GlobalPackages? _globals; - late final SystemCache cache = SystemCache(isOffline: false); + @override + // ignore: overridden_fields + late final SystemCache cache = SystemCache(); + @override GlobalPackages get globals => _globals ??= GlobalPackages(cache); late Iterable args = argResults.rest; @@ -46,7 +49,7 @@ run: onepub login final hostedUrl = OnePubSettings().onepubHostedUrl().toString(); - var package = readArg('No package to activate given.'); + final package = readArg('No package to activate given.'); // Parse the version constraint, if there is one. var constraint = VersionConstraint.any; @@ -58,7 +61,7 @@ run: onepub login } } - return await globals.activateHosted( + return globals.activateHosted( package, constraint, null, // all executables @@ -71,7 +74,7 @@ run: onepub login String readArg([String error = '']) { if (args.isEmpty) usageException(error); - var arg = args.first; + final arg = args.first; args = args.skip(1); return arg; } diff --git a/lib/src/commands/pub/global/deactivate.dart b/lib/src/commands/pub/global/deactivate.dart index 8fe6dcb..5e820e0 100644 --- a/lib/src/commands/pub/global/deactivate.dart +++ b/lib/src/commands/pub/global/deactivate.dart @@ -21,17 +21,21 @@ class DeactivateCommand extends PubCommand { String get name => 'deactivate'; GlobalPackages? _globals; - late final SystemCache cache = SystemCache(isOffline: false); + @override + // ignore: overridden_fields + late final SystemCache cache = SystemCache(); + @override GlobalPackages get globals => _globals ??= GlobalPackages(cache); late Iterable args = argResults.rest; /// + @override Future runProtected() async { OnePubSettings.load(); - var package = readArg('No package to deactivate given.'); + final package = readArg('No package to deactivate given.'); if (!globals.deactivate( package, @@ -40,7 +44,7 @@ class DeactivateCommand extends PubCommand { String readArg([String error = '']) { if (args.isEmpty) usageException(error); - var arg = args.first; + final arg = args.first; args = args.skip(1); return arg; } diff --git a/lib/src/commands/pub/private.dart b/lib/src/commands/pub/private.dart index 28666e9..79bfaed 100644 --- a/lib/src/commands/pub/private.dart +++ b/lib/src/commands/pub/private.dart @@ -21,7 +21,7 @@ import '../../util/send_command.dart'; /// class PrivateCommand extends Command { /// - PrivateCommand() {} + PrivateCommand(); @override bool get takesArguments => false; diff --git a/lib/src/entry_point.dart b/lib/src/entry_point.dart index 2cc95cf..1a90528 100644 --- a/lib/src/entry_point.dart +++ b/lib/src/entry_point.dart @@ -18,7 +18,7 @@ import 'util/log.dart' as ulog; /// Used by unit tests to alter the working directory a command runs in /// as onepub normally assumes it is operating in the pwd. ScopeKey unitTestWorkingDirectoryKey = - ScopeKey.withDefault(pwd, "WorkingDirectory"); + ScopeKey.withDefault(pwd, 'WorkingDirectory'); Future entrypoint( List args, @@ -26,16 +26,16 @@ Future entrypoint( String program, ) async { try { - MyRunner runner = MyRunner(args, program, _description, commandSet); + final runner = MyRunner(args, program, _description, commandSet); try { runner.init(); await runner.run(args); } on FormatException catch (e) { - ulog.logerr((e.message)); + ulog.logerr(e.message); // this is an Exception (generally from the server, not a usage problem) //showUsage(); } on UsageException catch (e) { - ulog.logerr((e.message)); + ulog.logerr(e.message); showUsage(runner); // ignore: avoid_catches_without_on_clauses } @@ -44,7 +44,7 @@ Future entrypoint( exit(e.exitCode); // ignore: avoid_catches_without_on_clauses } catch (e) { - ulog.logerr((e.toString())); + ulog.logerr(e.toString()); } } @@ -53,5 +53,4 @@ void showUsage(MyRunner runner) { exit(1); } -String get _description => ''' -${orange('OnePub CLI tools')}'''; +String get _description => orange('OnePub CLI tools'); diff --git a/lib/src/my_runner.dart b/lib/src/my_runner.dart index 34b5782..6618057 100644 --- a/lib/src/my_runner.dart +++ b/lib/src/my_runner.dart @@ -8,26 +8,20 @@ import 'dart:io'; import 'package:args/command_runner.dart'; import 'package:dcli/dcli.dart'; import 'package:scope/scope.dart'; -import 'package:onepub/src/pub/command.dart'; -import 'package:onepub/src/pub/log.dart' hide red; -import 'package:onepub/src/util/config.dart'; import 'commands/doctor.dart'; import 'commands/export.dart'; - import 'commands/import.dart'; import 'commands/login.dart'; import 'commands/logout.dart'; - import 'commands/pub.dart' as onepub; import 'entry_point.dart'; import 'exceptions.dart'; import 'onepub_paths.dart'; import 'onepub_settings.dart'; +import 'pub/command.dart'; import 'pub/command/add.dart'; - import 'pub/command/cache.dart'; - import 'pub/command/deps.dart'; import 'pub/command/downgrade.dart'; import 'pub/command/get.dart'; @@ -43,11 +37,12 @@ import 'pub/command/upgrade.dart'; import 'pub/command/uploader.dart'; import 'pub/command/version.dart'; import 'pub/io.dart'; +import 'pub/log.dart' hide red; import 'pub/log.dart' as plog; - +import 'util/config.dart'; import 'version/version.g.dart'; -enum CommandSet { OPUB, ONEPUB } +enum CommandSet { opub, onepub } /// /// @@ -57,10 +52,10 @@ class MyRunner extends CommandRunner implements PubTopLevel { : super(executableName, description) { try { switch (commandSet) { - case CommandSet.ONEPUB: + case CommandSet.onepub: onepubCommands(commandSet); break; - case CommandSet.OPUB: + case CommandSet.opub: opubCommands(); } } on FormatException catch (e) { @@ -80,43 +75,43 @@ class MyRunner extends CommandRunner implements PubTopLevel { exit(0); } - if (commandSet == CommandSet.ONEPUB) { + if (commandSet == CommandSet.onepub) { install(dev: results['dev'] as bool); } } void opubCommands() { - argParser.addFlag('version', negatable: false, help: 'Print pub version.'); - argParser.addFlag('debug', - negatable: false, abbr: 'd', help: 'Enable verbose logging'); - argParser.addFlag('trace', - negatable: false, - help: 'Print debugging information when an error occurs.'); argParser - .addOption('verbosity', help: 'Control output verbosity.', allowed: [ - 'error', - 'warning', - 'normal', - 'io', - 'solver', - 'all' - ], allowedHelp: { - 'error': 'Show only errors.', - 'warning': 'Show only errors and warnings.', - 'normal': 'Show errors, warnings, and user messages.', - 'io': 'Also show IO operations.', - 'solver': 'Show steps during version resolution.', - 'all': 'Show all output including internal tracing messages.' - }); - argParser.addFlag('verbose', - abbr: 'v', negatable: false, help: 'Shortcut for "--verbosity=all".'); - argParser.addOption( - 'directory', - abbr: 'C', - help: 'Run the subcommand in the directory.', - defaultsTo: '.', - valueHelp: 'dir', - ); + ..addFlag('version', negatable: false, help: 'Print pub version.') + ..addFlag('debug', + negatable: false, abbr: 'd', help: 'Enable verbose logging') + ..addFlag('trace', + negatable: false, + help: 'Print debugging information when an error occurs.') + ..addOption('verbosity', help: 'Control output verbosity.', allowed: [ + 'error', + 'warning', + 'normal', + 'io', + 'solver', + 'all' + ], allowedHelp: { + 'error': 'Show only errors.', + 'warning': 'Show only errors and warnings.', + 'normal': 'Show errors, warnings, and user messages.', + 'io': 'Also show IO operations.', + 'solver': 'Show steps during version resolution.', + 'all': 'Show all output including internal tracing messages.' + }) + ..addFlag('verbose', + abbr: 'v', negatable: false, help: 'Shortcut for "--verbosity=all".') + ..addOption( + 'directory', + abbr: 'C', + help: 'Run the subcommand in the directory.', + defaultsTo: '.', + valueHelp: 'dir', + ); addCommand(LishCommand()); addCommand(GetCommand()); addCommand(AddCommand()); @@ -139,16 +134,16 @@ class MyRunner extends CommandRunner implements PubTopLevel { } void onepubCommands(CommandSet commandSet) { - argParser.addFlag('debug', - negatable: false, abbr: 'd', help: 'Enable verbose logging'); - argParser.addFlag('version', - negatable: false, help: 'Displays the onepub version no. and exits.'); - - argParser.addFlag('dev', - hide: true, - negatable: false, - help: 'Allows for configuration of localhost for ' - 'use in a development environment.'); + argParser + ..addFlag('debug', + negatable: false, abbr: 'd', help: 'Enable verbose logging') + ..addFlag('version', + negatable: false, help: 'Displays the onepub version no. and exits.') + ..addFlag('dev', + hide: true, + negatable: false, + help: 'Allows for configuration of localhost for ' + 'use in a development environment.'); addCommand(DoctorCommand()); addCommand(OnePubLoginCommand()); @@ -179,10 +174,10 @@ class MyRunner extends CommandRunner implements PubTopLevel { if (exists(ConfigCommand.testingFlagPath)) { if (OnePubSettings().onepubUrl == OnePubSettings.defaultOnePubUrl) { - print(('This system is configured for testing, but is also configured' + print('This system is configured for testing, but is also configured' ' for the production URL. If you need to change this, then delete ' '${ConfigCommand.testingFlagPath} or use the --dev option to ' - 'change the URL')); + 'change the URL'); exit(1); } } @@ -198,7 +193,7 @@ class MyRunner extends CommandRunner implements PubTopLevel { String get directory { if (argResults.options.contains('directory') && argResults.wasParsed('directory')) { - return argResults['directory']; + return argResults['directory'] as String; } /// if we are in a unit test and directory hasn't been passed @@ -210,15 +205,13 @@ class MyRunner extends CommandRunner implements PubTopLevel { } @override - bool get captureStackChains { - return trace || verbose || verbosityString == 'all'; - } + bool get captureStackChains => trace || verbose || verbosityString == 'all'; String get verbosityString { if (!argResults.options.contains('verbosity')) { return ''; } - return argResults['verbosity']; + return argResults['verbosity'] as String; } @override @@ -249,13 +242,13 @@ class MyRunner extends CommandRunner implements PubTopLevel { if (!argResults.options.contains('trace')) { return false; } - return argResults['trace']; + return argResults['trace'] as bool; } bool get verbose { if (!argResults.options.contains('verbose')) { return false; } - return argResults['verbose']; + return argResults['verbose'] as bool; } } diff --git a/lib/src/onepub_paths.dart b/lib/src/onepub_paths.dart index 981e0fe..fe681c9 100644 --- a/lib/src/onepub_paths.dart +++ b/lib/src/onepub_paths.dart @@ -12,7 +12,7 @@ class OnePubPaths { OnePubPaths._internal(this._settingsRoot); - static OnePubPaths _self = OnePubPaths._internal(HOME); + static final OnePubPaths _self = OnePubPaths._internal(HOME); /// Path to the .batman settings directory String get pathToSettingsDir { @@ -26,7 +26,7 @@ class OnePubPaths { } String get pathToTestSettings { - var pathToTest = DartProject.self.pathToTestDir; + final pathToTest = DartProject.self.pathToTestDir; return join(pathToTest, 'test_settings.yaml'); } diff --git a/lib/src/onepub_settings.dart b/lib/src/onepub_settings.dart index c40c85e..c1459c4 100644 --- a/lib/src/onepub_settings.dart +++ b/lib/src/onepub_settings.dart @@ -7,12 +7,12 @@ import 'dart:math'; import 'package:dcli/dcli.dart'; import 'package:meta/meta.dart'; -import 'package:onepub/src/pub/source/hosted.dart'; import 'package:settings_yaml/settings_yaml.dart'; -import 'package:yaml/yaml.dart'; import 'package:url_builder/url_builder.dart'; +import 'package:yaml/yaml.dart'; import 'onepub_paths.dart'; +import 'pub/source/hosted.dart'; import 'util/log.dart'; void loadSettings() { @@ -60,7 +60,7 @@ class OnePubSettings { late final SettingsYaml settings; /// Path to the onepub onepub.yaml file. - static late final String pathToSettings = + static final String pathToSettings = join(OnePubPaths().pathToSettingsDir, 'onepub.yaml'); static const String defaultOnePubUrl = 'https://onepub.dev'; diff --git a/lib/src/util/bread_butter_auth.dart b/lib/src/util/bread_butter_auth.dart index 85c777e..7224627 100644 --- a/lib/src/util/bread_butter_auth.dart +++ b/lib/src/util/bread_butter_auth.dart @@ -16,16 +16,19 @@ import 'package:shelf/shelf_io.dart' as shelf_io; import '../onepub_settings.dart'; import 'send_command.dart'; -int _port = 42666; +class BreadButter { + final int _port = 42666; + late final HttpServer server; + late final Completer completer; -/// Return the auth token or null if the auth failed. -Future breadButterAuth() async { - final onepubUrl = OnePubSettings.load().onepubWebUrl; - final authUrl = OnePubSettings().resolveWebEndPoint('clilogin'); + /// Return the auth token or null if the auth failed. + Future auth() async { + final onepubUrl = OnePubSettings.load().onepubWebUrl; + final authUrl = OnePubSettings().resolveWebEndPoint('clilogin'); - final encodedUrl = Uri.encodeFull(authUrl); + final encodedUrl = Uri.encodeFull(authUrl); - print(''' + print(''' To login to OnePub. From a web browser, go to @@ -33,18 +36,37 @@ ${blue(encodedUrl)} Waiting for your authorisation...'''); - return _waitForResponse(onepubUrl); -} + return _waitForResponse(onepubUrl); + } + + /// Returns a map with the response + Future _waitForResponse( + String onepubWebUrl, + + // oauth2.AuthorizationCodeGrant grant + ) async { + completer = Completer(); + server = await bindServer(_port); + + final onepuburl = OnePubSettings().onepubUrl; + final headers = {'Access-Control-Allow-Origin': onepuburl!}; + shelf.Response _cors(shelf.Response response) => + response.change(headers: headers); + + final _fixCORS = shelf.createMiddleware(responseHandler: _cors); + +// Pipeline handlers + final handler = const shelf.Pipeline() + .addMiddleware(_fixCORS) + //.addMiddleware(shelf.logRequests()) + .addHandler(_oauthHandler); + + shelf_io.serveRequests(server, handler); -/// Returns a map with the response -Future _waitForResponse( - String onepubWebUrl, + return completer.future; + } - // oauth2.AuthorizationCodeGrant grant -) async { - final completer = Completer(); - final server = await bindServer(_port); - var handlerCascade = (request) async { + FutureOr _oauthHandler(shelf.Request request) async { await server.close(); try { @@ -82,61 +104,44 @@ Future _waitForResponse( return shelf.Response.internalServerError(body: e.toString()); } - }; - - final onepuburl = OnePubSettings().onepubUrl; - var headers = {"Access-Control-Allow-Origin": onepuburl!}; - shelf.Response _cors(shelf.Response response) => - response.change(headers: headers); - - shelf.Middleware _fixCORS = shelf.createMiddleware(responseHandler: _cors); - -// Pipeline handlers - final handler = const shelf.Pipeline() - .addMiddleware(_fixCORS) - //.addMiddleware(shelf.logRequests()) - .addHandler(handlerCascade); - - shelf_io.serveRequests(server, handler); - - return completer.future; -} + } -/// Bind local server to handle oauth redirect -Future bindServer(int port) async { - final server = await HttpMultiServer.loopback(port); - server.autoCompress = true; - return server; -} + /// Bind local server to handle oauth redirect + Future bindServer(int port) async { + final server = await HttpMultiServer.loopback(port); + server.autoCompress = true; + return server; + } -Map queryToMap(String queryList) { - final map = {}; - for (final pair in queryList.split('&')) { - final split = _split(pair, '='); - if (split.isEmpty) { - continue; + Map queryToMap(String queryList) { + final map = {}; + for (final pair in queryList.split('&')) { + final split = _split(pair, '='); + if (split.isEmpty) { + continue; + } + final key = _urlDecode(split[0]); + final value = split.length > 1 ? _urlDecode(split[1]) : ''; + map[key] = value; } - final key = _urlDecode(split[0]); - final value = split.length > 1 ? _urlDecode(split[1]) : ''; - map[key] = value; + return map; } - return map; -} -List _split(String toSplit, String pattern) { - if (toSplit.isEmpty) { - return []; - } + List _split(String toSplit, String pattern) { + if (toSplit.isEmpty) { + return []; + } - final index = toSplit.indexOf(pattern); - if (index == -1) { - return [toSplit]; + final index = toSplit.indexOf(pattern); + if (index == -1) { + return [toSplit]; + } + return [ + toSplit.substring(0, index), + toSplit.substring(index + pattern.length) + ]; } - return [ - toSplit.substring(0, index), - toSplit.substring(index + pattern.length) - ]; -} -String _urlDecode(String encoded) => - Uri.decodeComponent(encoded.replaceAll('+', ' ')); + String _urlDecode(String encoded) => + Uri.decodeComponent(encoded.replaceAll('+', ' ')); +} diff --git a/lib/src/util/one_pub_token_store.dart b/lib/src/util/one_pub_token_store.dart index a4affd6..956ddba 100644 --- a/lib/src/util/one_pub_token_store.dart +++ b/lib/src/util/one_pub_token_store.dart @@ -50,9 +50,7 @@ class OnePubTokenStore { return credentials.token!; } - Iterable get credentials { - return tokenStore.credentials; - } + Iterable get credentials => tokenStore.credentials; /// Removes the onepub token from the pub token store. void clearOldTokens() { diff --git a/pubspec.yaml b/pubspec.yaml index 33ae159..8dc4f52 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -7,42 +7,40 @@ repository: https://github.com/onepub-dev/onepub environment: sdk: '>=2.12.1 <3.0.0' dependencies: + analyzer: 2.3.0 args: 2.3.0 + async: 2.8.2 basic_utils: 3.8.0 + cli_util: ^0.3.5 + collection: 1.15.0 + crypto: 3.0.1 dcli: 1.20.1 equatable: 2.0.3 + frontend_server_client: 2.1.2 glob: 2.0.1 + http: 0.13.3 http_multi_server: 3.0.1 + http_parser: 4.0.0 json_annotation: 4.1.0 meta: 1.7.0 oauth2: 2.0.0 path: 1.8.1 + pool: 1.5.0 pub_semver: 2.1.0 pubspec2: ^2.4.0 + scope: ^2.2.1 settings_yaml: 3.4.1 shelf: 1.2.0 + source_span: 1.8.1 stack_trace: 1.10.0 + typed_data: 1.3.0 + url_builder: 1.0.0 usage: 4.0.2 validators2: 3.0.0 - yaml: 3.1.0 - analyzer: 2.3.0 - collection: 1.15.0 - source_span: 1.8.1 - http: 0.13.3 - pool: 1.5.0 - frontend_server_client: 2.1.2 - http_parser: 4.0.0 - crypto: 3.0.1 - async: 2.8.2 - typed_data: 1.3.0 - pedantic: 1.11.1 - yaml_edit: 2.0.2 watcher: 1.0.0 win32: 2.0.5 - pubspec: ^2.1.0 - cli_util: ^0.3.5 - url_builder: 1.0.0 - scope: ^2.2.1 + yaml: 3.1.0 + yaml_edit: 2.0.2 dev_dependencies: diff --git a/test/src/commands/doctor_test.dart b/test/src/commands/doctor_test.dart index e05775b..5a1405c 100644 --- a/test/src/commands/doctor_test.dart +++ b/test/src/commands/doctor_test.dart @@ -10,12 +10,12 @@ import 'test_utils.dart'; void main() { test('onepub doctor ...', () async { - var clean = runCmd('doctor'); + final clean = runCmd('doctor'); - var first = clean.first; + final first = clean.first; expect(first, 'OnePub version: $packageVersion '); - var last = clean[(clean.length - 2)]; + final last = clean[(clean.length - 2)]; expect(last, 'OnePub: status healthy.'); // check that we have each of the major headings diff --git a/test/src/commands/export_test.dart b/test/src/commands/export_test.dart index dbde8bf..68b0e3e 100644 --- a/test/src/commands/export_test.dart +++ b/test/src/commands/export_test.dart @@ -13,12 +13,12 @@ import 'test_utils.dart'; void main() { test('onepub export env...', () async { - var clean = runCmd('export'); + final clean = runCmd('export'); - var settings = OnePubSettings.load(); + final settings = OnePubSettings.load(); final organisationName = settings.organisationName; - var first = clean.first; + final first = clean.first; expect(first, 'OnePub version: $packageVersion '); expect(clean.contains('Exporting OnePub token for $organisationName.'), @@ -29,11 +29,11 @@ void main() { 'Add the following environment variable to your CI/CD secrets.'), isTrue); - var last = clean[(clean.length - 2)]; + final last = clean[(clean.length - 2)]; expect(last.startsWith('ONEPUB_SECRET='), isTrue); // check the secret has a guid - var parts = last.split('='); + final parts = last.split('='); expect(parts.length, equals(2)); expect(parts[1].length, equals(36)); }); @@ -43,12 +43,12 @@ void main() { SettingsYaml.load(pathToSettings: join('test', 'test_settings.yaml')); final cicdUser = settings.asString('cicd_member'); - var clean = runCmd('export --user $cicdUser'); + final clean = runCmd('export --user $cicdUser'); - var onepubSettings = OnePubSettings.load(); + final onepubSettings = OnePubSettings.load(); final organisationName = onepubSettings.organisationName; - var first = clean.first; + final first = clean.first; expect(first, 'OnePub version: $packageVersion '); expect(clean.contains('Exporting OnePub token for $organisationName.'), @@ -59,11 +59,11 @@ void main() { 'Add the following environment variable to your CI/CD secrets.'), isTrue); - var last = clean[(clean.length - 2)]; + final last = clean[(clean.length - 2)]; expect(last.startsWith('ONEPUB_SECRET='), isTrue); // check the secret has a guid - var parts = last.split('='); + final parts = last.split('='); expect(parts.length, equals(2)); expect(parts[1].length, equals(36)); }); diff --git a/test/src/commands/import_test.dart b/test/src/commands/import_test.dart index ee2e082..789ffcc 100644 --- a/test/src/commands/import_test.dart +++ b/test/src/commands/import_test.dart @@ -22,7 +22,7 @@ void main() { ..value(scopeKeyPathToSettings, pathToOnePubSettings) ..run(() { final onepubToken = testSettings.onepubToken; - var settings = OnePubSettings.load(); + final settings = OnePubSettings.load(); final organisationName = settings.organisationName; try { @@ -31,9 +31,9 @@ void main() { onepubToken: "$onepubToken" '''); runCmd('export --file '); - var clean = runCmd('import --file '); + final clean = runCmd('import --file '); - var first = clean.first; + final first = clean.first; expect(first, 'OnePub version: $packageVersion '); expect( @@ -45,11 +45,11 @@ onepubToken: "$onepubToken" 'Add the following environment variable to your CI/CD secrets.'), isTrue); - var last = clean[(clean.length - 2)]; + final last = clean[(clean.length - 2)]; expect(last.startsWith('ONEPUB_SECRET='), isTrue); // check the secret has a guid - var parts = last.split('='); + final parts = last.split('='); expect(parts.length, equals(2)); expect(parts[1].length, equals(36)); } on DCliException {} diff --git a/test/src/commands/login_test.dart b/test/src/commands/login_test.dart index 417d294..b3c24ac 100644 --- a/test/src/commands/login_test.dart +++ b/test/src/commands/login_test.dart @@ -9,6 +9,6 @@ import 'package:test/test.dart'; void main() { test('login ...', () async { - await entrypoint(['login'], CommandSet.ONEPUB, 'onepub'); + await entrypoint(['login'], CommandSet.onepub, 'onepub'); }, tags: ['manual']); } diff --git a/test/src/commands/logout_test.dart b/test/src/commands/logout_test.dart index 0f42c70..3100a1b 100644 --- a/test/src/commands/logout_test.dart +++ b/test/src/commands/logout_test.dart @@ -9,6 +9,6 @@ import 'package:test/test.dart'; void main() { test('logout ...', () async { - await entrypoint(['logout'], CommandSet.ONEPUB, 'onepub'); + await entrypoint(['logout'], CommandSet.onepub, 'onepub'); }, tags: ['manual']); } diff --git a/test/src/commands/pub/add_dep_test.dart b/test/src/commands/pub/add_dep_test.dart index 24f5dff..5bb68f9 100644 --- a/test/src/commands/pub/add_dep_test.dart +++ b/test/src/commands/pub/add_dep_test.dart @@ -20,7 +20,7 @@ void main() { expect(pubSpec.dependencies.containsKey('node_mgmt_lib'), isFalse); // run onepub add - var progress = 'dart $pathToOnePubScript pub add node_mgmt_lib' + final progress = 'dart $pathToOnePubScript pub add node_mgmt_lib' .start(workingDirectory: dartProject.pathToProjectRoot); expect(progress.exitCode, equals(0)); @@ -31,14 +31,14 @@ void main() { }); test('cli: entrypoint ...', () async { - final packageName = 'test_packag_1'; + const packageName = 'test_packag_1'; withTempProject(packageName, (dartProject) { final size = stat(dartProject.pathToPubSpec).size; Scope() ..value(unitTestWorkingDirectoryKey, dartProject.pathToProjectRoot) ..run(() { waitForEx(entrypoint( - ['pub', 'add', 'node_mgmt_lib'], CommandSet.ONEPUB, 'onepub')); + ['pub', 'add', 'node_mgmt_lib'], CommandSet.onepub, 'onepub')); }); expect(stat(dartProject.pathToPubSpec).size, greaterThan(size)); }); diff --git a/test/src/commands/pub/private_test.dart b/test/src/commands/pub/private_test.dart index 6266530..f219012 100644 --- a/test/src/commands/pub/private_test.dart +++ b/test/src/commands/pub/private_test.dart @@ -16,10 +16,10 @@ import '../test_utils.dart'; void main() { test('cli: private ...', () async { - var settings = OnePubSettings.load(); + final settings = OnePubSettings.load(); final organisationName = settings.organisationName; - final packageName = 'test_packag_1'; + const packageName = 'test_packag_1'; withTempProject(packageName, (dartProject) { expect(dartProject.pubSpec.pubspec.publishTo, isNull); @@ -27,14 +27,15 @@ void main() { final size = stat(dartProject.pathToPubSpec).size; // run onepub private - var clean = runCmd('pub private', + final clean = runCmd('pub private', workingDirectory: dartProject.pathToProjectRoot); - var first = clean.first; + final first = clean.first; expect(first, 'OnePub version: $packageVersion '); expect( clean.contains( - '$packageName has been marked as a private package for the organisation $organisationName.'), + '$packageName has been marked as a private package for the ' + 'organisation $organisationName.'), isTrue); expect( @@ -57,14 +58,14 @@ void main() { }); test('cli: entrypoint ...', () async { - final packageName = 'test_packag_1'; + const packageName = 'test_packag_1'; withTempProject(packageName, (dartProject) { final size = stat(dartProject.pathToPubSpec).size; Scope() ..value(unitTestWorkingDirectoryKey, dartProject.pathToProjectRoot) ..run(() { waitForEx( - entrypoint(['pub', 'private'], CommandSet.ONEPUB, 'onepub')); + entrypoint(['pub', 'private'], CommandSet.onepub, 'onepub')); }); expect(stat(dartProject.pathToPubSpec).size, greaterThan(size)); }); diff --git a/test/src/commands/publish_test.dart b/test/src/commands/publish_test.dart index 16610ba..32407b6 100644 --- a/test/src/commands/publish_test.dart +++ b/test/src/commands/publish_test.dart @@ -8,6 +8,6 @@ import 'package:test/test.dart'; void main() { test('logout ...', () async { - await entrypoint(['publish'], CommandSet.OPUB, 'opub'); + await entrypoint(['publish'], CommandSet.opub, 'opub'); }); } diff --git a/test/src/commands/test_utils.dart b/test/src/commands/test_utils.dart index f95192e..586480b 100644 --- a/test/src/commands/test_utils.dart +++ b/test/src/commands/test_utils.dart @@ -9,16 +9,16 @@ import 'package:dcli/dcli.dart' hide equals; /// stripped of any ansi chars. List runCmd(String command, {String? workingDirectory}) { workingDirectory ??= pwd; - var pathToRoot = DartProject.self.pathToProjectRoot; - var pathToOnePub = join(pathToRoot, 'bin', 'onepub.dart'); + final pathToRoot = DartProject.self.pathToProjectRoot; + final pathToOnePub = join(pathToRoot, 'bin', 'onepub.dart'); - var results = + final results = '$pathToOnePub $command'.toList(workingDirectory: workingDirectory); - var clean = []; + final clean = []; /// strip all of the ansi chars from results to make matching easier. - for (var result in results) { + for (final result in results) { clean.add(Ansi.strip(result)); } @@ -27,10 +27,10 @@ List runCmd(String command, {String? workingDirectory}) { /// Creates a dart project in a temp directory from one of the /// test fixtures under test/fixtures. Pass the fixture directory -/// as the [packageName]. +/// as the [projectName]. void withTempProject( String projectName, void Function(DartProject dartProject) action) { - var pathToRoot = DartProject.self.pathToProjectRoot; + final pathToRoot = DartProject.self.pathToProjectRoot; withTempDir((workingDir) { copyTree(join(pathToRoot, 'test', 'fixtures', projectName), workingDir); @@ -38,4 +38,4 @@ void withTempProject( }); } -var pathToOnePubScript = join(DartProject.self.pathToBinDir, 'onepub.dart'); +String pathToOnePubScript = join(DartProject.self.pathToBinDir, 'onepub.dart'); diff --git a/test/src/test_settings.dart b/test/src/test_settings.dart index e7ffaf3..b852c1e 100644 --- a/test/src/test_settings.dart +++ b/test/src/test_settings.dart @@ -10,7 +10,7 @@ class TestSettings { late final SettingsYaml _settings; String get member => _settings.asString('member'); - String get cicd_member => _settings.asString('cicd_member'); + String get cicdMember => _settings.asString('cicd_member'); String get onepubToken => _settings.asString('onepub_token'); } diff --git a/tool/critical_test/pre_hook/auth.dart b/tool/critical_test/pre_hook/auth.dart index dc3bc2c..f8be1e4 100755 --- a/tool/critical_test/pre_hook/auth.dart +++ b/tool/critical_test/pre_hook/auth.dart @@ -17,28 +17,28 @@ import 'package:settings_yaml/settings_yaml.dart'; /// For details on installing dcli. /// void main(List args) { - var pathToBin = DartProject.self.pathToBinDir; + final pathToBin = DartProject.self.pathToBinDir; - var pathToOnePubExe = join(pathToBin, 'onepub.dart'); + final pathToOnePubExe = join(pathToBin, 'onepub.dart'); - var settings = + final settings = SettingsYaml.load(pathToSettings: OnePubPaths().pathToTestSettings); - var user = settings.asString('member'); + final user = settings.asString('member'); print('Please login with $user account'); /// prompt the user to login inot onepub. '$pathToOnePubExe login'.run; - var tokenStore = OnePubTokenStore(); + final tokenStore = OnePubTokenStore(); if (!tokenStore.isLoggedIn) { printerr(red('Login Failed. Tests run stopped')); exit(1); } final onepubSettings = OnePubSettings.load(); - var url = onepubSettings.onepubApiUrl; + final url = onepubSettings.onepubApiUrl; final credentials = tokenStore.tokenStore.findCredential(Uri.parse(url)); if (credentials == null) { @@ -46,7 +46,7 @@ void main(List args) { exit(1); } - var onePubToken = credentials.token; + final onePubToken = credentials.token; settings['OnePubToken'] = onePubToken; settings.save();