Пример #1
0
 /**
  * Set oauth token (to increase API limit to 5000 per hour, instead of default 60)
  *
  * @param Client $client
  */
 protected function setToken(Client $client)
 {
     $token = getenv('BOWERPHP_TOKEN');
     if (!empty($token)) {
         $client->authenticate($token, null, Client::AUTH_HTTP_TOKEN);
     }
 }
 /**
  * @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);
 }
Пример #3
0
 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(), []);
 }
Пример #4
0
 /**
  * (non-PHPdoc)
  * @see \Symfony\Component\Console\Command\Command::execute()
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $dialog = $this->getHelper('dialog');
     try {
         $client = new Client();
         $username = $input->getOption('username');
         if (!$username) {
             $username = $dialog->ask($output, 'Please enter your GitHub username: '******'password');
         if (!$password) {
             $password = $dialog->askHiddenResponse($output, 'Please enter your GitHub password: ');
         }
         $client->authenticate($username, $password, Client::AUTH_HTTP_PASSWORD);
         $forkService = $this->getForkService($input, $client);
         $forkedRepositoryList = $forkService->fork();
         $message = $this->formatMessage($forkedRepositoryList);
     } catch (\InvalidArgumentException $exception) {
         $message = $exception->getMessage();
     } catch (GithubRuntimeException $exception) {
         $message = $exception->getMessage();
         $message = "<error>{$message}</error>";
     } finally {
         $output->writeln($message);
     }
 }
Пример #5
0
 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;
 }
Пример #6
0
 public function testInjectApi()
 {
     $client = new Client();
     $userApiMock = $this->getMockBuilder('Github\\Api\\ApiInterface')->getMock();
     $client->setApi('user', $userApiMock);
     $this->assertSame($userApiMock, $client->getUserApi());
 }
Пример #7
0
 /**
  * {@inheritdoc}
  */
 public function register(Application $app)
 {
     $app['github'] = $app->share(function () {
         $client = new Client(new CachedHttpClient(['cache_dir' => __DIR__ . '/../../../app/cache/github-api-cache']));
         return new GithubAdapter($client->getHttpClient());
     });
 }
Пример #8
0
 /**
  * {@inheritdoc}
  */
 public function findProjects($name)
 {
     return $this->requestProjects($name, function ($name) {
         list($user) = explode('/', $name);
         return $this->client->user()->repositories($user);
     }, 'full_name');
 }
Пример #9
0
 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()];
 }
Пример #10
0
 /**
  * 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);
 }
 protected function getEngine()
 {
     $client = new Client();
     if ($client->rateLimit()->getCoreLimit() < 1) {
         $this->markTestSkipped('The github API rate limit is reached, so this engine cannot be tested.');
     }
     return new GitHubMarkdownEngine();
 }
Пример #12
0
 /**
  * @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;
 }
Пример #13
0
 /**
  * Add a team member to AsgardCms
  * @param string $githubUsername
  * @return \Guzzle\Http\EntityBodyInterface|mixed|string
  */
 public function addTeamMember($githubUsername)
 {
     try {
         return $this->client->organization()->teams()->addMember('1132536', $githubUsername);
     } catch (\Exception $e) {
         dd($e->getMessage());
     }
 }
Пример #14
0
 /**
  * Construct GitSpam instance with its dependencies
  *
  * @param $username
  * @param $password
  *
  * @return GitSpam
  */
 private function setup($username, $password)
 {
     $client = new GithubAPIClient();
     $client->authenticate($username, $password);
     $commitReader = new YouTrackCommitReader();
     $gitSpammer = new GitSpammer($client, $commitReader);
     return $gitSpammer;
 }
/**
 * Runs pull request validation
 *
 * @param Client $client    GitHub client
 * @param Config $config    Configuration
 * @param array  $arguments Command line arguments
 *
 * @return int              Exit code
 * @throws \InvalidArgumentException
 */
function run(Client $client, Config $config, array $arguments)
{
    $config = $config->getParams();
    $client->authenticate($config['token'], null, Client::AUTH_URL_TOKEN);
    $changeset = new Changeset($client, array_shift($arguments), array_shift($arguments), array_shift($arguments));
    $runner = new Runner();
    return $runner->run($changeset, $arguments);
}
Пример #16
0
 protected function getClient()
 {
     $httpClient = new CachedHttpClient(['cache_dir' => storage_path(config('services.github.cache_url'))]);
     $client = new Client($httpClient);
     //dd($client);
     $client->authenticate(auth()->user()->github_token, 'http_token');
     return $client;
 }
Пример #17
0
 public static function createClient(SettingsManager $settingsManager)
 {
     $settings = new GeneralSettings();
     $settingsManager->loadSettings($settings);
     $client = new Client();
     $client->authenticate($settings->githubToken, null, Client::AUTH_HTTP_TOKEN);
     return $client;
 }
