Skip to content

Instantly share code, notes, and snippets.

@DanielHudson
Last active November 27, 2017 13:21
Show Gist options
  • Save DanielHudson/a99dc237f1390e4e66318ace1317e8a5 to your computer and use it in GitHub Desktop.
Save DanielHudson/a99dc237f1390e4e66318ace1317e8a5 to your computer and use it in GitHub Desktop.
Fetch GH issues, Laravel Console
<?php
namespace TGS\Console\Commands;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Storage;
class GitHubIssues extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'tgs:github-issues {owner} {repo} {user}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Lists GitHub issue titles and created date.';
/**
* Track page number.
* @var int
*/
protected $page = 1;
/**
* Results per page.
* @var int
*/
protected $per_page = 100;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$password = $this->secret(
sprintf('Github password for %s:', $this->argument('username'))
);
$issues = $this->fetchAll(
$this->argument('owner'),
$this->argument('repo'),
$this->argument('user'),
$password
);
$file = sprintf(
'%s-%s-issues.txt',
$this->argument('owner'),
$this->argument('repo')
);
Storage::disk('local')->put(
$file,
$issues->reduce(function ($carry, $issue) {
$message = $this->getOneliner($issue);
$this->info($message);
return $carry .= sprintf("%s\n", $message);
}, sprintf("## %s\n\n", $this->argument('repo')))
);
$this->info(sprintf('Output written to %s', $file));
$this->info('Done...');
}
private function fetchAll($owner, $repo, $user, $password)
{
$all = collect();
while (true) {
$this->info(sprintf('Fetching page %s...', $this->page));
$issues = $this->fetch($owner, $repo, $user, $password);
$all = $all->merge($issues);
if ($issues->count() < $this->per_page) {
break;
}
$this->page++;
}
return $all;
}
private function fetch($owner, $repo, $user, $password)
{
$client = new Client();
$response = $client->get(
sprintf(
'https://api.github.com/repos/%s/%s/issues?state=all&sort=created&page=%s&per_page=%s',
$owner,
$repo,
$this->page,
$this->per_page
),
[
'auth' => [
$user,
$password,
]
]
);
if ($response->getStatusCode() != 200) {
return false;
}
return collect(json_decode($response->getBody()));
}
private function getOneliner($issue)
{
$created_at = new Carbon($issue->created_at);
return sprintf(
'- %s/%s #%s %s by %s [%s with %s comments.]',
$created_at->format('m'),
$created_at->format('y'),
$issue->number,
$issue->title,
$issue->user->login,
ucfirst($issue->state),
ucfirst($issue->comments)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment