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: add --allowed to check licenses #848

Merged
merged 79 commits into from
Oct 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
79 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
94657b5
feat: allow ignoring failures when checking licenses
alestiago Oct 10, 2023
3a03531
used const
alestiago Oct 10, 2023
eec1abf
testing
alestiago Oct 10, 2023
928e699
more tests and fixes
alestiago Oct 10, 2023
6fac91b
test progress update
alestiago Oct 10, 2023
f75c0d5
removed TODO
alestiago Oct 10, 2023
b1c49e4
refactor _composeReport
alestiago Oct 10, 2023
3b97198
usage exception
alestiago Oct 10, 2023
4c42853
Merge branch 'alestiago/licenses-fetch' into alestiago/licenses-ignor…
alestiago Oct 10, 2023
8ce817c
feat: add `dependency-type` to `check licenses`
alestiago Oct 10, 2023
cd321eb
format
alestiago Oct 10, 2023
10a9c75
updated usage
alestiago Oct 10, 2023
097beaf
started testing
alestiago Oct 10, 2023
56eb24b
reach test coverage
alestiago Oct 10, 2023
8876d4e
refactor dependencyType
alestiago Oct 10, 2023
461808a
completed all tests
alestiago Oct 10, 2023
d3318bb
Merge remote-tracking branch 'origin' into alestiago/licenses-ignore-…
alestiago Oct 11, 2023
0b49949
update flag description
alestiago Oct 11, 2023
f81adce
Merge branch 'alestiago/licenses-ignore-failures' into alestiago/lice…
alestiago Oct 11, 2023
840d267
chore: generated spdx_license.gen.dart
alestiago Oct 11, 2023
0dbb8f3
license output
alestiago Oct 11, 2023
25d50db
improved report
alestiago Oct 11, 2023
2c64cc5
improve banned report
alestiago Oct 11, 2023
49354b2
refactor coloredLicenseTypes
alestiago Oct 11, 2023
4fa8617
full stop
alestiago Oct 11, 2023
2a2e390
add uri
alestiago Oct 11, 2023
1a3a503
changed to warning
alestiago Oct 11, 2023
cd0b8b2
Merge remote-tracking branch 'origin' into alestiago/licenses-specify…
alestiago Oct 12, 2023
143ad5c
Merge branch 'alestiago/licenses-specify-dependency-type' into alesti…
alestiago Oct 13, 2023
beb5178
update _expectedPackagesCheckLicensesUsage
alestiago Oct 13, 2023
122cee2
updated tests
alestiago Oct 13, 2023
ac0beeb
test for invalid warning
alestiago Oct 13, 2023
9bb6af9
coverage
alestiago Oct 13, 2023
84b0858
exclude gen files
alestiago Oct 13, 2023
7a5d564
dart format .
alestiago Oct 13, 2023
03d9ff4
comment
alestiago Oct 13, 2023
e442433
changed if
alestiago Oct 13, 2023
0e34aa8
move _invalidLicenses
alestiago Oct 13, 2023
f05abe1
refactor logic
alestiago Oct 13, 2023
450eb19
docs
alestiago Oct 13, 2023
7003dd1
refactor _bannedDependencies
alestiago Oct 13, 2023
f4caa5e
update _bannedDependencies signature
alestiago Oct 13, 2023
4111679
refactor _bannedDependencies
alestiago Oct 13, 2023
868d5a2
refactor used typedef
alestiago Oct 13, 2023
cd7fc59
refactor used typedef
alestiago Oct 13, 2023
355dcc7
docs
alestiago Oct 13, 2023
dc7af03
docs
alestiago Oct 13, 2023
61dfad3
trailing comma
alestiago Oct 13, 2023
a9b222a
Merge remote-tracking branch 'origin' into alestiago/allowed-licenses
alestiago Oct 16, 2023
230d885
docs used initialized
alestiago Oct 16, 2023
879f831
test name
alestiago Oct 16, 2023
6722c74
mason make spdx_license
alestiago Oct 16, 2023
d4091e2
revert spdx_license.gen.dart
alestiago Oct 16, 2023
bd44f7d
remove sdk
alestiago Oct 16, 2023
c41ad0e
mason make spdx_license
alestiago Oct 16, 2023
2b4ff5d
revert change
alestiago Oct 16, 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
148 changes: 140 additions & 8 deletions lib/src/commands/packages/commands/check/commands/licenses.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,26 @@ 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';
import 'package:very_good_cli/src/pub_license/spdx_license.gen.dart';

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

/// The URI for the pub.dev license page for the given [packageName].
@visibleForTesting
Uri pubLicenseUri(String packageName) =>
Uri.parse('https://pub.dev/packages/$packageName/license');

/// Defines a [Map] with dependencies as keys and their licenses as values.
///
/// If a dependency's license failed to be retrieved its license will be `null`.
typedef _DependencyLicenseMap = Map<String, Set<String>?>;

/// Defines a [Map] with banned dependencies as keys and their banned licenses
/// as values.
typedef _BannedDependencyLicenseMap = Map<String, Set<String>>;

/// {@template packages_check_licenses_command}
/// `very_good packages check licenses` command for checking packages licenses.
/// {@endtemplate}
Expand Down Expand Up @@ -42,6 +57,10 @@ class PackagesCheckLicensesCommand extends Command<int> {
'transitive': 'Check for transitive dependencies.',
},
defaultsTo: ['direct-main'],
)
..addMultiOption(
'allowed',
help: 'Whitelist of allowed licenses.',
);
}

Expand Down Expand Up @@ -69,6 +88,14 @@ class PackagesCheckLicensesCommand extends Command<int> {

final ignoreFailures = _argResults['ignore-failures'] as bool;
final dependencyTypes = _argResults['dependency-type'] as List<String>;
final allowedLicenses = _argResults['allowed'] as List<String>;

final invalidLicenses = _invalidLicenses(allowedLicenses);
if (invalidLicenses.isNotEmpty) {
_logger.warn(
'''Some ${styleItalic.wrap('allowed')} licenses failed to be recognized: ${invalidLicenses.stringify()}. Refer to the documentation for a list of valid licenses.''',
);
}

final target = _argResults.rest.length == 1 ? _argResults.rest[0] : '.';
final targetPath = path.normalize(Directory(target).absolute.path);
Expand Down Expand Up @@ -114,7 +141,7 @@ class PackagesCheckLicensesCommand extends Command<int> {
final licenses = <String, Set<String>?>{};
for (final dependency in filteredDependencies) {
progress.update(
'Collecting licenses of ${licenses.length}/${filteredDependencies.length} packages',
'Collecting licenses of ${licenses.length}/${filteredDependencies.length} packages.',
);

final dependencyName = dependency.package();
Expand Down Expand Up @@ -145,7 +172,21 @@ class PackagesCheckLicensesCommand extends Command<int> {
}
}

progress.complete(_composeReport(licenses));
final bannedDependencies = allowedLicenses.isNotEmpty
? _bannedDependencies(licenses, allowedLicenses.contains)
: null;

progress.complete(
_composeReport(
licenses: licenses,
bannedDependencies: bannedDependencies,
),
);

if (bannedDependencies != null) {
_logger.err(_composeBannedReport(bannedDependencies));
return ExitCode.config.code;
}

return ExitCode.success.code;
}
Expand All @@ -163,28 +204,119 @@ PubspecLock? _tryParsePubspecLock(File pubspecLockFile) {
}
}

/// Verifies that all [licenses] are valid license inputs.
///
/// Valid license inputs are:
/// - [SpdxLicense] values.
///
/// Returns a [List] of invalid licenses, if all licenses are valid the list
/// will be empty.
List<String> _invalidLicenses(List<String> licenses) {
final invalidLicenses = <String>[];
for (final license in licenses) {
final parsedLicense = SpdxLicense.tryParse(license);
if (parsedLicense == null) {
invalidLicenses.add(license);
}
}

return invalidLicenses;
}

/// Returns a [Map] of banned dependencies and their banned licenses.
///
/// The [Map] is lazily initialized, if no dependencies are banned `null` is
/// returned.
_BannedDependencyLicenseMap? _bannedDependencies(
_DependencyLicenseMap licenses,
bool Function(String license) isAllowed,
) {
_BannedDependencyLicenseMap? bannedDependencies;
for (final dependency in licenses.entries) {
final name = dependency.key;
final license = dependency.value;
if (license == null) continue;

for (final licenseType in license) {
if (isAllowed(licenseType)) continue;

bannedDependencies ??= <String, Set<String>>{};
bannedDependencies.putIfAbsent(name, () => <String>{});
bannedDependencies[name]!.add(licenseType);
}
}

return bannedDependencies;
}

/// Composes a human friendly [String] to report the result of the retrieved
/// licenses.
String _composeReport(Map<String, Set<String>?> licenses) {
///
/// If [bannedDependencies] is provided those banned licenses will be
/// highlighted in red.
String _composeReport({
required _DependencyLicenseMap licenses,
required _BannedDependencyLicenseMap? bannedDependencies,
}) {
final bannedLicenseTypes =
bannedDependencies?.values.fold(<String>{}, (previousValue, licenses) {
if (licenses.isEmpty) return previousValue;
return previousValue..addAll(licenses);
});
final licenseTypes =
licenses.values.fold(<String>{}, (previousValue, element) {
if (element == null) return previousValue;
return previousValue..addAll(element);
licenses.values.fold(<String>{}, (previousValue, licenses) {
if (licenses == null) return previousValue;
return previousValue..addAll(licenses);
});
final coloredLicenseTypes = licenseTypes.map((license) {
if (bannedLicenseTypes != null && bannedLicenseTypes.contains(license)) {
return red.wrap(license)!;
}
return green.wrap(license)!;
});

final licenseCount = licenses.values.fold<int>(0, (previousValue, element) {
if (element == null) return previousValue;
return previousValue + element.length;
});

final licenseWord = licenseCount == 1 ? 'license' : 'licenses';
final packageWord = licenses.length == 1 ? 'package' : 'packages';
final suffix = licenseTypes.isEmpty
final suffix = coloredLicenseTypes.isEmpty
? ''
: ' of type: ${licenseTypes.toList().stringify()}';
: ' of type: ${coloredLicenseTypes.toList().stringify()}';

return '''Retrieved $licenseCount $licenseWord from ${licenses.length} $packageWord$suffix.''';
}

String _composeBannedReport(_BannedDependencyLicenseMap bannedDependencies) {
final bannedDependenciesList = bannedDependencies.entries.fold(
<String>[],
(previousValue, element) {
final dependencyName = element.key;
final dependencyLicenses = element.value;

final text = '$dependencyName (${link(
uri: pubLicenseUri(dependencyName),
message: dependencyLicenses.toList().stringify(),
)})';
return previousValue..add(text);
},
);
final bannedLicenseTypes =
bannedDependencies.values.fold(<String>{}, (previousValue, licenses) {
if (licenses.isEmpty) return previousValue;
return previousValue..addAll(licenses);
});

final prefix =
bannedDependencies.length == 1 ? 'dependency has' : 'dependencies have';
final suffix =
bannedLicenseTypes.length == 1 ? 'a banned license' : 'banned licenses';

return '''${bannedDependencies.length} $prefix $suffix: ${bannedDependenciesList.stringify()}.''';
}

extension on List<Object> {
String stringify() {
if (isEmpty) return '';
Expand Down
Loading