Skip to content

Instantly share code, notes, and snippets.

@Spomky
Created April 17, 2024 12:52
Show Gist options
  • Save Spomky/a93cfa4d5373f865c2435bd9b0606522 to your computer and use it in GitHub Desktop.
Save Spomky/a93cfa4d5373f865c2435bd9b0606522 to your computer and use it in GitHub Desktop.
Castor function to check licenses used on the project
<?php
declare(strict_types=1);
use Castor\Attribute\AsOption;
use Castor\Attribute\AsTask;
use function Castor\io;
use function Castor\run;
/**
* @param array<string> $allowedLicenses
*/
#[AsTask(description: 'Check licenses')]
function checkLicenses(
#[AsOption(description: 'Allowed licenses.')]
array $allowedLicenses = ['Apache-2.0', 'BSD-2-Clause', 'BSD-3-Clause', 'ISC', 'MIT', 'MPL-2.0', 'OSL-3.0']
): void {
io()->title('Checking licenses');
$command = ['composer', 'licenses', '-f', 'json'];
$environment = [
'XDEBUG_MODE' => 'off',
];
$result = run($command, environment: $environment, quiet: true);
if (! $result->isSuccessful()) {
io()->error('Cannot determine licenses');
exit(1);
}
$licenses = json_decode($result->getOutput(), true);
$disallowed = array_filter(
$licenses['dependencies'],
static fn (array $info, $name) => count(array_diff($info['license'], $allowedLicenses)) === 1,
\ARRAY_FILTER_USE_BOTH
);
$allowed = array_filter(
$licenses['dependencies'],
static fn (array $info, $name) => count(array_diff($info['license'], $allowedLicenses)) === 0,
\ARRAY_FILTER_USE_BOTH
);
if (count($disallowed) > 0) {
io()
->table(
['Package', 'License'],
array_map(
static fn ($name, $info) => [$name, implode(', ', $info['license'])],
array_keys($disallowed),
$disallowed
)
);
io()
->error('Disallowed licenses found');
exit(1);
}
io()
->table(
['Package', 'License'],
array_map(
static fn ($name, $info) => [$name, implode(', ', $info['license'])],
array_keys($allowed),
$allowed
)
);
io()
->success('All licenses are allowed');
}
@damienalexandre
Copy link

Awesome 👍 Thanks a lot for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment