From 0b8293f2aaa67c678fc6b96425f00a7a60342131 Mon Sep 17 00:00:00 2001 From: Felix Angelov Date: Thu, 2 Mar 2023 11:37:56 -0600 Subject: [PATCH] chore: create new cli --- .github/ISSUE_TEMPLATE/ config.yml | 1 + .github/ISSUE_TEMPLATE/bug_report.md | 29 +++ .github/ISSUE_TEMPLATE/feature_request.md | 18 ++ .github/PULL_REQUEST_TEMPLATE.md | 23 +++ .github/workflows/main.yaml | 46 +++++ .gitignore | 15 ++ CHANGELOG.md | 3 + COPYRIGHT | 3 + LICENSE-APACHE | 176 ++++++++++++++++++ LICENSE-MIT | 19 ++ README.md | 3 + analysis_options.yaml | 4 + bin/shorebird.dart | 18 ++ dart_test.yaml | 3 + lib/shorebird_cli.dart | 10 ++ lib/src/command_runner.dart | 144 +++++++++++++++ lib/src/commands/commands.dart | 2 + lib/src/commands/publish_command.dart | 26 +++ lib/src/commands/update_command.dart | 74 ++++++++ lib/src/version.dart | 2 + pubspec.yaml | 23 +++ test/ensure_build_test.dart | 9 + test/src/command_runner_test.dart | 178 ++++++++++++++++++ test/src/commands/publish_command_test.dart | 26 +++ test/src/commands/update_command_test.dart | 188 ++++++++++++++++++++ 25 files changed, 1043 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/ config.yml create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/workflows/main.yaml create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 COPYRIGHT create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 README.md create mode 100644 analysis_options.yaml create mode 100644 bin/shorebird.dart create mode 100644 dart_test.yaml create mode 100644 lib/shorebird_cli.dart create mode 100644 lib/src/command_runner.dart create mode 100644 lib/src/commands/commands.dart create mode 100644 lib/src/commands/publish_command.dart create mode 100644 lib/src/commands/update_command.dart create mode 100644 lib/src/version.dart create mode 100644 pubspec.yaml create mode 100644 test/ensure_build_test.dart create mode 100644 test/src/command_runner_test.dart create mode 100644 test/src/commands/publish_command_test.dart create mode 100644 test/src/commands/update_command_test.dart diff --git a/.github/ISSUE_TEMPLATE/ config.yml b/.github/ISSUE_TEMPLATE/ config.yml new file mode 100644 index 00000000..3ba13e0c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/ config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..50a4c7b8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,29 @@ +--- +name: Bug Report +about: Create a report to help us improve +title: "fix: " +labels: bug +--- + +**Description** + +A clear and concise description of what the bug is. + +**Steps To Reproduce** + +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected Behavior** + +A clear and concise description of what you expected to happen. + +**Screenshots** + +If applicable, add screenshots to help explain your problem. + +**Additional Context** + +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..ddd2fcca --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,18 @@ +--- +name: Feature Request +about: A new feature to be added to the project +title: "feat: " +labels: feature +--- + +**Description** + +Clearly describe what you are looking to add. The more context the better. + +**Requirements** + +- [ ] Checklist of requirements to be fulfilled + +**Additional Context** + +Add any other context or screenshots about the feature request go here. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..6b9372ef --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,23 @@ + + +## Description + + + +## Type of Change + + + +- [ ] โœจ New feature (non-breaking change which adds functionality) +- [ ] ๐Ÿ› ๏ธ Bug fix (non-breaking change which fixes an issue) +- [ ] โŒ Breaking change (fix or feature that would cause existing functionality to change) +- [ ] ๐Ÿงน Code refactor +- [ ] โœ… Build configuration change +- [ ] ๐Ÿ“ Documentation +- [ ] ๐Ÿ—‘๏ธ Chore diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml new file mode 100644 index 00000000..fa9a05ae --- /dev/null +++ b/.github/workflows/main.yaml @@ -0,0 +1,46 @@ +name: ci + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +on: + pull_request: + paths: + - ".github/workflows/shorebird_cli.yaml" + - "lib/**" + - "test/**" + - "pubspec.yaml" + push: + branches: + - main + paths: + - ".github/workflows/shorebird_cli.yaml" + - "lib/**" + - "test/**" + - "pubspec.yaml" + +jobs: + semantic-pull-request: + uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/semantic_pull_request.yml@v1 + + build: + uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/dart_package.yml@v1 + + verify-version: + runs-on: ubuntu-latest + steps: + - name: ๐Ÿ“š Git Checkout + uses: actions/checkout@v2 + + - name: ๐ŸŽฏ Setup Dart + uses: dart-lang/setup-dart@v1 + with: + sdk: "stable" + + - name: ๐Ÿ“ฆ Install Dependencies + run: | + dart pub get + + - name: ๐Ÿ”Ž Verify version + run: dart run test --run-skipped -t version-verify diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..9f6ee8a7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +# See https://www.dartlang.org/guides/libraries/private-files + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +pubspec.lock + +# Files generated during tests +.test_coverage.dart +coverage/ +.test_runner.dart + +# Android studio and IntelliJ +.idea \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..4fff97bd --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3 @@ +# 0.0.1 + +- feat: initial commit ๐ŸŽ‰ diff --git a/COPYRIGHT b/COPYRIGHT new file mode 100644 index 00000000..4e5eae7a --- /dev/null +++ b/COPYRIGHT @@ -0,0 +1,3 @@ +Licensed under either of Apache License, Version 2.0 (LICENSE-APACHE or +http://www.apache.org/licenses/LICENSE-2.0) MIT license (LICENSE-MIT or +http://opensource.org/licenses/MIT) at your option. diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 00000000..a7e77cb2 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 00000000..6802bc4b --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,19 @@ +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 00000000..fba6ae29 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +## shorebird_cli + +The Shorebird command-line tool. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 00000000..d767e5d3 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:very_good_analysis/analysis_options.4.0.0.yaml +linter: + rules: + public_member_api_docs: false diff --git a/bin/shorebird.dart b/bin/shorebird.dart new file mode 100644 index 00000000..a5aa097e --- /dev/null +++ b/bin/shorebird.dart @@ -0,0 +1,18 @@ +import 'dart:io'; + +import 'package:shorebird_cli/src/command_runner.dart'; + +Future main(List args) async { + await _flushThenExit(await ShorebirdCliCommandRunner().run(args)); +} + +/// Flushes the stdout and stderr streams, then exits the program with the given +/// status code. +/// +/// This returns a Future that will never complete, since the program will have +/// exited already. This is useful to prevent Future chains from proceeding +/// after you've decided to exit. +Future _flushThenExit(int status) { + return Future.wait([stdout.close(), stderr.close()]) + .then((_) => exit(status)); +} diff --git a/dart_test.yaml b/dart_test.yaml new file mode 100644 index 00000000..2f46c7e9 --- /dev/null +++ b/dart_test.yaml @@ -0,0 +1,3 @@ +tags: + version-verify: + skip: "Should only be run during pull request. Verifies if version file is updated." \ No newline at end of file diff --git a/lib/shorebird_cli.dart b/lib/shorebird_cli.dart new file mode 100644 index 00000000..f328272e --- /dev/null +++ b/lib/shorebird_cli.dart @@ -0,0 +1,10 @@ +/// shorebird_cli, The shorebird command-line tool +/// +/// ```sh +/// # activate shorebird_cli +/// dart pub global activate shorebird_cli +/// +/// # see usage +/// shorebird --help +/// ``` +library shorebird_cli; diff --git a/lib/src/command_runner.dart b/lib/src/command_runner.dart new file mode 100644 index 00000000..ccdc648f --- /dev/null +++ b/lib/src/command_runner.dart @@ -0,0 +1,144 @@ +import 'package:args/args.dart'; +import 'package:args/command_runner.dart'; +import 'package:cli_completion/cli_completion.dart'; +import 'package:mason_logger/mason_logger.dart'; +import 'package:pub_updater/pub_updater.dart'; +import 'package:shorebird_cli/src/commands/commands.dart'; +import 'package:shorebird_cli/src/version.dart'; + +const executableName = 'shorebird'; +const packageName = 'shorebird_cli'; +const description = 'The shorebird command-line tool'; + +/// {@template shorebird_cli_command_runner} +/// A [CommandRunner] for the CLI. +/// +/// ``` +/// $ shorebird --version +/// ``` +/// {@endtemplate} +class ShorebirdCliCommandRunner extends CompletionCommandRunner { + /// {@macro shorebird_cli_command_runner} + ShorebirdCliCommandRunner({ + Logger? logger, + PubUpdater? pubUpdater, + }) : _logger = logger ?? Logger(), + _pubUpdater = pubUpdater ?? PubUpdater(), + super(executableName, description) { + // Add root options and flags + argParser + ..addFlag( + 'version', + abbr: 'v', + negatable: false, + help: 'Print the current version.', + ) + ..addFlag( + 'verbose', + help: 'Noisy logging, including all shell commands executed.', + ); + + // Add sub commands + addCommand(PublishCommand(logger: _logger)); + addCommand(UpdateCommand(logger: _logger, pubUpdater: _pubUpdater)); + } + + @override + void printUsage() => _logger.info(usage); + + final Logger _logger; + final PubUpdater _pubUpdater; + + @override + Future run(Iterable args) async { + try { + final topLevelResults = parse(args); + if (topLevelResults['verbose'] == true) { + _logger.level = Level.verbose; + } + return await runCommand(topLevelResults) ?? ExitCode.success.code; + } on FormatException catch (e, stackTrace) { + // On format errors, show the commands error message, root usage and + // exit with an error code + _logger + ..err(e.message) + ..err('$stackTrace') + ..info('') + ..info(usage); + return ExitCode.usage.code; + } on UsageException catch (e) { + // On usage errors, show the commands usage message and + // exit with an error code + _logger + ..err(e.message) + ..info('') + ..info(e.usage); + return ExitCode.usage.code; + } + } + + @override + Future runCommand(ArgResults topLevelResults) async { + // Fast track completion command + if (topLevelResults.command?.name == 'completion') { + await super.runCommand(topLevelResults); + return ExitCode.success.code; + } + + // Verbose logs + _logger + ..detail('Argument information:') + ..detail(' Top level options:'); + for (final option in topLevelResults.options) { + if (topLevelResults.wasParsed(option)) { + _logger.detail(' - $option: ${topLevelResults[option]}'); + } + } + if (topLevelResults.command != null) { + final commandResult = topLevelResults.command!; + _logger + ..detail(' Command: ${commandResult.name}') + ..detail(' Command options:'); + for (final option in commandResult.options) { + if (commandResult.wasParsed(option)) { + _logger.detail(' - $option: ${commandResult[option]}'); + } + } + } + + // Run the command or show version + final int? exitCode; + if (topLevelResults['version'] == true) { + _logger.info(packageVersion); + exitCode = ExitCode.success.code; + } else { + exitCode = await super.runCommand(topLevelResults); + } + + // Check for updates + if (topLevelResults.command?.name != UpdateCommand.commandName) { + await _checkForUpdates(); + } + + 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 { + final latestVersion = await _pubUpdater.getLatestVersion(packageName); + final isUpToDate = packageVersion == latestVersion; + if (!isUpToDate) { + _logger + ..info('') + ..info( + ''' +${lightYellow.wrap('Update available!')} ${lightCyan.wrap(packageVersion)} \u2192 ${lightCyan.wrap(latestVersion)} +Run ${lightCyan.wrap('$executableName update')} to update''', + ); + } + } catch (_) {} + } +} diff --git a/lib/src/commands/commands.dart b/lib/src/commands/commands.dart new file mode 100644 index 00000000..25f6ce6c --- /dev/null +++ b/lib/src/commands/commands.dart @@ -0,0 +1,2 @@ +export 'publish_command.dart'; +export 'update_command.dart'; diff --git a/lib/src/commands/publish_command.dart b/lib/src/commands/publish_command.dart new file mode 100644 index 00000000..e1a3ce0e --- /dev/null +++ b/lib/src/commands/publish_command.dart @@ -0,0 +1,26 @@ +import 'package:args/command_runner.dart'; +import 'package:mason_logger/mason_logger.dart'; + +/// {@template sample_command} +/// +/// `shorebird sample` +/// A [Command] to exemplify a sub command +/// {@endtemplate} +class PublishCommand extends Command { + /// {@macro sample_command} + PublishCommand({required Logger logger}) : _logger = logger; + + @override + String get description => 'Publish an update.'; + + @override + String get name => 'publish'; + + final Logger _logger; + + @override + Future run() async { + _logger.info('Coming soon...'); + return ExitCode.success.code; + } +} diff --git a/lib/src/commands/update_command.dart b/lib/src/commands/update_command.dart new file mode 100644 index 00000000..810eda19 --- /dev/null +++ b/lib/src/commands/update_command.dart @@ -0,0 +1,74 @@ +import 'dart:io'; + +import 'package:args/command_runner.dart'; +import 'package:mason_logger/mason_logger.dart'; +import 'package:pub_updater/pub_updater.dart'; +import 'package:shorebird_cli/src/command_runner.dart'; +import 'package:shorebird_cli/src/version.dart'; + +/// {@template update_command} +/// A command which updates the CLI. +/// {@endtemplate} +class UpdateCommand extends Command { + /// {@macro update_command} + UpdateCommand({ + required Logger logger, + PubUpdater? pubUpdater, + }) : _logger = logger, + _pubUpdater = pubUpdater ?? PubUpdater(); + + final Logger _logger; + final PubUpdater _pubUpdater; + + @override + String get description => 'Update the CLI.'; + + static const String commandName = 'update'; + + @override + String get name => commandName; + + @override + Future run() async { + final updateCheckProgress = _logger.progress('Checking for updates'); + late final String latestVersion; + try { + latestVersion = await _pubUpdater.getLatestVersion(packageName); + } catch (error) { + updateCheckProgress.fail(); + _logger.err('$error'); + return ExitCode.software.code; + } + updateCheckProgress.complete('Checked for updates'); + + final isUpToDate = packageVersion == latestVersion; + if (isUpToDate) { + _logger.info('CLI is already at the latest version.'); + return ExitCode.success.code; + } + + final updateProgress = _logger.progress('Updating to $latestVersion'); + + late final ProcessResult result; + try { + result = await _pubUpdater.update( + packageName: packageName, + versionConstraint: latestVersion, + ); + } catch (error) { + updateProgress.fail(); + _logger.err('$error'); + return ExitCode.software.code; + } + + if (result.exitCode != ExitCode.success.code) { + updateProgress.fail(); + _logger.err('Error updating CLI: ${result.stderr}'); + return ExitCode.software.code; + } + + updateProgress.complete('Updated to $latestVersion'); + + return ExitCode.success.code; + } +} diff --git a/lib/src/version.dart b/lib/src/version.dart new file mode 100644 index 00000000..67a7647b --- /dev/null +++ b/lib/src/version.dart @@ -0,0 +1,2 @@ +// Generated code. Do not modify. +const packageVersion = '0.0.1'; diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 00000000..28e77e87 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,23 @@ +name: shorebird_cli +description: The shorebird command-line tool +version: 0.0.1 + +environment: + sdk: ">=2.19.0 <3.0.0" + +dependencies: + args: ^2.3.1 + cli_completion: ^0.2.0 + mason_logger: ^0.2.4 + pub_updater: ^0.2.4 + +dev_dependencies: + build_runner: ^2.0.0 + build_verify: ^3.0.0 + build_version: ^2.0.0 + mocktail: ^0.3.0 + test: ^1.19.2 + very_good_analysis: ^4.0.0 + +executables: + shorebird: diff --git a/test/ensure_build_test.dart b/test/ensure_build_test.dart new file mode 100644 index 00000000..3d1173b0 --- /dev/null +++ b/test/ensure_build_test.dart @@ -0,0 +1,9 @@ +@Tags(['version-verify']) +library; + +import 'package:build_verify/build_verify.dart'; +import 'package:test/test.dart'; + +void main() { + test('ensure_build', expectBuildClean); +} diff --git a/test/src/command_runner_test.dart b/test/src/command_runner_test.dart new file mode 100644 index 00000000..6dcefa28 --- /dev/null +++ b/test/src/command_runner_test.dart @@ -0,0 +1,178 @@ +import 'dart:io'; + +import 'package:args/command_runner.dart'; +import 'package:cli_completion/cli_completion.dart'; +import 'package:mason_logger/mason_logger.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:pub_updater/pub_updater.dart'; +import 'package:shorebird_cli/src/command_runner.dart'; +import 'package:shorebird_cli/src/version.dart'; +import 'package:test/test.dart'; + +class _MockLogger extends Mock implements Logger {} + +class _MockProcessResult extends Mock implements ProcessResult {} + +class _MockProgress extends Mock implements Progress {} + +class _MockPubUpdater extends Mock implements PubUpdater {} + +const latestVersion = '0.0.0'; + +final updatePrompt = ''' +${lightYellow.wrap('Update available!')} ${lightCyan.wrap(packageVersion)} \u2192 ${lightCyan.wrap(latestVersion)} +Run ${lightCyan.wrap('$executableName update')} to update'''; + +void main() { + group('ShorebirdCliCommandRunner', () { + late PubUpdater pubUpdater; + late Logger logger; + late ProcessResult processResult; + late ShorebirdCliCommandRunner commandRunner; + + setUp(() { + pubUpdater = _MockPubUpdater(); + + when( + () => pubUpdater.getLatestVersion(any()), + ).thenAnswer((_) async => packageVersion); + + logger = _MockLogger(); + + processResult = _MockProcessResult(); + when(() => processResult.exitCode).thenReturn(ExitCode.success.code); + + commandRunner = ShorebirdCliCommandRunner( + logger: logger, + pubUpdater: pubUpdater, + ); + }); + + test('shows update message when newer version exists', () async { + when( + () => pubUpdater.getLatestVersion(any()), + ).thenAnswer((_) async => latestVersion); + + final result = await commandRunner.run(['--version']); + expect(result, equals(ExitCode.success.code)); + verify(() => logger.info(updatePrompt)).called(1); + }); + + test( + 'Does not show update message when the shell calls the ' + 'completion command', + () async { + when( + () => pubUpdater.getLatestVersion(any()), + ).thenAnswer((_) async => latestVersion); + + final result = await commandRunner.run(['completion']); + expect(result, equals(ExitCode.success.code)); + verifyNever(() => logger.info(updatePrompt)); + }, + ); + + test('does not show update message when using update command', () async { + when( + () => pubUpdater.getLatestVersion(any()), + ).thenAnswer((_) async => latestVersion); + when( + () => pubUpdater.update( + packageName: packageName, + versionConstraint: any(named: 'versionConstraint'), + ), + ).thenAnswer((_) async => processResult); + when( + () => pubUpdater.isUpToDate( + packageName: any(named: 'packageName'), + currentVersion: any(named: 'currentVersion'), + ), + ).thenAnswer((_) async => true); + + final progress = _MockProgress(); + final progressLogs = []; + when(() => progress.complete(any())).thenAnswer((_) { + final message = _.positionalArguments.elementAt(0) as String?; + if (message != null) progressLogs.add(message); + }); + when(() => logger.progress(any())).thenReturn(progress); + + final result = await commandRunner.run(['update']); + expect(result, equals(ExitCode.success.code)); + verifyNever(() => logger.info(updatePrompt)); + }); + + test('can be instantiated without an explicit analytics/logger instance', + () { + final commandRunner = ShorebirdCliCommandRunner(); + expect(commandRunner, isNotNull); + expect(commandRunner, isA>()); + }); + + test('handles FormatException', () async { + const exception = FormatException('oops!'); + var isFirstInvocation = true; + when(() => logger.info(any())).thenAnswer((_) { + if (isFirstInvocation) { + isFirstInvocation = false; + throw exception; + } + }); + final result = await commandRunner.run(['--version']); + expect(result, equals(ExitCode.usage.code)); + verify(() => logger.err(exception.message)).called(1); + verify(() => logger.info(commandRunner.usage)).called(1); + }); + + test('handles UsageException', () async { + final exception = UsageException('oops!', 'exception usage'); + var isFirstInvocation = true; + when(() => logger.info(any())).thenAnswer((_) { + if (isFirstInvocation) { + isFirstInvocation = false; + throw exception; + } + }); + final result = await commandRunner.run(['--version']); + expect(result, equals(ExitCode.usage.code)); + verify(() => logger.err(exception.message)).called(1); + verify(() => logger.info('exception usage')).called(1); + }); + + group('--version', () { + test('outputs current version', () async { + final result = await commandRunner.run(['--version']); + expect(result, equals(ExitCode.success.code)); + verify(() => logger.info(packageVersion)).called(1); + }); + }); + + group('--verbose', () { + test('enables verbose logging', () async { + final result = await commandRunner.run(['--verbose']); + expect(result, equals(ExitCode.success.code)); + + verify(() => logger.detail('Argument information:')).called(1); + verify(() => logger.detail(' Top level options:')).called(1); + verify(() => logger.detail(' - verbose: true')).called(1); + verifyNever(() => logger.detail(' Command options:')); + }); + + test('enables verbose logging for sub commands', () async { + final result = await commandRunner.run([ + '--verbose', + 'sample', + '--cyan', + ]); + expect(result, equals(ExitCode.success.code)); + + verify(() => logger.detail('Argument information:')).called(1); + verify(() => logger.detail(' Top level options:')).called(1); + verify(() => logger.detail(' - verbose: true')).called(1); + verify(() => logger.detail(' Command: sample')).called(1); + verify(() => logger.detail(' Command options:')).called(1); + verify(() => logger.detail(' - cyan: true')).called(1); + }); + }); + }); +} diff --git a/test/src/commands/publish_command_test.dart b/test/src/commands/publish_command_test.dart new file mode 100644 index 00000000..0df9bf3e --- /dev/null +++ b/test/src/commands/publish_command_test.dart @@ -0,0 +1,26 @@ +import 'package:mason_logger/mason_logger.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:shorebird_cli/src/command_runner.dart'; +import 'package:test/test.dart'; + +class _MockLogger extends Mock implements Logger {} + +void main() { + group('publish', () { + late Logger logger; + late ShorebirdCliCommandRunner commandRunner; + + setUp(() { + logger = _MockLogger(); + commandRunner = ShorebirdCliCommandRunner(logger: logger); + }); + + test('outputs coming soon...', () async { + final exitCode = await commandRunner.run(['publish']); + + expect(exitCode, ExitCode.success.code); + + verify(() => logger.info('Coming soon...')).called(1); + }); + }); +} diff --git a/test/src/commands/update_command_test.dart b/test/src/commands/update_command_test.dart new file mode 100644 index 00000000..b2bfb61a --- /dev/null +++ b/test/src/commands/update_command_test.dart @@ -0,0 +1,188 @@ +import 'dart:io'; + +import 'package:mason_logger/mason_logger.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:pub_updater/pub_updater.dart'; +import 'package:shorebird_cli/src/command_runner.dart'; +import 'package:shorebird_cli/src/commands/commands.dart'; +import 'package:shorebird_cli/src/version.dart'; +import 'package:test/test.dart'; + +class _MockLogger extends Mock implements Logger {} + +class _MockProcessResult extends Mock implements ProcessResult {} + +class _MockProgress extends Mock implements Progress {} + +class _MockPubUpdater extends Mock implements PubUpdater {} + +void main() { + const latestVersion = '0.0.0'; + + group('update', () { + late PubUpdater pubUpdater; + late Logger logger; + late ProcessResult processResult; + late ShorebirdCliCommandRunner commandRunner; + + setUp(() { + final progress = _MockProgress(); + final progressLogs = []; + pubUpdater = _MockPubUpdater(); + logger = _MockLogger(); + processResult = _MockProcessResult(); + commandRunner = ShorebirdCliCommandRunner( + logger: logger, + pubUpdater: pubUpdater, + ); + + when( + () => pubUpdater.getLatestVersion(any()), + ).thenAnswer((_) async => packageVersion); + when( + () => pubUpdater.update( + packageName: packageName, + versionConstraint: latestVersion, + ), + ).thenAnswer((_) async => processResult); + when( + () => pubUpdater.isUpToDate( + packageName: any(named: 'packageName'), + currentVersion: any(named: 'currentVersion'), + ), + ).thenAnswer((_) async => true); + when(() => progress.complete(any())).thenAnswer((_) { + final message = _.positionalArguments.elementAt(0) as String?; + if (message != null) progressLogs.add(message); + }); + when(() => logger.progress(any())).thenReturn(progress); + when(() => processResult.exitCode).thenReturn(ExitCode.success.code); + }); + + test('can be instantiated without a pub updater', () { + final command = UpdateCommand(logger: logger); + expect(command, isNotNull); + }); + + test( + 'handles pub latest version query errors', + () async { + when( + () => pubUpdater.getLatestVersion(any()), + ).thenThrow(Exception('oops')); + final result = await commandRunner.run(['update']); + expect(result, equals(ExitCode.software.code)); + verify(() => logger.progress('Checking for updates')).called(1); + verify(() => logger.err('Exception: oops')); + verifyNever( + () => pubUpdater.update( + packageName: any(named: 'packageName'), + versionConstraint: any(named: 'versionConstraint'), + ), + ); + }, + ); + + test( + 'handles pub update errors', + () async { + when( + () => pubUpdater.getLatestVersion(any()), + ).thenAnswer((_) async => latestVersion); + when( + () => pubUpdater.update( + packageName: any(named: 'packageName'), + versionConstraint: any(named: 'versionConstraint'), + ), + ).thenThrow(Exception('oops')); + final result = await commandRunner.run(['update']); + expect(result, equals(ExitCode.software.code)); + verify(() => logger.progress('Checking for updates')).called(1); + verify(() => logger.err('Exception: oops')); + verify( + () => pubUpdater.update( + packageName: any(named: 'packageName'), + versionConstraint: any(named: 'versionConstraint'), + ), + ).called(1); + }, + ); + + test('handles pub update process errors', () async { + const error = 'Oh no! Installing this is not possible right now!'; + + when(() => processResult.exitCode).thenReturn(1); + when(() => processResult.stderr).thenReturn(error); + when( + () => pubUpdater.getLatestVersion(any()), + ).thenAnswer((_) async => latestVersion); + + when( + () => pubUpdater.update( + packageName: any(named: 'packageName'), + versionConstraint: any(named: 'versionConstraint'), + ), + ).thenAnswer((_) async => processResult); + + final result = await commandRunner.run(['update']); + + expect(result, equals(ExitCode.software.code)); + verify(() => logger.progress('Checking for updates')).called(1); + verify(() => logger.err('Error updating CLI: $error')); + verify( + () => pubUpdater.update( + packageName: any(named: 'packageName'), + versionConstraint: any(named: 'versionConstraint'), + ), + ).called(1); + }); + + test( + 'updates when newer version exists', + () async { + when( + () => pubUpdater.getLatestVersion(any()), + ).thenAnswer((_) async => latestVersion); + when( + () => pubUpdater.update( + packageName: any(named: 'packageName'), + versionConstraint: any(named: 'versionConstraint'), + ), + ).thenAnswer((_) async => processResult); + when(() => logger.progress(any())).thenReturn(_MockProgress()); + final result = await commandRunner.run(['update']); + expect(result, equals(ExitCode.success.code)); + verify(() => logger.progress('Checking for updates')).called(1); + verify(() => logger.progress('Updating to $latestVersion')).called(1); + verify( + () => pubUpdater.update( + packageName: packageName, + versionConstraint: latestVersion, + ), + ).called(1); + }, + ); + + test( + 'does not update when already on latest version', + () async { + when( + () => pubUpdater.getLatestVersion(any()), + ).thenAnswer((_) async => packageVersion); + when(() => logger.progress(any())).thenReturn(_MockProgress()); + final result = await commandRunner.run(['update']); + expect(result, equals(ExitCode.success.code)); + verify( + () => logger.info('CLI is already at the latest version.'), + ).called(1); + verifyNever(() => logger.progress('Updating to $latestVersion')); + verifyNever( + () => pubUpdater.update( + packageName: any(named: 'packageName'), + versionConstraint: any(named: 'versionConstraint'), + ), + ); + }, + ); + }); +}