Skip to content

Instantly share code, notes, and snippets.

@woganmay
Last active August 6, 2024 22:30
Show Gist options
  • Save woganmay/c619e3fbcc5a51b18fe46239169574b9 to your computer and use it in GitHub Desktop.
Save woganmay/c619e3fbcc5a51b18fe46239169574b9 to your computer and use it in GitHub Desktop.
A Laravel Artisan command for scanning your package-lock.json and composer.lock files to determine all the people and orgs that contributed to the packages you're using. Produces an open-source.json file with the names and contact info.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class ResolveOpenSourceAuthors extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:resolve-open-source-authors';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Refresh the open source contributors based on dependencies';
/**
* Execute the console command.
*/
public function handle()
{
$handle = fopen("php://temp", "w+");
$this->info("Resolving NPM packages...");
$this->resolvePackageJson($handle);
$this->info("Resolving Composer packages...");
$this->resolveComposerJson($handle);
// Now we merge these into a giant Authors array
rewind($handle);
$authors = [];
while($row = fgetcsv($handle))
{
if (!array_key_exists($row[0], $authors)) {
$authors[$row[0]] = [
'weight' => 0,
];
}
$authors[$row[0]]['email'] = $row[1];
$authors[$row[0]]['url'] = $row[2];
$authors[$row[0]]['weight']++;
}
fclose($handle);
file_put_contents(json_encode($authors, JSON_PRETTY_PRINT), base_path('open-source.json'));
$this->info("Authors written to " . base_path('open-source.json'));
}
private function resolvePackageJson($handle) : void {
$json = json_decode(file_get_contents(base_path('package-lock.json')));
foreach($json->packages as $name => $values) {
if ($name == "") continue;
$packageUrl = substr($values->resolved, 0, strrpos($values->resolved, '/-/'));
$registry = file_get_contents($packageUrl);
$object = json_decode($registry);
fputcsv($handle, [
$object->author->name ?? null,
$object->author->email ?? null,
$object->author->url ?? null,
]);
if (property_exists($object, 'maintainers')) {
foreach($object->maintainers as $maintainer) {
fputcsv($handle, [
$maintainer->name ?? null,
$maintainer->email ?? null,
$maintainer->url ?? null,
]);
}
}
echo ".";
}
echo "\n";
}
private function resolveComposerJson($handle) : void {
$lockFile = json_decode(file_get_contents(base_path('composer.lock')), true);
foreach ($lockFile['packages'] as $package) {
if (array_key_exists('authors', $package)) {
foreach($package['authors'] as $author) {
fputcsv($handle, [
$author['name'] ?? null,
$author['email'] ?? null,
$author['homepage'] ?? null,
]);
echo ".";
}
}
}
echo "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment