Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow packages check licenses to fetch licenses #842

Merged
merged 29 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
cbc6c9b
feat: include hidden check licenses command
alestiago Oct 4, 2023
bd6e631
coverage
alestiago Oct 5, 2023
9dfc476
typo
alestiago Oct 5, 2023
2c416f7
analyzer
alestiago Oct 5, 2023
6eeb7a4
Merge branch 'main' into alestiago/include-hidden-check-command
alestiago Oct 5, 2023
5b9fe36
feat: allow fetching licenses
alestiago Oct 5, 2023
31cc3a0
full stop
alestiago Oct 5, 2023
d13d6dc
_isHostedDirectDependency
alestiago Oct 6, 2023
5cf0b0b
Merge branch 'main' into alestiago/licenses-fetch
alestiago Oct 6, 2023
924c51b
Merge remote-tracking branch 'origin' into alestiago/licenses-fetch
alestiago Oct 9, 2023
fe5a5dd
testing
alestiago Oct 9, 2023
19414b1
licenses and packages singular
alestiago Oct 9, 2023
5f0af9d
included TODOs
alestiago Oct 9, 2023
d434f6f
test progress
alestiago Oct 10, 2023
225837c
Merge branch 'main' into alestiago/licenses-fetch
alestiago Oct 10, 2023
71c965b
refactor to "dependencyName"
alestiago Oct 10, 2023
754728b
refactor _tryParsePubspecLock
alestiago Oct 10, 2023
d88047d
remove old ignore
alestiago Oct 10, 2023
ba9c203
missing cancel
alestiago Oct 10, 2023
ad09a3c
remove commented code
alestiago Oct 10, 2023
4da6306
words
alestiago Oct 10, 2023
6d5a23d
words
alestiago Oct 10, 2023
cf25b30
removed argResults override
alestiago Oct 10, 2023
3a03531
used const
alestiago Oct 10, 2023
6fac91b
test progress update
alestiago Oct 10, 2023
3b97198
usage exception
alestiago Oct 10, 2023
23c6449
improved docs
alestiago Oct 10, 2023
8bcf934
improved docs
alestiago Oct 10, 2023
0c38268
improve docs
alestiago Oct 10, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 113 additions & 2 deletions lib/src/commands/packages/commands/check/commands/licenses.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import 'dart:io';

import 'package:args/args.dart';
import 'package:args/command_runner.dart';
import 'package:mason/mason.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
import 'package:pubspec_lock/pubspec_lock.dart';
import 'package:very_good_cli/src/pub_license/pub_license.dart';

/// The basename of the pubspec lock file.
@visibleForTesting
const pubspecLockBasename = 'pubspec.lock';

/// {@template packages_check_licenses_command}
/// `very_good packages check licenses` command for checking packages licenses.
/// {@endtemplate}
Expand All @@ -13,10 +23,8 @@ class PackagesCheckLicensesCommand extends Command<int> {
}) : _logger = logger ?? Logger(),
_pubLicense = pubLicense ?? PubLicense();

// ignore: unused_field
final Logger _logger;

// ignore: unused_field
final PubLicense _pubLicense;

@override
Expand All @@ -29,8 +37,111 @@ class PackagesCheckLicensesCommand extends Command<int> {
@override
bool get hidden => true;

ArgResults get _argResults => argResults!;

@override
Future<int> run() async {
if (_argResults.rest.length > 1) {
usageException('Too many arguments');
}

final target = _argResults.rest.length == 1 ? _argResults.rest[0] : '.';
final targetPath = path.normalize(Directory(target).absolute.path);

final progress = _logger.progress('Checking licenses on $targetPath');

final pubspecLockFile = File(path.join(targetPath, pubspecLockBasename));
if (!pubspecLockFile.existsSync()) {
progress.cancel();
_logger.err('Could not find a $pubspecLockBasename in $targetPath');
return ExitCode.noInput.code;
}

final pubspecLock = _tryParsePubspecLock(pubspecLockFile);
if (pubspecLock == null) {
progress.cancel();
_logger.err('Could not parse $pubspecLockBasename in $targetPath');
return ExitCode.noInput.code;
}

final filteredDependencies =
pubspecLock.packages.where(_isHostedDirectDependency);

if (filteredDependencies.isEmpty) {
progress.cancel();
_logger.err('No hosted direct dependencies found in $targetPath');
return ExitCode.usage.code;
}

final licenses = <String, Set<String>>{};
for (final dependency in filteredDependencies) {
progress.update(
'Collecting licenses of ${licenses.length}/${filteredDependencies.length} packages',
);

final dependencyName = dependency.package();
Set<String> rawLicense;
try {
rawLicense = await _pubLicense.getLicense(dependencyName);
} on PubLicenseException catch (e) {
progress.cancel();
_logger.err('[$dependencyName] ${e.message}');
return ExitCode.unavailable.code;
} catch (e) {
progress.cancel();
_logger.err('[$dependencyName] Unexpected failure with error: $e');
return ExitCode.software.code;
}

licenses[dependencyName] = rawLicense;
}

final licenseTypes = licenses.values.fold(
<String>{},
(previousValue, element) => previousValue..addAll(element),
);
final licenseCount = licenses.values.fold<int>(
0,
(previousValue, element) => previousValue + element.length,
);

final licenseWord = licenseCount == 1 ? 'license' : 'licenses';
final packageWord =
filteredDependencies.length == 1 ? 'package' : 'packages';
progress.complete(
'''Retrieved $licenseCount $licenseWord from ${filteredDependencies.length} $packageWord of type: ${licenseTypes.toList().stringify()}.''',
);

return ExitCode.success.code;
}
}

/// Attempts to parse a [PubspecLock] file in the given [path].
///
/// If [pubspecLockFile] is not readable or fails to be parsed, `null` is
/// returned.
PubspecLock? _tryParsePubspecLock(File pubspecLockFile) {
try {
return pubspecLockFile.readAsStringSync().loadPubspecLockFromYaml();
} catch (e) {
return null;
}
}

bool _isHostedDirectDependency(
PackageDependency dependency,
) {
// ignore: invalid_use_of_protected_member
final isPubHostedDependency = dependency.hosted != null;
final isDirectDependency = dependency.type() == DependencyType.direct;
return isPubHostedDependency && isDirectDependency;
}

extension on List<Object> {
String stringify() {
if (isEmpty) return '';
if (length == 1) return first.toString();
final last = removeLast();
return '${join(', ')} and $last';
}
}
4 changes: 2 additions & 2 deletions lib/src/pub_license/pub_license.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/// Enables checking a package's license from pub.dev.
///
/// This library is intented to be used by Very Good CLI to help extracting
/// license information. The existance of this library is likely to be
/// This library is intended to be used by Very Good CLI to help extracting
/// license information. The existence of this library is likely to be
/// ephemeral. It may be obsolete once [pub.dev](https://pub.dev/) exposes
/// stable license information in their official API; you may track the
/// progress [here](https://github.com/dart-lang/pub-dev/issues/4717).
Expand Down
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ dependencies:
meta: ^1.3.0
path: ^1.8.0
pub_updater: ">=0.3.1 <0.5.0"
pubspec_lock: ^3.0.2
pubspec_parse: ^1.2.0
stack_trace: ^1.10.0
universal_io: ^2.0.4
Expand Down
1 change: 1 addition & 0 deletions test/helpers/command_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ void Function() withRunner(
final commandRunner = VeryGoodCommandRunner(
logger: logger,
pubUpdater: pubUpdater,
pubLicense: pubLicense,
);

when(() => progress.complete(any())).thenAnswer((_) {
Expand Down
Loading