public function getContributors($link = null) { $api = $this->client->api('repo'); $paginator = new ResultPager($this->client); $parameters = [$this->config['contributors']['user'], $this->config['contributors']['repository']]; return ['contributors' => $paginator->fetch($api, 'contributors', $parameters), 'links' => $paginator->getPagination()]; }
public function showPage() { if (isset($_POST["register-data"]) && isset($_POST["register-password"])) { try { $client = new Client(); $client->authenticate($_POST["register-data"], Client::AUTH_HTTP_TOKEN); $user = $client->api('current_user')->show(); $repos = []; foreach ($client->api('current_user')->repositories('member', 'updated', 'desc') as $repo) { $repos[] = ["name" => $repo["full_name"], "isPrivate" => $repo["private"]]; } if (strlen($_POST["register-password"]) >= 6) { Users::createUser($user["login"], $client->api('current_user')->emails()->all()[0], $_POST["register-password"], $_POST["register-data"], $repos); Channels::addChannels($repos); echo $this->getTemplateEngine()->render($this->getTemplateSnip("page"), ["title" => "Register", "content" => $this->getTemplateEngine()->render($this->getTemplate(), ["user" => $user])]); } else { echo $this->getTemplateEngine()->render($this->getTemplateSnip("page"), ["title" => "Register", "content" => $this->getTemplateEngine()->render($this->getTemplate(), ["error" => "Passwords must be at least 6 characters long."])]); } } catch (\Exception $e) { echo $this->getTemplateEngine()->render($this->getTemplateSnip("page"), ["title" => "Register", "content" => $this->getTemplateEngine()->render($this->getTemplate(), ["error" => "Oh no! Your registration couldn't be completed. Do you already have an account? Is your token valid?"])]); } } else { echo $this->getTemplateEngine()->render($this->getTemplateSnip("page"), ["title" => "Register", "content" => $this->getTemplateEngine()->render($this->getTemplate(), [])]); } //echo $this->getTemplateEngine()->render($this->getTemplate(), []); }
public function build($username, $repository) { $this->repository = new Repository($username, $repository); // repository data $data = $this->client->api('repo')->show($this->repository->username, $this->repository->repository); $this->repository->size = $data['size']; $this->repository->stargazersCount = $data['stargazers_count']; $this->repository->forks = $data['forks']; $this->repository->openIssues = $data['open_issues']; $this->repository->subscribersCount = $data['subscribers_count']; // repository commit activity do { $activity = $this->client->api('repo')->activity($this->repository->username, $this->repository->repository); $responseStatusCode = $this->client->getHttpClient()->getLastResponse()->getStatusCode(); if ($responseStatusCode != 200) { sleep(3); } else { break; } } while (true); $commitsLastYear = array_map(function (array $weekCommits) { return $weekCommits['total']; }, $activity); $this->repository->commitsCount = array_sum($commitsLastYear); $this->repository->commitsLastMonthCount = array_sum(array_slice($commitsLastYear, -4)); $this->repository->avgCommitsPerWeek = count($commitsLastYear) > 0 ? floor(array_sum($commitsLastYear) / count($commitsLastYear)) : 0; // repository contributors $paginator = new ResultPager($this->client); $contributors = $paginator->fetchAll($this->client->api('repo'), 'contributors', [$this->repository->username, $this->repository->repository, true]); $this->repository->contributorsCount = count($contributors); // user data $user = $this->client->api('user')->show($this->repository->username); $this->repository->userPublicRepos = $user['public_repos']; return $this; }
/** * Finds the repositories * * @return array */ public function find() { /** @var Repo $repositoryApi */ $repositoryApi = $this->github->api('repo'); $repositories = $this->fetchRepositoryApi($repositoryApi, $this->query); $forkedRepositories = $this->fetchRepositoryApi($repositoryApi, $this->forkedRepoQuery); return array_merge($repositories, $forkedRepositories); }
/** * @param $gistId * @return array * @throws GistNotFoundException */ public function getGist($gistId) { try { return $this->github->api('gists')->show($gistId); } catch (Exception $e) { throw new GistNotFoundException($gistId, $e->getMessage()); } }
/** * @param Package $package * * @return \Guzzle\Http\EntityBodyInterface|mixed|string */ public function execute(Package $package) { /** @var Repo $githubRepository */ $githubRepository = $this->client->api('repo'); $fork = $githubRepository->forks()->create($package->getUsername(), $package->getRepoName()); $this->dispatchEvent(StepsEvents::REPOSITORY_FORKED, new RepositoryForkedEvent($fork)); return $fork; }
/** * Analyse Pull Request * * @param string $repositoryOwner * @param string $repositoryName * @param integer $pullRequestID * @return array */ public function analysePR($repositoryOwner, $repositoryName, $pullRequestID) { $commits = $this->githubClient->api('pull_request')->commits($repositoryOwner, $repositoryName, $pullRequestID); if (!$commits) { throw new Exception('Cannot fetch Pull Request data'); } $commitsAnalysisResults = $this->commitReader->analyseCommits($commits); return $commitsAnalysisResults; }
/** * Get the file contents * * @param string $file * @param string $branch * * @return string */ public function getFileContents($file, $branch = 'master') { try { $fileContent = $this->client->api('repo')->contents()->download($this->project->getVendorName(), $this->project->getPackageName(), $file, $branch); return $this->parseJson($fileContent); } catch (\Github\Exception\RuntimeException $e) { return ""; } }
/** * {@inheritdoc} */ public function interact(InputInterface $input, OutputInterface $output) { $config = parent::interact($input, $output); // Do authentication now so we can detect 2fa if (self::AUTH_HTTP_PASSWORD === $config['authentication']['http-auth-type']) { $client = new Client(); try { $client->authenticate($config['authentication']['username'], $config['authentication']['password-or-token']); try { // Make a call to test authentication $client->api('authorizations')->all(); } catch (TwoFactorAuthenticationRequiredException $e) { // Create a random authorization to make GitHub send the code // We expect an exception, which gets cached by the next catch-block // Note. This authorization is not actually created $client->api('authorizations')->create(['note' => 'Gush on ' . gethostname() . mt_rand(), 'scopes' => ['public_repo']]); } } catch (TwoFactorAuthenticationRequiredException $e) { $isAuthenticated = false; $authenticationAttempts = 0; $authorization = []; $scopes = ['user', 'user:email', 'public_repo', 'repo', 'repo:status', 'read:org']; $output->writeln(sprintf('Two factor authentication of type %s is required: ', trim($e->getType()))); // We already know the password is valid, we just need a valid code // Don't want fill in everything again when you know its valid ;) while (!$isAuthenticated) { // Prevent endless loop with a broken test if ($authenticationAttempts > 500) { $output->writeln('<error>To many attempts, aborting.</error>'); break; } if ($authenticationAttempts > 0) { $output->writeln('<error>Authentication failed please try again.</error>'); } try { $code = $this->questionHelper->ask($input, $output, (new Question('Authentication code: '))->setValidator([$this, 'validateNoneEmpty'])); // Use a date with time to make sure its unique // Its not possible get existing authorizations, only a new one $time = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y-m-d\\TH:i:s'); $authorization = $client->api('authorizations')->create(['note' => sprintf('Gush on %s at %s', gethostname(), $time), 'scopes' => $scopes], $code); $isAuthenticated = isset($authorization['token']); } catch (TwoFactorAuthenticationRequiredException $e) { // Noop, continue the loop, try again } catch (\Exception $e) { $output->writeln("<error>{$e->getMessage()}</error>"); $output->writeln(''); } ++$authenticationAttempts; } if ($isAuthenticated) { $config['authentication']['http-auth-type'] = self::AUTH_HTTP_TOKEN; $config['authentication']['password-or-token'] = $authorization['token']; } } } return $config; }
/** * */ public function run() { $repos = $this->client->api('organization')->repositories($this->githubSettings['organization'], 'member'); /* * @var Github\Api\Repo */ foreach ($repos as $repo) { $this->composerChecker->check($repo); } }
/** * {@inheritdoc} */ public function getCommits() { $commits = $this->client->api('repo')->commits()->all($this->user, $this->repo, ['sha' => $this->branch]); if (!count($commits)) { return; } foreach ($commits as $commit) { (yield $this->createCommit($commit)); } }
/** * @param $organization * @param array $repository */ private function checkComposerLock($organization, array $repository) { $tempFile = tempnam(sys_get_temp_dir(), 'sec'); $handle = fopen($tempFile, 'w'); fwrite($handle, $this->client->api('repo')->contents()->download($organization, $repository['name'], 'composer.lock')); fclose($handle); $alerts = $this->securityChecker->check($tempFile); $contributors = $this->client->api('repo')->contributors($organization, $repository['name']); $this->alertHandler->handleAlerts($repository, $contributors, $alerts); unlink($tempFile); }
/** * Get an array of commit messages for a specific PR * * @param string $username * @param string $repository * @param int $pullRequestId * * @return array */ public function getMessages(string $username, string $repository, int $pullRequestId) : array { /** @var \Github\Api\PullRequest $prApi */ $prApi = $this->client->api('pr'); $response = $prApi->commits($username, $repository, $pullRequestId); $messages = []; foreach ($response as $commit) { $messages[] = new GitHubMessageImplementation($commit['commit']['message'], $commit['sha']); } return $messages; }
/** * Get remote bower.json file (or package.json file) * * @param string $version * @return string */ private function getDepBowerJson($version) { list($repoUser, $repoName) = explode('/', $this->clearGitURL($this->url)); $contents = $this->githubClient->api('repo')->contents(); if ($contents->exists($repoUser, $repoName, 'bower.json', $version)) { $json = $contents->download($repoUser, $repoName, 'bower.json', $version); } else { $isPackageJson = true; if ($contents->exists($repoUser, $repoName, 'package.json', $version)) { $json = $contents->download($repoUser, $repoName, 'package.json', $version); } elseif ($version != 'master') { return $this->getDepBowerJson('master'); } // try anyway. E.g. exists() return false for Modernizr, but then it downloads :-| $json = $contents->download($repoUser, $repoName, 'package.json', $version); } if (substr($json, 0, 3) == "") { $json = substr($json, 3); } // for package.json, remove dependencies (see the case of Modernizr) if (isset($isPackageJson)) { $array = json_decode($json, true); if (isset($array['dependencies'])) { unset($array['dependencies']); } $json = Json::encode($array); } return $json; }
public function handleResponse(UserResponseInterface $response, UserService $userService) { $fields = $response->getResponse(); $gitHubLogin = $fields['login']; $accessToken = $response->getAccessToken(); $user = $userService->findByGitHubLogin($gitHubLogin); if (null === $user) { throw new UsernameNotFoundException(); } $oAuthUser = new OAuthUser($user); $oAuthUser->addRole('ROLE_GITHUB_USER'); $oAuthUser->setAccessToken($accessToken); if (array_key_exists('name', $fields)) { $gitHubName = $fields['name']; $oAuthUser->setRealName($gitHubName); } else { $oAuthUser->setRealName($gitHubLogin); } $client = new Client(); $client->setOption('api_version', 'v3'); $client->authenticate($response->getAccessToken(), Client::AUTH_HTTP_TOKEN); /* @var \Github\Api\CurrentUser $currentUserApi */ $currentUserApi = $client->api('current_user'); $emails = $currentUserApi->emails(); $allEMails = $emails->all(); $oAuthUser->setEmail($this->getPrimaryEmailAddress($allEMails)); return $oAuthUser; }
/** * Exports the changed files into specified directory * * @param string $dir Target directory * * @return void * @throws Exception */ public function export($dir) { /** @var \Github\Api\PullRequest $api */ $api = $this->client->api('pull_request'); $files = $api->files($this->user, $this->repo, $this->pull); /** @var \Github\Api\GitData $api */ $api = $this->client->api('git_data'); $api = $api->blobs(); /** @var \Github\Api\GitData\Blobs $api */ $api->configure('raw'); foreach ($files as $file) { try { $contents = $this->getContents($file['sha']); } catch (RuntimeException $e) { if ($e->getCode() === 404) { // this is probably a submodule reference // :TODO: need a better solution continue; } } $path = $dir . '/' . $file['filename']; $dirName = dirname($path); if (!file_exists($dirName)) { mkdir(dirname($path), 0777, true); } file_put_contents($path, $contents); } }
/** * @param InputInterface $input * @param OutputInterface $output * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { $changelog = array(); $client = new Client(new \Github\HttpClient\CachedHttpClient(array('cache_dir' => '/tmp/github-api-cache'))); $client->authenticate($input->getArgument("token"), null, Client::AUTH_HTTP_TOKEN); $pullRequestAPI = $client->api('pull_request'); $paginator = new ResultPager($client); $parameters = array($input->getArgument("organisation"), $input->getArgument("repository"), array('state' => 'closed')); $pullRequests = $paginator->fetchAll($pullRequestAPI, 'all', $parameters); $mergedPullRequests = array_filter($pullRequests, function ($pullRequest) { return !empty($pullRequest["merged_at"]); }); foreach ($mergedPullRequests as $pullRequest) { if (empty($pullRequest['milestone'])) { $milestone = "No Milestone Selected"; } else { $milestone = $pullRequest['milestone']['title'] . " / " . strftime("%Y-%m-%d", strtotime($pullRequest['milestone']['due_on'])); } if (!array_key_exists($milestone, $changelog)) { $changelog[$milestone] = array(); } $changelog[$milestone][] = $pullRequest; } uksort($changelog, 'version_compare'); $changelog = array_reverse($changelog); echo "# Changelog"; foreach ($changelog as $milestone => $pullRequests) { echo "\n\n## {$milestone}\n\n"; foreach ($pullRequests as $pullRequest) { echo "* " . $pullRequest['title'] . " [#" . $pullRequest['number'] . "](" . $pullRequest['html_url'] . ") ([@" . $pullRequest['user']['login'] . "](" . $pullRequest['user']['html_url'] . ")) \n"; } } //var_dump($changelog); }
public function handle(Client $client) { $client->authenticate($this->user->token, Client::AUTH_HTTP_TOKEN); try { // @todo: Can we get only those updated since date? the API can.. can our client? and does a new comment make it marked as updated? foreach ($client->api('gists')->all() as $gist) { foreach ($client->api('gist')->comments()->all($gist['id']) as $comment) { $this->handleComment($comment, $gist, $this->user); } } } catch (ExceptionInterface $e) { Log::info(sprintf('Attempting to queue "get comments" for user %s after GitHub exception. Delayed exceution for 60 minutes after (%d) attempts. Message: [%s] Exception class: [%s]', $this->user->id, $this->attempts(), $e->getMessage(), get_class($e))); $this->release(3600); } catch (Exception $e) { Log::info(sprintf('Attempting to queue "get comments" for user %s after generic exception. Delayed execution for 2 seconds after (%d) attempts. Message: [%s] Exception class: [%s]', $this->user->id, $this->attempts(), $e->getMessage(), get_class($e))); $this->release(2); } }
/** * Display a list of collaborators (From org or from repo- * @param Request $request * @param Application $app * @param $repo * * @return \Symfony\Component\HttpFoundation\JsonResponse */ public function collaboratorsAction(Request $request, Application $app, $repo) { if (isset($app['config']['github_organization'])) { $collabs = $this->client->api('repo')->collaborators()->all($app['config']['github_organization'], $repo); } else { $collabs = $this->client->api('repo')->collaborators()->all($app['config']['github_username'], $repo); } $out = []; if (is_array($collabs)) { foreach ($collabs as $coll) { if (isset($app['config']['skip_map']) && is_array($app['config']['skip_map']) && in_array($coll['login'], $app['config']['skip_map'])) { continue; } $out[] = ['id' => $coll['id'], 'login' => $coll['login'], 'username' => $this->getUsername($coll['login'], $app['config'])]; } } return $app->json($out); }
/** * @param string $user * @param string $repository * @return string[] */ private function fetchCollaborators($user, $repository) { /** @var \GitHub\Api\Repo $repositoryApi */ $repositoryApi = $this->github->api('repo'); $collaborators = $repositoryApi->collaborators()->all($user, $repository); $collaborators = array_map(function ($user) { return $user['login']; }, $collaborators); return $collaborators; }
/** * {@inheritdoc} */ public function getPullRequest($id) { if (is_null($id)) { throw new \InvalidArgumentException('Invalid ID.'); } $pull = $this->client->api('pull_request')->show('laravel', 'laravel', (int) $id); if ($pull) { return ['id' => (int) $id, 'title' => $pull['title'], 'user' => $pull['user']['login'], 'url' => $pull['html_url'], 'from_branch' => $pull['head']['ref'], 'to_branch' => $pull['base']['ref']]; } throw new \InvalidArgumentException('ID Not Found.'); }
/** * send(). * * Send the bug report to github. * And store the user email privately. * To add later the function to email the user if the bug is closed. * * @param githubValidator $input */ public function send(githubValidator $input) { // TODO: Set credentials to the .env file. $client = new Client(); $client->authenticate('Tjoosten', '0474834880Tim!', $client::AUTH_HTTP_PASSWORD); $client->api('issues')->create(env('GIT_NAME'), env('GIT_REPO'), ['title' => $input->title, 'body' => $input->body]); // Success: Error created. session()->flash('flash_title', 'Bedankt.'); session()->flash('flash_message', 'Wij hebben je melding geregistreerd.'); session()->flash('flash_message_important', true); return Redirect::back(); }
protected function execute(InputInterface $input, OutputInterface $output) { chdir(__DIR__ . '/../..'); $table = new TableHelper(); $table->setHeaders(['Vendor name', 'Ahead', 'Permalink']); $vendorRows = array_filter(file('vendors.csv')); // Filter out empty rows. $githubApi = new GithubClient(); /** @var Repo $repoApi */ $repoApi = $githubApi->api('repo'); if ($input->getOption('username')) { $password = $input->getOption('password'); if (!$password) { $q = new Question(sprintf('Please enter the GitHub password for user <comment>%s</comment>:', $input->getOption('username'))); $q->setHidden(true); $q->setValidator(function ($value) { if (empty($value)) { throw new \InvalidArgumentException('You must provide a password'); } }); $password = $this->getHelper('question')->ask($input, $output, $q); } $githubApi->authenticate($input->getOption('username'), $password, GithubClient::AUTH_HTTP_PASSWORD); } foreach ($vendorRows as $vendorRow) { list($vendorName, $repoId, $latestCommitHash) = str_getcsv($vendorRow); // Repo ID is in the format author-name/repository-name. list($repoAuthor, $repoName) = explode('/', $repoId); // This provides us with much information, example: http://pastebin.com/raw.php?i=gkmUS9nU $headInfo = $repoApi->commits()->compare($repoAuthor, $repoName, $latestCommitHash, 'HEAD'); $aheadBy = "<comment>Up to date!</comment>"; $permalink = ""; if ($headInfo['ahead_by']) { $permalink = $headInfo['permalink_url']; $additions = array_sum(array_map(function ($files) { return $files['additions']; }, $headInfo['files'])); $deletions = array_sum(array_map(function ($files) { return $files['deletions']; }, $headInfo['files'])); if ($additions) { $additions = "<comment>+{$additions}</comment>"; } if ($deletions) { $deletions = "<info>-{$deletions}</info>"; } $aheadBy = "<info>{$headInfo['ahead_by']}</info> commits ({$additions}/{$deletions})"; } $table->addRow(["{$vendorName} (<info>{$repoId}</info>)", $aheadBy, $permalink]); } $table->render($output); }
public function getPhotoList() { $list = []; if (!$this->client->api('repo')->contents()->exists($this->user, $this->repo, 'photos', $this->branch)) { return $list; } foreach ($this->client->api('repo')->contents()->show($this->user, $this->repo, 'photos', $this->branch) as $file) { $sequence = substr($file['name'], -8); $sequence = substr($sequence, 0, 4); $list[] = $sequence; } return $list; }
/** * Return GitHub notifications * * @return OauthTokenError|mixed */ public static final function notifications() { if (!Cache::has('github_token')) { return new Util\OauthTokenError('GitHub', url('auth/github')); } try { $client = new GithubClient(); $client->authenticate(Cache::get('github_token'), null, GithubClient::AUTH_URL_TOKEN); return $client->api('notification')->all(true, false, new \DateTime('-24 hours')); } catch (\Exception $e) { } return false; }
/** * Collects GitHub credentials and stores them. * * @param Client $client GitHub client * @param Config $config Configuration * @param resource $input Input stream * @param resource $output Output stream */ function collectCredentials(Client $client, Config $config, $input, $output) { fwrite($output, 'Username: '******'Password: '******'authorizations'); $info = $api->create(array('note' => 'DiffSniffer', 'scopes' => 'repo')); $config->setParams($info); fwrite($output, 'Configuration successfully saved.' . PHP_EOL); }
public function setUp() { $client = new Client(); try { $client->api('current_user')->show(); } catch (ApiLimitExceedException $e) { $this->markTestSkipped('API limit reached. Skipping to prevent unnecessary failure.'); } catch (RuntimeException $e) { if ('Requires authentication' == $e->getMessage()) { $this->markTestSkipped('Test requires authentication. Skipping to prevent unnecessary failure.'); } } $this->client = $client; }
/** * {@inheritdoc} */ public function collect(array $repos) { $commitsApi = $this->client->api('repos')->commits(); $metrics = array(); foreach ($repos as $author => $authorRepos) { foreach ($authorRepos as $repo) { $repoCommits = $commitsApi->all($author, $repo, array('since' => date('Y-m-d\\TH:i:s\\Z', time() - 60 * 60 * 24))); foreach ($repoCommits as $commit) { $userName = $commit['commit']['author']['name']; $message = $commit['commit']['message']; $wasAMerge = strpos($message, 'Merge') !== false; if (!$wasAMerge) { if (array_key_exists($userName, $metrics)) { $metrics[$userName]++; } else { $metrics[$userName] = 1; } } } } } return $metrics; }
/** * @param array $files * @param string $commitId * @return array */ public function downloadFiles($files, $commitId) { $downloadedFiles = []; foreach ($files as $file) { if (!preg_match('/.*\\.php$/', $file['filename']) || $file['status'] === "removed") { continue; } $fileContent = $this->client->api('repo')->contents()->download($this->owner, $this->repository, $file['filename'], $commitId); $file = sys_get_temp_dir() . "/" . $file['filename']; $this->filesystem->put($file, $fileContent); $downloadedFiles[] = $file; } return $downloadedFiles; }
/** * コメントを取得する * * PR内のファイルに対するもの、PR自体に対するもの、両方を取得しマージする * * @param int $pr_number PR番号 * @return array $return_arr GithubAPI-Commentのレスポンスと、追加情報を含む配列 */ public function getComments($pr_number, $mode = self::COMMENT_GET_ALL) { // コメントは30個でページングされるため、それらを一気に取得するためのインスタンスを生成する $pager = new \Github\ResultPager($this->client); // コメントを取得する (PR内のファイルに対するもの) $pr_comments = []; if (self::COMMENT_GET_ALL === $mode or self::COMMENT_GET_FILE === $mode) { $pr_comments = $pager->fetchAll($this->client->api('pull_request')->comments(), 'all', array($this->repo_owner, $this->repo_name, $pr_number)); } // コメントを取得する (PR自体に対するもの) $issue_comments = []; if (self::COMMENT_GET_ALL === $mode or self::COMMENT_GET_PR === $mode) { $issue_comments = $pager->fetchAll($this->client->api('issue')->comments(), 'all', array($this->repo_owner, $this->repo_name, $pr_number)); } // コメントをマージして、日付昇順にする $comment_arr = array_merge($pr_comments, $issue_comments); usort($comment_arr, 'self::dateAscSort'); // 情報を追加する $is_new = true; $review_status = 0; $return_arr = []; foreach ($comment_arr as $comment) { if (1 === preg_match(GITHUB_PATTERN_IGNORE_USER, $comment['user']['login'])) { // このユーザのコメントは無視する continue; } $is_agree = $is_reset = $is_deco = false; if (isset($comment['diff_hunk'])) { // PR内のファイルに対するものであるとき $type = 'file'; } else { // PR自体に対するものであるとき $type = 'pr'; if (1 === preg_match(GITHUB_PATTERN_AGREE, $comment['body'])) { $is_agree = true; $review_status += 1; } if (1 === preg_match(GITHUB_PATTERN_RESET_AGREE, $comment['body'])) { $is_reset = true; $review_status = 0; } if (1 === preg_match(GITHUB_PATTERN_SHOW_URL, $comment['body'])) { $is_deco = true; } } $return_arr[] = ['is_new' => $is_new, 'is_decorate' => $is_deco, 'is_agree' => $is_agree, 'is_reset' => $is_reset, 'review_status' => $review_status, 'type' => $type, 'content' => $comment]; $is_new = false; } return $return_arr; }