Пример #18
0
 /**
  * {@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;
 }
Пример #19
0
 public function let(Client $client, HookSettings $hookSettings, GithubRepo $githubRepo, Repo $repo, Hooks $hooks)
 {
     $githubRepo->getOwner()->willReturn('owner');
     $githubRepo->getName()->willReturn('repository');
     $client->repo()->willReturn($repo);
     $repo->hooks()->willReturn($hooks);
     $hookSettings->getCreateHookParams()->willReturn(['params']);
     $this->beConstructedWith($client, $hookSettings, $githubRepo);
 }
Пример #20
0
 /**
  * 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 "";
     }
 }
Пример #21
0
 public function it_returns_the_badges(Client $client, Repo $api, Contents $content)
 {
     $client->repos()->willReturn($api);
     $api->contents()->willReturn($content);
     $content->show('foo', 'bar', '.travis.yml')->shouldBeCalled()->willReturn(['encoding' => 'base64', 'content' => base64_encode('{}')]);
     $content->show('foo', 'bar', 'composer.json')->shouldBeCalled()->willReturn(['encoding' => 'base64', 'content' => base64_encode('{ "name" : "foo/bar"}')]);
     $this->getBadges()->shouldBeArray();
     $this->getBadges()->shouldHaveCount(3);
 }
Пример #22
0
 /**
  * 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;
 }
 /**
  * Constructs a new GitHub tracker instance.
  *
  * @param string $username
  * @param string $password
  * @param string $project
  * @param string $owner Optional project owner, e.g. user or organization.
  */
 public function __construct($username, $password, $project, $owner = null)
 {
     $github = new Client();
     $github->setHeaders(array('Authorization: Basic ' . base64_encode("{$username}:{$password}")));
     $github->authenticate($username, $password, Client::AUTH_HTTP_PASSWORD);
     $this->github = $github->getIssueApi();
     $this->owner = $owner ?: $username;
     $this->project = $project;
 }
 /**
  * @return Client
  */
 public function getGithubClient()
 {
     if (!$this->client) {
         $token = $this->container->getParameter('github')['api']['auth_token'];
         $this->client = new \Github\Client();
         $this->client->authenticate($token, null, \Github\Client::AUTH_HTTP_TOKEN);
     }
     return $this->client;
 }
Пример #25
0
 /**
  * Create a github client wrapper with automated token-based authentication.
  *
  * @param string $token The API token to authenticate with.
  * @param string $owner The owner name of the github repository.
  * @param string $repo The name of the github repository.
  * @param string $apiUrl The base url to the github API if different from the main github site (i.e., GitHub Enterprise).
  * @return self The github client wrapper, authenticated against the API.
  */
 public static function createWithToken($token, $owner, $repo, $apiUrl = null)
 {
     $client = new Client();
     if ($apiUrl !== null) {
         $client->setOption('base_url', $apiUrl);
     }
     $client->authenticate($token, null, Client::AUTH_HTTP_TOKEN);
     return new static($client, $owner, $repo);
 }
 /**
  * @param string|null $accessToken
  * @return Client
  */
 public function createClient($accessToken = null)
 {
     $client = new Client();
     if ($this->token instanceof OAuthToken && null === $accessToken) {
         $client->authenticate($this->token->getAccessToken(), null, Client::AUTH_HTTP_TOKEN);
     } elseif (null !== $accessToken) {
         $client->authenticate($accessToken, null, Client::AUTH_HTTP_TOKEN);
     }
     return $client;
 }
Пример #27
0
 /**
  * {@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 string $user
  * @param string $repository
  * @return float
  */
 private function computeOpenIssueRatio($user, $repository)
 {
     $query = "repo:{$user}/{$repository} type:issue " . $this->getExcludedLabelsSearchString();
     $results = $this->github->search()->issues("{$query} state:open");
     $openCount = $results['total_count'];
     $results = $this->github->search()->issues("{$query} state:closed");
     $closedCount = $results['total_count'];
     $total = $openCount + $closedCount;
     return $total !== 0 ? $openCount / $total : 0;
 }
Пример #29
0
 /**
  * Register the github client class.
  *
  * @param  \Illuminate\Contracts\Foundation\Application  $app
  * @return void
  */
 protected function registerGithubClient(Application $app)
 {
     $app->singleton('blogit.github.client', function ($app) {
         $cachedHttpClient = $app['blogit.github.cachedHttpClient'];
         $client = new Client($cachedHttpClient);
         $client->authenticate(env('GITHUB_TOKEN'), 'http_token');
         return $client;
     });
     $app->alias('blogit.github.client', Client::class);
 }
Пример #30
0
 /**
  * gets a file (content) from the repository.
  *
  * @param string $filename
  *
  * @return string
  */
 protected function getFile($filename)
 {
     try {
         $file = $this->client->repos()->contents()->show($this->raw['owner']['login'], $this->raw['name'], $filename);
         if ('base64' === $file['encoding']) {
             return base64_decode($file['content'], true);
         }
     } catch (\Exception $e) {
         //file not found
     }
 }