/** * Retorna um array com os detalhes de um usuário do GitHub de acordo com o Login * * @param string $usuarioLogin login do usuário no GitHub * @return array $usuarioDetalhes detalhes do perfil do usuário no GitHub */ public function exibeDetalhesPerfil($usuarioLogin) { $client = new \Github\Client(); $usuarioDetalhes = $client->api('user')->show($usuarioLogin); return $usuarioDetalhes; }
public function onStart(EnvironmentEvent $event) { $io = $event->getIO(); $configValues = $event->getConfigValues(); $io->write('Getting Github metadata...'); $repository = $this->getRepositoryComponents($configValues['repository']); if (2 != count($repository)) { $io->write('<error>Invalid repository name.</error>'); return; } $client = new \Github\Client(); $metadataRepo = $client->api('repo')->show($repository['vendor'], $repository['name']); $metadata = ['name' => $metadataRepo['name'], 'full_name' => $metadataRepo['full_name'], 'description' => $metadataRepo['description'], 'fork' => $metadataRepo['fork'], 'html_url' => $metadataRepo['html_url'], 'clone_url' => $metadataRepo['clone_url'], 'git_url' => $metadataRepo['git_url'], 'ssh_url' => $metadataRepo['ssh_url'], 'mirror_url' => $metadataRepo['mirror_url'], 'homepage' => $metadataRepo['homepage'], 'forks_count' => $metadataRepo['forks_count'], 'stargazers_count' => $metadataRepo['stargazers_count'], 'watchers_count' => $metadataRepo['watchers_count'], 'size' => $metadataRepo['size'], 'default_branch' => $metadataRepo['default_branch'], 'open_issues_count' => $metadataRepo['open_issues_count'], 'has_issues' => $metadataRepo['has_issues'], 'has_wiki' => $metadataRepo['has_wiki'], 'has_pages' => $metadataRepo['has_pages'], 'has_downloads' => $metadataRepo['has_downloads'], 'pushed_at' => $metadataRepo['pushed_at'], 'created_at' => $metadataRepo['created_at'], 'updated_at' => $metadataRepo['updated_at'], 'owner' => ['login' => $metadataRepo['owner']['login'], 'avatar_url' => $metadataRepo['owner']['avatar_url'], 'gravatar_id' => $metadataRepo['owner']['gravatar_id'], 'html_url' => $metadataRepo['owner']['html_url']], 'organization' => [], 'source' => [], 'contributors' => []]; if (isset($metadataRepo['organization'])) { $metadata['organization'] = ['login' => $metadataRepo['organization']['login'], 'avatar_url' => $metadataRepo['organization']['avatar_url'], 'html_url' => $metadataRepo['organization']['html_url']]; } if (isset($metadataRepo['source'])) { $metadata['source'] = ['name' => $metadataRepo['source']['name'], 'full_name' => $metadataRepo['source']['full_name'], 'description' => $metadataRepo['source']['description'], 'html_url' => $metadataRepo['source']['html_url'], 'clone_url' => $metadataRepo['source']['clone_url'], 'git_url' => $metadataRepo['source']['git_url'], 'ssh_url' => $metadataRepo['source']['ssh_url'], 'svn_url' => $metadataRepo['source']['svn_url'], 'mirror_url' => $metadataRepo['source']['mirror_url'], 'homepage' => $metadataRepo['source']['homepage'], 'forks_count' => $metadataRepo['source']['forks_count'], 'stargazers_count' => $metadataRepo['source']['stargazers_count'], 'watchers_count' => $metadataRepo['source']['watchers_count'], 'size' => $metadataRepo['source']['size'], 'default_branch' => $metadataRepo['source']['default_branch'], 'open_issues_count' => $metadataRepo['source']['open_issues_count'], 'has_issues' => $metadataRepo['source']['has_issues'], 'has_wiki' => $metadataRepo['source']['has_wiki'], 'has_pages' => $metadataRepo['source']['has_pages'], 'has_downloads' => $metadataRepo['source']['has_downloads'], 'pushed_at' => $metadataRepo['source']['pushed_at'], 'created_at' => $metadataRepo['source']['created_at'], 'updated_at' => $metadataRepo['source']['updated_at']]; } $contributors = $client->api('repo')->contributors($repository['vendor'], $repository['name']); foreach ($contributors as $contributor) { $metadata['contributors'][] = ['login' => $contributor['login'], 'avatar_url' => $contributor['avatar_url'], 'html_url' => $contributor['html_url'], 'type' => $contributor['type'], 'contributions' => $contributor['contributions']]; } $configValues['github'] = $metadata; $event->setConfigValues($configValues); }
protected function fetchExtensionPerBranch() { $path = 'ext'; $extensionsPerBranch = []; foreach ($this->branches as $name => $branch) { $fileInfo = $this->client->api('repo')->contents()->show('php', 'php-src', $path, $branch['commit']['sha']); $extensionsPerBranch[$name] = $this->getBundledExtensions($fileInfo); } return $extensionsPerBranch; }
/** * @param array $pull_request_data * @param string $reject_reason */ private function rejectPullRequest(array $pull_request_data, $reject_reason) { $client = new \Github\Client(); $params = array(); $params['state'] = 'closed'; $base = $pull_request_data['base']; $head = $pull_request_data['head']; $user = $head['user']; $repo = $base['repo']; $owner = $repo['owner']; $id = $pull_request_data['number']; if (!defined('GITHUB_API_OAUTH2TOKEN')) { throw new InvalidArgumentException(); } $client->authenticate(GITHUB_API_OAUTH2TOKEN, null, \Github\Client::AUTH_HTTP_TOKEN); $client->api('pull_request')->update($owner['login'], $repo['name'], $id, $params); $params = array(); $comment_body = ''; switch ($reject_reason) { case self::NON_MEMBER_REJECT_REASON: case self::NON_FOUNDATION_MEMBER_REJECT_REASON: $comment_body = sprintf('User %s is not an OpenStack Foundation Member. Please go to https://www.openstack.org/join/register/ and complete the registration form in order to become a Foundation Member. After that, please take a look at How to Contribute to Openstack (https://wiki.openstack.org/wiki/How_To_Contribute) and make sure you sign the Contributer License Agreement (http://docs.openstack.org/infra/manual/developers.html#account-setup).', $user['login']); break; case self::NON_SIGNED_CLA_REJECT_REASON: $comment_body = sprintf('User %s has not signed the Contributer License Agreement. Please take a look at How to Contribute to Openstack (https://wiki.openstack.org/wiki/How_To_Contribute) and make sure you sign the CLA (http://docs.openstack.org/infra/manual/developers.html#account-setup).', $user['login']); break; } $params['body'] = $comment_body; $client->api('issue')->comments()->create($owner['login'], $repo['name'], $id, $params); }
public function progress($offset, $limit) { $source = $this->connection->fetchAll("\n SELECT `id`, `name`\n FROM `s_names`\n WHERE `github_response_code` = 0\n LIMIT {$offset}, {$limit};\n "); $names = array_column($source, 'name', 'id'); $responseCodeIdMap = []; /* @var $api \Github\Api\User */ $client = new \Github\Client(); $client->authenticate($this->authToken, \Github\Client::AUTH_HTTP_PASSWORD); $api = $client->api('user'); foreach ($names as $id => $name) { try { $api->show($name); $code = 200; } catch (\Github\Exception\RuntimeException $e) { // "You have reached GitHub hour limit! Actual limit is: 5000" if (empty($code = $e->getCode())) { break; } } $responseCodeIdMap[$code][] = $id; } foreach ($responseCodeIdMap as $code => $idList) { $idStringList = join(',', $idList); $this->connection->executeUpdate("\n UPDATE `s_names`\n SET `github_response_code` = {$code}\n WHERE `id` IN ({$idStringList})\n "); } }
public function __construct() { //CodeReview --repo=clickbus-mexico --pr=24 --flags=clean-code,psr2 //CodeReview --repo=clickbus-mexico --branch=feature/LMX-788 --flags=clean-code,psr2 $client = new \Github\Client(); $repositories = $client->api('user')->repositories('ajaxman'); var_dump($repositories); echo "working..."; }
/** * @param Github\Client $client * @param Github\Api\Repo $repoApi * @param Github\Api\Repository\Commits $commitsApi */ function it_should_not_collect_merge_commits($client, $repoApi, $commitsApi) { $client->api('repos')->willReturn($repoApi); $repoApi->commits()->willReturn($commitsApi); $commitsApi->all('author1', 'repo1', Argument::type('array'))->shouldBeCalled()->willReturn($this->repo1Commits); $this->repo2Commits[0]['commit']['message'] = 'Merged something into something'; $commitsApi->all('author1', 'repo2', Argument::type('array'))->shouldBeCalled()->willReturn($this->repo2Commits); $this->collect(array('author1' => array('repo1', 'repo2')))->shouldReturn(array('john doe' => 1, 'jane doe' => 1)); }
public function showAction($slug) { $em = $this->getDoctrine()->getEntityManager(); $q = "SELECT p FROM DdnetPortfolioBundle:Project p WHERE p.slug = :slug"; $q = $em->createQuery($q)->setParameter('slug', $slug); $r = $q->getSingleResult(); $gh = new \Github\Client(); $commits = $gh->api('repo')->commits()->all($r->getGithubUser(), $r->getGithubRepo(), array('sha' => $r->getGithubBranch())); return $this->render('DdnetPortfolioBundle:Project:show.html.twig', array('portfolio' => $r, 'commits' => $commits)); }
/** * Obtain the user information from GitHub. * * @return Response */ public function callback(Request $request) { $user = Socialite::with('github')->user(); // TODO: Nice error page $request->session()->set('github', ['token' => $user->token, 'id' => $user->getId(), 'nickname' => $user->getNickname(), 'name' => $user->getName(), 'email' => $user->getEmail(), 'avatar' => $user->getAvatar()]); $client = new \Github\Client(); $client->authenticate($user->token, false, \Github\Client::AUTH_HTTP_TOKEN); //$repos = $client->api('user')->repositories($user->getNickname()); // Get this users repos $content = $client->api('repo')->contents()->show('ashleyhindle', 'fodor-example', 'fodor.json', 'master'); dd(base64_decode($content['content'])); }
public function sendScreenshot($cloudName, $apiKey, $apiSecret, $authToken) { $this->say('Sending image'); // Upload image Cloudinary::config(array('cloud_name' => $cloudName, 'api_key' => $apiKey, 'api_secret' => $apiSecret)); $result = \Cloudinary\Uploader::upload(realpath(dirname(__FILE__) . '/tests/_output/InstallNenoCest.installNeno.fail.png')); $this->say('Image sent'); $this->say('Creating Github issue'); $client = new \Github\Client(); $client->authenticate($authToken, \Github\Client::AUTH_HTTP_TOKEN); $client->api('issue')->create('Jensen-Technologies', 'neno', array('title' => 'Test error', 'body' => '![Screenshot](' . $result['secure_url'] . ')')); }
/** * Constructor * * @param string $contextRepo The repository context. Pass a GitHub repo * such as 'aptoma/twig-markdown' to render e.g. issues #23 in the * context of the repo. * @param bool $gfm Whether to use GitHub's Flavored Markdown or the * standard markdown. Default is true. * @param string $cacheDir Location on disk where rendered documents should * be stored. * @param \Github\Client $client Client object to use. A new Github\Client() * object is constructed automatically if $client is null. */ public function __construct($contextRepo = null, $gfm = true, $cacheDir = '/tmp/github-markdown-cache', \GitHub\Client $client = null) { $this->repo = $contextRepo; $this->mode = $gfm ? 'gfm' : 'markdown'; $this->cacheDir = rtrim($cacheDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; if (!is_dir($this->cacheDir)) { @mkdir($this->cacheDir, 0777, true); } if ($client === null) { $client = new \Github\Client(); } $this->api = $client->api('markdown'); }
protected function installPoshGit(InputInterface $in, OutputInterface $out) { $dir = realpath(__DIR__ . '/../runtime') . '/posh-git-sh'; if (!is_dir($dir)) { mkdir($dir); $client = new \Github\Client(); /** @var Repo $repo */ $repo = $client->api('repo'); /** @var string $data The binary tar data. */ $data = $repo->contents()->archive('lyze', 'posh-git-sh', 'tarball'); $proc = proc_open("tar xvz --strip 1 -C {$dir}", [['pipe', 'r']], $pipes); fwrite($pipes[0], $data); } }
/** * @param Package $package * * @return Package */ public function analyzePackage(Package $package) { $client = new GuzzleClient(); $response = $client->get($this->packageVendor . $package->getName(), array('exceptions' => false)); if ($response->getStatusCode() == 200) { $data = $this->parseJson((string) $response->getBody()); // TODO: Handle this differently $urlChunks = explode("/", $data['url']); $githubClient = new \Github\Client(); $tags = $githubClient->api('repo')->tags($urlChunks[3], substr($urlChunks[4], 0, -4)); $newestVersion = $this->getLatestVersion(array_column($tags, 'name')); $package->setLatestVersion($newestVersion); $package->setLastChecktAt(new \DateTime()); } return $package; }
public function actionCommits() { $http_client = new \Guzzle\Http\Client(); $client = new \Github\Client(); try { $commits = $client->api('repo')->commits()->all('KnpLabs', 'php-github-api', array('sha' => 'master')); foreach ($commits as $commit_info) { $commit_info = json_decode($http_client->get($commit_info['url'])->send()->getBody(), true); $commit = Commits::findOne(['sha' => $commit_info['sha']]); if (!$commit) { $commit = new Commits(); $commit->sha = $commit_info['sha']; $commit->user_name = $commit_info['commit']['committer']['name']; $commit->date_commit = date('Y-m-d', strtotime($commit_info['commit']['committer']['date'])); $commit->message = $commit_info['commit']['message']; $commit->save(); } echo $commit->id . PHP_EOL; foreach ($commit_info['files'] as $file_info) { $commit_file = CommitsFiles::findOne(['sha' => $file_info['sha']]); if (!$commit_file) { $commit_file = new CommitsFiles(); $commit_file->sha = $file_info['sha']; $commit_file->commit_id = $commit->id; $commit_file->filename = $file_info['filename']; $commit_file->status = $file_info['status']; $commit_file->additions = $file_info['additions']; $commit_file->deletions = $file_info['deletions']; $commit_file->changes = $file_info['changes']; $commit_file->blob_url = $file_info['blob_url']; $commit_file->date_add = $commit->date_commit; if (!$commit_file->save()) { print_r($commit_file->getErrors()); die; } } echo '--' . $commit_file->id . PHP_EOL; } } } catch (\Exception $e) { } }
public function actionTeam() { $members = Yii::$app->params['members']; $activeMembers = []; $pastMembers = []; foreach ($members as $member) { if ($member['active']) { $activeMembers[] = $member; } else { $pastMembers[] = $member; } } $activeMembers = RowHelper::split($activeMembers, 3); $pastMembers = RowHelper::split($pastMembers, 3); $contributorLimit = 1000; // getting contributors from github try { $cacheKey = __CLASS__ . ":team:contributors:{$contributorLimit}"; if (($contributors = Yii::$app->cache->get($cacheKey)) === false) { $client = new \Github\Client(); $api = $client->api('repo'); $paginator = new \Github\ResultPager($client); $parameters = ['yiisoft', 'yii2']; $contributors = $paginator->fetch($api, 'contributors', $parameters); while ($paginator->hasNext() && count($contributors) < $contributorLimit) { $contributors = array_merge($contributors, $paginator->fetchNext()); } // remove team members $teamGithubs = array_filter(array_map(function ($member) { return isset($member['github']) ? $member['github'] : false; }, $members)); foreach ($contributors as $key => $contributor) { if (in_array($contributor['login'], $teamGithubs)) { unset($contributors[$key]); } } $contributors = array_slice($contributors, 0, $contributorLimit); Yii::$app->cache->set($cacheKey, $contributors, 3600 * 12); // cache for 12hours } } catch (\Exception $e) { $contributors = false; } return $this->render('team', ['activeMembers' => $activeMembers, 'pastMembers' => $pastMembers, 'contributors' => $contributors]); }
} $authentication = json_decode(file_get_contents('credentials.json')); $client->authenticate($authentication->apikey, Github\Client::AUTH_URL_TOKEN); $paginator = new Github\ResultPager($client); $config = json_decode(file_get_contents('config.json')); $repositories = []; $updateDueDate = []; $SHOW_MILESTONE = true; $SHOW_LABEL = true; foreach ($config->repos as $repo) { $repositories[$repo] = ['milestones' => [], 'labels' => []]; print 'Repo ' . $config->org . '/' . $repo . PHP_EOL; if ($SHOW_MILESTONE) { print " Milestones" . PHP_EOL; } $milestones = $client->api('issue')->milestones()->all($config->org, $repo); uasort($milestones, 'milestoneSort'); foreach ($milestones as $milestone) { $repositories[$repo]['milestones'][$milestone['title']] = $milestone; if ($SHOW_MILESTONE) { print " "; } if ($milestone['open_issues'] !== 0) { if ($SHOW_MILESTONE) { print $milestone['title'] . ' ' . $milestone['open_issues']; } } else { if ($SHOW_MILESTONE) { print $COLOR_GRAY . $milestone['title']; } }
<?php require_once 'vendor/autoload.php'; $client = new \Github\Client(); $contributors = $client->api('repo')->contributors('php-br-org', 'php-br'); print_r($contributors);
exit; try { $conn = new PDO("mysql:host={$servername};dbname={$dbname}", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // sql to create table $sql = "select * from webid where login = '******' ; "; $stmt = $conn->prepare($sql); $stmt->execute(); $webid = $stmt->fetch(); } catch (PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } //print_r($row); if (!$user) { $user = $client->api('user')->show($nick); try { $conn = new PDO("mysql:host={$servername};dbname={$dbname}", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // sql to create table $sql = "insert into users values (NULL, '{$nick}', '{$user['name']}', '{$user['email']}', '{$user['company']}', '{$user['location']}', '{$user['avatar_url']}', '{$user['blog']}', NULL) ; "; $stmt = $conn->prepare($sql); $stmt->execute(); } catch (PDOException $e) { echo $sql . " - " . $e->getMessage(); } } else { } $users = $client->api('user')->followers($nick); //echo "<h3>Profile</h3>";
public function getMeta() { if (!$this->repositoryMeta) { $client = new \Github\Client(); $meta = $client->api('repo')->show($this->gitHubVendorName, $this->gitHubRepositoryName); $this->repositoryMeta = $meta; } }
if ($merge) { freepbx::outn("Attempting to merge release/" . $options['updatemaster'] . " into master..."); $repo->checkout("master"); $merged = $repo->pull("origin", "release/" . $options['updatemaster']); if (!$merged) { freepbx::out("\t\t\tMerge from release/" . $options['updatemaster'] . " into master failed"); freepbx::out("Module " . $module . " will not be tagged!"); continue; } $repo->push("origin", "master"); freepbx::out("Done"); freepbx::outn("Checking you out into release/" . $options['updatemaster'] . "..."); $repo->checkout("release/" . $options['updatemaster']); freepbx::out("Done"); } $organizationApi = $client->api('organization'); $paginator = new Github\ResultPager($client); $parameters = array('freepbx'); $repos = $paginator->fetchAll($organizationApi, 'repositories', $parameters); $core = array(); foreach ($repos as $repo) { $core[] = $repo['name']; } $paginator = new Github\ResultPager($client); $parameters = array('FreePBX-ContributedModules'); $repos = $paginator->fetchAll($organizationApi, 'repositories', $parameters); $contrib = array(); foreach ($repos as $repo) { $contrib[] = $repo['name']; } if (in_array($rawname, $core)) {
echo 'Status:', $issue->getStatus()->getName(), "\n"; echo 'Responsável: ', $issue->getAssignee()->getDisplayName(), "\n"; echo 'Prioridade:', $issue->getPriority()->getName(), "\n"; echo 'Criado em :', $issue->getCreated()->format('d/m/Y H:i:s'), "\n"; echo 'Última atualização em :', $issue->getUpdated()->format('d/m/Y H:i:s'), "\n"; if (getWeekdayDifference($issue->getUpdated(), $now) >= 2) { echo "URGENTE: esta tarefa precisa ser quebrada e entregue hoje. Nenhuma tarefa pode ficar mais de 2 dias parada", "\n"; } echo "\n\n"; } $client = new \Github\Client(new \Github\HttpClient\CachedHttpClient(array('cache_dir' => '/tmp/github-api-cache'))); $githubUser = getenv('GITHUB_USER'); $githubPassword = getenv('GITHUB_PASSWORD'); $githubRepo = getenv('GITHUB_REPO'); $client->authenticate($githubUser, $githubPassword, \Github\Client::AUTH_HTTP_PASSWORD); $activity = $client->api('repo')->statistics($githubUser, $githubRepo); echo "Commits \n\n"; foreach ($activity as $a) { $lastWeek = count($a['weeks']) - 1; if ($a['weeks'][$lastWeek]['c'] > 0) { echo $a['author']['login'], " Total de commits: ", $a['total'], '. Commits na última semana (começando em ' . DateTime::createFromFormat('U', $a['weeks'][$lastWeek]['w'])->format('d/m/Y') . ' ):' . $a['weeks'][$lastWeek]['c'], "\n"; } } echo "\n\nOBS: se o nome de alguém não aparece acima não significa que ela não está trabalhando e sim que está commitando em branches diferentes da master pois o Github só entrega estatísticas desta branch. A ausência de alguém na lista acima indica que a sua tarefa está demorando mais de dois dias para terminar e ser aprovada no master o que reforça a necessidade de quebrar a tarefa em pedaços menores.\n"; function getWeekdayDifference(\DateTime $startDate, \DateTime $endDate) { $days = 0; while ($startDate->diff($endDate)->days > 0) { $days += $startDate->format('N') < 6 ? 1 : 0; $startDate = $startDate->add(new \DateInterval("P1D")); }
$data = 'client_id=' . 'd12c2803a9453ba44900' . '&' . 'client_secret=' . '76a1c2f9c3d9229af028ee6b890e1c21de8cb926' . '&' . 'code=' . urlencode($_GET['code']); $ch = curl_init('https://github.com/login/oauth/access_token'); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); preg_match('/access_token=([0-9a-f]+)/', $response, $out); curl_close($ch); if ($out[1]) { $fgmembersite->insertToken($out[1]); } } $token = $fgmembersite->getusertoken(); if ($token != NULL) { $client = new Github\Client(); $client->authenticate($token, $password = NULL, Github\Client::AUTH_HTTP_TOKEN); $general_info = $client->api('current_user')->show(); $fggitclass->cleanRepos(); $fggitclass->cloneRepos(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>EasyDoc</title> <link rel="stylesheet" href="css/layout.css" type="text/css" media="screen" /> <!--[if lt IE 9]> <link rel="stylesheet" href="css/ie.css" type="text/css" media="screen" /> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]-->
/** * Generates contributor data and avatars * @return success or fail */ public function actionGenerate() { if (!$this->acquireMutex()) { $this->stderr("Execution terminated: command is already running.\n", Console::FG_RED); return self::EXIT_CODE_ERROR; } $members = Yii::$app->params['members']; $contributors = array(); $raw_contributors = array(); $contributorLimit = 1000; // getting contributors from github try { $client = new \Github\Client(); $token_file = Yii::getAlias('@app/data') . '/github.token'; if (file_exists($token_file)) { $this->stdout("Authenticating with Github token.\n"); $token = file_get_contents($token_file); $client->authenticate($token, null, \Github\Client::AUTH_URL_TOKEN); } $api = $client->api('repo'); $paginator = new \Github\ResultPager($client); $parameters = ['yiisoft', 'yii2']; $raw_contributors = $paginator->fetch($api, 'contributors', $parameters); while ($paginator->hasNext() && count($raw_contributors) < $contributorLimit) { $raw_contributors = array_merge($raw_contributors, $paginator->fetchNext()); } // remove team members $teamGithubs = array_filter(array_map(function ($member) { return isset($member['github']) ? $member['github'] : false; }, $members)); foreach ($raw_contributors as $key => $raw_contributor) { if (in_array($raw_contributor['login'], $teamGithubs)) { unset($raw_contributors[$key]); } } $raw_contributors = array_slice($raw_contributors, 0, $contributorLimit); } catch (\Exception $e) { $raw_contributors = false; } if ($raw_contributors) { foreach ($raw_contributors as $raw_contributor) { $contributor = array(); $contributor['login'] = $raw_contributor['login']; $contributor['avatar_url'] = $raw_contributor['avatar_url']; $contributor['html_url'] = $raw_contributor['html_url']; $contributor['contributions'] = $raw_contributor['contributions']; $contributors[] = $contributor; } } // save 'contributors.json' in the data directory $data_dir = Yii::getAlias('@app/data'); file_put_contents($data_dir . DIRECTORY_SEPARATOR . 'contributors.json', json_encode($contributors, JSON_PRETTY_PRINT)); // Generate avatar thumbnails and store them in data/avatars $thumbnail_dir = $data_dir . DIRECTORY_SEPARATOR . 'avatars'; if (!is_dir($thumbnail_dir)) { FileHelper::createDirectory($thumbnail_dir); } $imagine = new Imagine(); $mode = ImageInterface::THUMBNAIL_OUTBOUND; $size = new \Imagine\Image\Box(48, 48); foreach ($contributors as $contributor) { $login = $contributor['login']; // Check if the file exists and there are no errors $headers = get_headers($contributor['avatar_url'], 1); $code = isset($headers[1]) ? explode(' ', $headers[1]) : explode(' ', $headers[0]); $code = next($code); if ($code != 404 and $code != 403 and $code != 400 and $code != 500) { // the image url seems to be good, save the thumbnail $this->stdout("Saving {$login}.png\n"); $imagine->open($contributor['avatar_url'])->thumbnail($size, $mode)->save($thumbnail_dir . DIRECTORY_SEPARATOR . $login . '.png'); } else { //TODO: default avatar thumbnail? $this->stdout("Avatar {$login}.png was not found\n"); } } if (YII_ENV_DEV) { exec('gulp sprites && gulp styles', $output, $ret); } else { exec('gulp sprites && gulp styles --production', $output, $ret); } $this->releaseMutex(); return self::EXIT_CODE_NORMAL; }
public function add($to, $message, $options = []) { extract($options); $news = !empty($news); $project = !empty($project); $issue = !empty($issue); $language = !empty($language) ? $language : false; if ($language) { if (!in_array($language, System::getAvailableLanguages())) { return 'error: INVALID_LANGUAGE'; } } else { $language = $this->user->getLanguage(); } $table = ($project ? 'groups_' : '') . 'posts'; $retStr = Db::query(['INSERT INTO "' . $table . '" ("from","to","message","news","lang") VALUES (:id,:to,:message, :news, :language)', [':id' => $_SESSION['id'], ':to' => $to, ':message' => Comments::parseQuote(htmlspecialchars($message, ENT_QUOTES, 'UTF-8')), ':news' => $news ? 'true' : 'false', ':language' => $language]], Db::FETCH_ERRSTR); if ($retStr != Db::NO_ERRSTR) { return $retStr; } if ($project && $issue && $to == Config\ISSUE_BOARD) { require_once __DIR__ . '/vendor/autoload.php'; $client = new \Github\Client(); $client->authenticate(Config\ISSUE_GIT_KEY, null, \Github\client::AUTH_URL_TOKEN); $message = static::stripTags($message); try { $client->api('issue')->create('nerdzeu', 'nerdz.eu', ['title' => substr($message, 0, 128), 'body' => User::getUsername() . ': ' . $message]); } catch (\Github\Exception\RuntimeException $exception) { System::dumpError('GitHub API: ' . $exception->getMessage()); System::dumpError('GitHub API: ' . $exception->getPrevious()); } } return $retStr; }
/** * @param Github\Client $github * @param Packagist\Api\Client $packagist * @param Github\Api\Organization $organization * @param Github\Api\Repo $repo */ function let($github, $packagist, $organization, $repo) { $github->api('organization')->willReturn($organization); $github->api('repo')->willReturn($repo); $this->beConstructedWith('Sylius', $github, $packagist); }
<?php //require_once 'sessionStart.php'; // This file is generated by Composer error_reporting(E_ALL); ini_set('display_errors', 'on'); require_once 'vendor/autoload.php'; $client = new \Github\Client(); $repositories = $client->api('user')->repositories('ornicar');
foreach ($client->api('repo')->hooks()->all($session->getUsername(), $args['repository']) as $hook) { if ($hook['name'] == 'web' && strpos($hook['config']['url'], 'redports.org') !== false) { $client->api('repo')->hooks()->remove($session->getUsername(), $args['repository'], $hook['id']); } } $webhook = $client->api('repo')->hooks()->create($session->getUsername(), $args['repository'], array('name' => 'web', 'active' => true, 'events' => array('push'), 'config' => array('url' => 'https://api.redports.org/github/', 'content_type' => 'json'))); } catch (\Github\Exception\RuntimeException $e) { return $response->withStatus(500)->write($e->getMessage()); } /* TODO: register repository at master */ return $response->withRedirect('/repositories'); }); /* GitHub repository uninstall */ $app->get('/repositories/{repository}/uninstall', function ($request, $response, $args) use($session) { if (!$session->getUsername()) { return $response->withStatus(403)->write('Not authenticated'); } $client = new \Github\Client(); $client->authenticate($_SESSION['token'], null, \Github\Client::AUTH_HTTP_TOKEN); try { foreach ($client->api('repo')->hooks()->all($session->getUsername(), $args['repository']) as $hook) { if ($hook['name'] == 'web' && strpos($hook['config']['url'], 'redports.org') !== false) { $client->api('repo')->hooks()->remove($session->getUsername(), $args['repository'], $hook['id']); } } } catch (\Github\Exception\RuntimeException $e) { return $response->withStatus(500)->write($e->getMessage()); } return $response->withRedirect('/repositories'); }); $app->run();
protected function github_single($sha) { $client = new \Github\Client(new \Github\HttpClient\CachedHttpClient(array('cache_dir' => '/tmp/github-api-cache'))); $client = new \Github\HttpClient\CachedHttpClient(); $client->setCache(new \Github\HttpClient\Cache\FilesystemCache('/tmp/github-api-cache')); $client = new \Github\Client($client); $result = $commit = $client->api('repo')->commits()->show('shihjay2', 'nosh-core', $sha); return $result; }
#!/usr/bin/php <?php $config = ['require_services' => ['guzzle3'], 'git_urls' => ['https://github.com/KnpLabs/php-github-api.git' => 'php_github_api/'], 'autoload_config' => ['php_github_api/lib/Github/' => 'Github'], 'example' => function () { $client = new \Github\Client(); $repositories = $client->api('user')->repositories('yfix'); foreach ($repositories as $v) { $a[$v['full_name']] = $v['html_url']; } print_r($a); }]; if ($return_config) { return $config; } require_once __DIR__ . '/_yf_autoloader.php'; new yf_autoloader($config);
} if (!$githubToken) { echo "Github token is not set\n"; exit(1); } $dependenciesNames = getDependenciesNames($composerJsonPath); $packagistClient = new Packagist\Api\Client(); $githubRepositories = array(); foreach ($dependenciesNames as $packageName) { try { $githubRepository = getGithubRepository($packagistClient, $packageName); } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) { if (strpos($e->getMessage(), '[reason phrase] Not Found') === false) { throw $e; } } if (!$githubRepository) { echo "Github repository for package {$packageName} is not found\n"; continue; } $githubRepositories[] = $githubRepository; } if (empty($githubRepositories)) { exit; } $client = new \Github\Client(); $client->authenticate($githubToken, '', Github\Client::AUTH_URL_TOKEN); foreach ($githubRepositories as $githubRepository) { $client->api('current_user')->starring()->star($githubRepository['author'], $githubRepository['name']); echo $githubRepository['url'] . "\n"; }