repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
platformsh/platformsh-cli | src/Console/CustomMarkdownDescriptor.php | CustomMarkdownDescriptor.describeInputArgument | protected function describeInputArgument(InputArgument $argument, array $options = [])
{
$this->write('* **`' . $argument->getName() . "`**");
$notes = [
$argument->isRequired() ? "required" : "optional",
];
if ($argument->isArray()) {
$notes[] = "multiple values allowed";
}
$this->write(' (' . implode('; ', $notes) . ')');
$this->write(" \n " . $argument->getDescription());
if (!$argument->isRequired() && $argument->getDefault()) {
$default = var_export($argument->getDefault(), true);
$this->write(" \n Default: `$default``");
}
} | php | protected function describeInputArgument(InputArgument $argument, array $options = [])
{
$this->write('* **`' . $argument->getName() . "`**");
$notes = [
$argument->isRequired() ? "required" : "optional",
];
if ($argument->isArray()) {
$notes[] = "multiple values allowed";
}
$this->write(' (' . implode('; ', $notes) . ')');
$this->write(" \n " . $argument->getDescription());
if (!$argument->isRequired() && $argument->getDefault()) {
$default = var_export($argument->getDefault(), true);
$this->write(" \n Default: `$default``");
}
} | [
"protected",
"function",
"describeInputArgument",
"(",
"InputArgument",
"$",
"argument",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"write",
"(",
"'* **`'",
".",
"$",
"argument",
"->",
"getName",
"(",
")",
".",
"\"`**\"",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/CustomMarkdownDescriptor.php#L72-L87 |
platformsh/platformsh-cli | src/Console/CustomMarkdownDescriptor.php | CustomMarkdownDescriptor.describeInputOption | protected function describeInputOption(InputOption $option, array $options = [])
{
$this->write('* **`--' . $option->getName() . "`**");
if ($shortcut = $option->getShortcut()) {
$this->write(" (`-" . implode('|-', explode('|', $shortcut)). "`)");
}
$notes = [];
if ($option->isArray()) {
$notes[] = 'multiple values allowed';
} elseif ($option->acceptValue()) {
$notes[] = 'expects a value';
}
if ($notes) {
$this->write(' (' . implode('; ', $notes) . ')');
}
if ($description = $option->getDescription()) {
$this->write(" \n " . $description);
}
if ($option->acceptValue() && $option->getDefault()) {
$default = var_export($option->getDefault(), true);
$this->write(" \n Default: `$default`");
}
} | php | protected function describeInputOption(InputOption $option, array $options = [])
{
$this->write('* **`--' . $option->getName() . "`**");
if ($shortcut = $option->getShortcut()) {
$this->write(" (`-" . implode('|-', explode('|', $shortcut)). "`)");
}
$notes = [];
if ($option->isArray()) {
$notes[] = 'multiple values allowed';
} elseif ($option->acceptValue()) {
$notes[] = 'expects a value';
}
if ($notes) {
$this->write(' (' . implode('; ', $notes) . ')');
}
if ($description = $option->getDescription()) {
$this->write(" \n " . $description);
}
if ($option->acceptValue() && $option->getDefault()) {
$default = var_export($option->getDefault(), true);
$this->write(" \n Default: `$default`");
}
} | [
"protected",
"function",
"describeInputOption",
"(",
"InputOption",
"$",
"option",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"write",
"(",
"'* **`--'",
".",
"$",
"option",
"->",
"getName",
"(",
")",
".",
"\"`**\"",
")",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/CustomMarkdownDescriptor.php#L92-L114 |
platformsh/platformsh-cli | src/Local/DependencyManager/Bundler.php | Bundler.install | public function install($path, array $dependencies, $global = false)
{
$gemFile = $path . '/Gemfile';
$gemFileContent = $this->formatGemfile($dependencies);
$current = file_exists($gemFile) ? file_get_contents($gemFile) : false;
if ($current !== $gemFileContent) {
file_put_contents($gemFile, $gemFileContent);
if (file_exists($path . '/Gemfile.lock')) {
unlink('Gemfile.lock');
}
}
if ($global) {
$this->runCommand('bundle install --system --gemfile=Gemfile', $path);
} else {
$this->runCommand('bundle install --path=. --binstubs --gemfile=Gemfile', $path);
}
} | php | public function install($path, array $dependencies, $global = false)
{
$gemFile = $path . '/Gemfile';
$gemFileContent = $this->formatGemfile($dependencies);
$current = file_exists($gemFile) ? file_get_contents($gemFile) : false;
if ($current !== $gemFileContent) {
file_put_contents($gemFile, $gemFileContent);
if (file_exists($path . '/Gemfile.lock')) {
unlink('Gemfile.lock');
}
}
if ($global) {
$this->runCommand('bundle install --system --gemfile=Gemfile', $path);
} else {
$this->runCommand('bundle install --path=. --binstubs --gemfile=Gemfile', $path);
}
} | [
"public",
"function",
"install",
"(",
"$",
"path",
",",
"array",
"$",
"dependencies",
",",
"$",
"global",
"=",
"false",
")",
"{",
"$",
"gemFile",
"=",
"$",
"path",
".",
"'/Gemfile'",
";",
"$",
"gemFileContent",
"=",
"$",
"this",
"->",
"formatGemfile",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyManager/Bundler.php#L28-L44 |
platformsh/platformsh-cli | src/Local/DependencyManager/Bundler.php | Bundler.formatGemfile | private function formatGemfile(array $dependencies)
{
$lines = ["source 'https://rubygems.org'"];
foreach ($dependencies as $package => $version) {
if ($version != '*') {
$lines[] = sprintf("gem '%s', '%s', :require => false", $package, $version);
} else {
$lines[] = sprintf("gem '%s', :require => false", $package);
}
}
return implode("\n", $lines);
} | php | private function formatGemfile(array $dependencies)
{
$lines = ["source 'https://rubygems.org'"];
foreach ($dependencies as $package => $version) {
if ($version != '*') {
$lines[] = sprintf("gem '%s', '%s', :require => false", $package, $version);
} else {
$lines[] = sprintf("gem '%s', :require => false", $package);
}
}
return implode("\n", $lines);
} | [
"private",
"function",
"formatGemfile",
"(",
"array",
"$",
"dependencies",
")",
"{",
"$",
"lines",
"=",
"[",
"\"source 'https://rubygems.org'\"",
"]",
";",
"foreach",
"(",
"$",
"dependencies",
"as",
"$",
"package",
"=>",
"$",
"version",
")",
"{",
"if",
"(",
... | @param array $dependencies
@return string | [
"@param",
"array",
"$dependencies"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyManager/Bundler.php#L51-L63 |
platformsh/platformsh-cli | src/Command/Auth/BrowserLoginCommand.php | BrowserLoginCommand.getAccessToken | private function getAccessToken($authCode, $redirectUri, $tokenUrl)
{
return (new Client())->post(
$tokenUrl,
[
'json' => [
'grant_type' => 'authorization_code',
'code' => $authCode,
'client_id' => $this->config()->get('api.oauth2_client_id'),
'redirect_uri' => $redirectUri,
],
'auth' => false,
'verify' => !$this->config()->get('api.skip_ssl'),
]
)->json();
} | php | private function getAccessToken($authCode, $redirectUri, $tokenUrl)
{
return (new Client())->post(
$tokenUrl,
[
'json' => [
'grant_type' => 'authorization_code',
'code' => $authCode,
'client_id' => $this->config()->get('api.oauth2_client_id'),
'redirect_uri' => $redirectUri,
],
'auth' => false,
'verify' => !$this->config()->get('api.skip_ssl'),
]
)->json();
} | [
"private",
"function",
"getAccessToken",
"(",
"$",
"authCode",
",",
"$",
"redirectUri",
",",
"$",
"tokenUrl",
")",
"{",
"return",
"(",
"new",
"Client",
"(",
")",
")",
"->",
"post",
"(",
"$",
"tokenUrl",
",",
"[",
"'json'",
"=>",
"[",
"'grant_type'",
"=... | Exchange the authorization code for an access token.
@param string $authCode
@param string $redirectUri
@param string $tokenUrl
@return array | [
"Exchange",
"the",
"authorization",
"code",
"for",
"an",
"access",
"token",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Auth/BrowserLoginCommand.php#L289-L304 |
platformsh/platformsh-cli | src/Command/Service/MongoDB/MongoExportCommand.php | MongoExportCommand.getCollections | private function getCollections(array $service, $sshUrl)
{
/** @var \Platformsh\Cli\Service\Relationships $relationshipsService */
$relationshipsService = $this->getService('relationships');
/** @var \Platformsh\Cli\Service\Ssh $ssh */
$ssh = $this->getService('ssh');
/** @var \Platformsh\Cli\Service\Shell $shell */
$shell = $this->getService('shell');
$js = 'printjson(db.getCollectionNames())';
$command = 'mongo '
. $relationshipsService->getDbCommandArgs('mongo', $service)
. ' --quiet --eval ' . OsUtil::escapePosixShellArg($js);
$sshArgs = array_merge(['ssh'], $ssh->getSshArgs());
$sshArgs[] = $sshUrl;
$sshArgs[] = $command;
/** @noinspection PhpUnhandledExceptionInspection */
$result = $shell->execute($sshArgs, null, true);
if (!is_string($result)) {
return [];
}
$collections = json_decode($result, true) ?: [];
return array_filter($collections, function ($collection) {
return substr($collection, 0, 7) !== 'system.';
});
} | php | private function getCollections(array $service, $sshUrl)
{
/** @var \Platformsh\Cli\Service\Relationships $relationshipsService */
$relationshipsService = $this->getService('relationships');
/** @var \Platformsh\Cli\Service\Ssh $ssh */
$ssh = $this->getService('ssh');
/** @var \Platformsh\Cli\Service\Shell $shell */
$shell = $this->getService('shell');
$js = 'printjson(db.getCollectionNames())';
$command = 'mongo '
. $relationshipsService->getDbCommandArgs('mongo', $service)
. ' --quiet --eval ' . OsUtil::escapePosixShellArg($js);
$sshArgs = array_merge(['ssh'], $ssh->getSshArgs());
$sshArgs[] = $sshUrl;
$sshArgs[] = $command;
/** @noinspection PhpUnhandledExceptionInspection */
$result = $shell->execute($sshArgs, null, true);
if (!is_string($result)) {
return [];
}
$collections = json_decode($result, true) ?: [];
return array_filter($collections, function ($collection) {
return substr($collection, 0, 7) !== 'system.';
});
} | [
"private",
"function",
"getCollections",
"(",
"array",
"$",
"service",
",",
"$",
"sshUrl",
")",
"{",
"/** @var \\Platformsh\\Cli\\Service\\Relationships $relationshipsService */",
"$",
"relationshipsService",
"=",
"$",
"this",
"->",
"getService",
"(",
"'relationships'",
"... | Get collections in the MongoDB database.
@param array $service
@param string $sshUrl
@return array | [
"Get",
"collections",
"in",
"the",
"MongoDB",
"database",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Service/MongoDB/MongoExportCommand.php#L113-L143 |
platformsh/platformsh-cli | src/Command/Mount/MountUploadCommand.php | MountUploadCommand.configure | protected function configure()
{
$this
->setName('mount:upload')
->setDescription('Upload files to a mount, using rsync')
->addOption('source', null, InputOption::VALUE_REQUIRED, 'A directory containing files to upload')
->addOption('mount', 'm', InputOption::VALUE_REQUIRED, 'The mount (as an app-relative path)')
->addOption('delete', null, InputOption::VALUE_NONE, 'Whether to delete extraneous files in the mount')
->addOption('exclude', null, InputOption::VALUE_IS_ARRAY|InputOption::VALUE_REQUIRED, 'File(s) to exclude from the upload (pattern)')
->addOption('include', null, InputOption::VALUE_IS_ARRAY|InputOption::VALUE_REQUIRED, 'File(s) to include in the upload (pattern)')
->addOption('refresh', null, InputOption::VALUE_NONE, 'Whether to refresh the cache');
$this->addProjectOption();
$this->addEnvironmentOption();
$this->addAppOption();
} | php | protected function configure()
{
$this
->setName('mount:upload')
->setDescription('Upload files to a mount, using rsync')
->addOption('source', null, InputOption::VALUE_REQUIRED, 'A directory containing files to upload')
->addOption('mount', 'm', InputOption::VALUE_REQUIRED, 'The mount (as an app-relative path)')
->addOption('delete', null, InputOption::VALUE_NONE, 'Whether to delete extraneous files in the mount')
->addOption('exclude', null, InputOption::VALUE_IS_ARRAY|InputOption::VALUE_REQUIRED, 'File(s) to exclude from the upload (pattern)')
->addOption('include', null, InputOption::VALUE_IS_ARRAY|InputOption::VALUE_REQUIRED, 'File(s) to include in the upload (pattern)')
->addOption('refresh', null, InputOption::VALUE_NONE, 'Whether to refresh the cache');
$this->addProjectOption();
$this->addEnvironmentOption();
$this->addAppOption();
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'mount:upload'",
")",
"->",
"setDescription",
"(",
"'Upload files to a mount, using rsync'",
")",
"->",
"addOption",
"(",
"'source'",
",",
"null",
",",
"InputOption",
"::",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Mount/MountUploadCommand.php#L17-L31 |
platformsh/platformsh-cli | src/Command/Mount/MountUploadCommand.php | MountUploadCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$appName = $this->selectApp($input);
$appConfig = $this->getAppConfig($appName, (bool) $input->getOption('refresh'));
if (empty($appConfig['mounts'])) {
$this->stdErr->writeln(sprintf('The app "%s" doesn\'t define any mounts.', $appConfig['name']));
return 1;
}
/** @var \Platformsh\Cli\Service\Mount $mountService */
$mountService = $this->getService('mount');
$mounts = $mountService->normalizeMounts($appConfig['mounts']);
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
/** @var \Platformsh\Cli\Service\Filesystem $fs */
$fs = $this->getService('fs');
if ($input->getOption('mount')) {
$mountPath = $mountService->validateMountPath($input->getOption('mount'), $mounts);
} elseif ($input->isInteractive()) {
$mountPath = $questionHelper->choose(
$this->getMountsAsOptions($mounts),
'Enter a number to choose a mount to upload to:'
);
} else {
$this->stdErr->writeln('The <error>--mount</error> option must be specified (in non-interactive mode).');
return 1;
}
$source = null;
$defaultSource = null;
if ($input->getOption('source')) {
$source = $input->getOption('source');
} elseif ($projectRoot = $this->getProjectRoot()) {
$sharedMounts = $mountService->getSharedFileMounts($appConfig);
if (isset($sharedMounts[$mountPath])) {
if (file_exists($projectRoot . '/' . $this->config()->get('local.shared_dir') . '/' . $sharedMounts[$mountPath])) {
$defaultSource = $projectRoot . '/' . $this->config()->get('local.shared_dir') . '/' . $sharedMounts[$mountPath];
}
}
$applications = LocalApplication::getApplications($projectRoot, $this->config());
$appPath = $projectRoot;
foreach ($applications as $path => $candidateApp) {
if ($candidateApp->getName() === $appName) {
$appPath = $path;
break;
}
}
if (is_dir($appPath . '/' . $mountPath)) {
$defaultSource = $appPath . '/' . $mountPath;
}
}
if (empty($source)) {
$questionText = 'Source directory';
if ($defaultSource !== null) {
$formattedDefaultSource = $fs->formatPathForDisplay($defaultSource);
$questionText .= ' <question>[' . $formattedDefaultSource . ']</question>';
}
$questionText .= ': ';
$source = $questionHelper->ask($input, $this->stdErr, new Question($questionText, $defaultSource));
}
if (empty($source)) {
$this->stdErr->writeln('The source directory must be specified.');
return 1;
}
$this->validateDirectory($source);
$confirmText = sprintf(
"\nUploading files from <comment>%s</comment> to the remote mount <comment>%s</comment>"
. "\n\nAre you sure you want to continue?",
$fs->formatPathForDisplay($source),
$mountPath
);
if (!$questionHelper->confirm($confirmText)) {
return 1;
}
$this->runSync($appName, $mountPath, $source, true, [
'delete' => $input->getOption('delete'),
'exclude' => $input->getOption('exclude'),
'include' => $input->getOption('include'),
]);
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$appName = $this->selectApp($input);
$appConfig = $this->getAppConfig($appName, (bool) $input->getOption('refresh'));
if (empty($appConfig['mounts'])) {
$this->stdErr->writeln(sprintf('The app "%s" doesn\'t define any mounts.', $appConfig['name']));
return 1;
}
/** @var \Platformsh\Cli\Service\Mount $mountService */
$mountService = $this->getService('mount');
$mounts = $mountService->normalizeMounts($appConfig['mounts']);
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
/** @var \Platformsh\Cli\Service\Filesystem $fs */
$fs = $this->getService('fs');
if ($input->getOption('mount')) {
$mountPath = $mountService->validateMountPath($input->getOption('mount'), $mounts);
} elseif ($input->isInteractive()) {
$mountPath = $questionHelper->choose(
$this->getMountsAsOptions($mounts),
'Enter a number to choose a mount to upload to:'
);
} else {
$this->stdErr->writeln('The <error>--mount</error> option must be specified (in non-interactive mode).');
return 1;
}
$source = null;
$defaultSource = null;
if ($input->getOption('source')) {
$source = $input->getOption('source');
} elseif ($projectRoot = $this->getProjectRoot()) {
$sharedMounts = $mountService->getSharedFileMounts($appConfig);
if (isset($sharedMounts[$mountPath])) {
if (file_exists($projectRoot . '/' . $this->config()->get('local.shared_dir') . '/' . $sharedMounts[$mountPath])) {
$defaultSource = $projectRoot . '/' . $this->config()->get('local.shared_dir') . '/' . $sharedMounts[$mountPath];
}
}
$applications = LocalApplication::getApplications($projectRoot, $this->config());
$appPath = $projectRoot;
foreach ($applications as $path => $candidateApp) {
if ($candidateApp->getName() === $appName) {
$appPath = $path;
break;
}
}
if (is_dir($appPath . '/' . $mountPath)) {
$defaultSource = $appPath . '/' . $mountPath;
}
}
if (empty($source)) {
$questionText = 'Source directory';
if ($defaultSource !== null) {
$formattedDefaultSource = $fs->formatPathForDisplay($defaultSource);
$questionText .= ' <question>[' . $formattedDefaultSource . ']</question>';
}
$questionText .= ': ';
$source = $questionHelper->ask($input, $this->stdErr, new Question($questionText, $defaultSource));
}
if (empty($source)) {
$this->stdErr->writeln('The source directory must be specified.');
return 1;
}
$this->validateDirectory($source);
$confirmText = sprintf(
"\nUploading files from <comment>%s</comment> to the remote mount <comment>%s</comment>"
. "\n\nAre you sure you want to continue?",
$fs->formatPathForDisplay($source),
$mountPath
);
if (!$questionHelper->confirm($confirmText)) {
return 1;
}
$this->runSync($appName, $mountPath, $source, true, [
'delete' => $input->getOption('delete'),
'exclude' => $input->getOption('exclude'),
'include' => $input->getOption('include'),
]);
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"validateInput",
"(",
"$",
"input",
")",
";",
"$",
"appName",
"=",
"$",
"this",
"->",
"selectApp",
"(",
"$",
"inp... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Mount/MountUploadCommand.php#L36-L130 |
platformsh/platformsh-cli | src/Service/Shell.php | Shell.setOutput | public function setOutput(OutputInterface $output)
{
$this->output = $output;
$this->stdErr = $output instanceof ConsoleOutputInterface
? $output->getErrorOutput()
: $output;
} | php | public function setOutput(OutputInterface $output)
{
$this->output = $output;
$this->stdErr = $output instanceof ConsoleOutputInterface
? $output->getErrorOutput()
: $output;
} | [
"public",
"function",
"setOutput",
"(",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"output",
"=",
"$",
"output",
";",
"$",
"this",
"->",
"stdErr",
"=",
"$",
"output",
"instanceof",
"ConsoleOutputInterface",
"?",
"$",
"output",
"->",
"ge... | Change the output object.
@param OutputInterface $output | [
"Change",
"the",
"output",
"object",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Shell.php#L31-L37 |
platformsh/platformsh-cli | src/Service/Shell.php | Shell.executeSimple | public function executeSimple($commandline, $dir = null, array $env = [])
{
$this->stdErr->writeln(
'Running command: <info>' . $commandline . '</info>',
OutputInterface::VERBOSITY_VERBOSE
);
if (!empty($env)) {
$this->showEnvMessage($env);
$env = $env + $this->getParentEnv();
} else {
$env = null;
}
$this->showWorkingDirMessage($dir);
$process = proc_open($commandline, [STDIN, STDOUT, STDERR], $pipes, $dir, $env);
return proc_close($process);
} | php | public function executeSimple($commandline, $dir = null, array $env = [])
{
$this->stdErr->writeln(
'Running command: <info>' . $commandline . '</info>',
OutputInterface::VERBOSITY_VERBOSE
);
if (!empty($env)) {
$this->showEnvMessage($env);
$env = $env + $this->getParentEnv();
} else {
$env = null;
}
$this->showWorkingDirMessage($dir);
$process = proc_open($commandline, [STDIN, STDOUT, STDERR], $pipes, $dir, $env);
return proc_close($process);
} | [
"public",
"function",
"executeSimple",
"(",
"$",
"commandline",
",",
"$",
"dir",
"=",
"null",
",",
"array",
"$",
"env",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"stdErr",
"->",
"writeln",
"(",
"'Running command: <info>'",
".",
"$",
"commandline",
".",... | Execute a command, using STDIN, STDERR and STDOUT directly.
@param string $commandline
@param string|null $dir
@param array $env
@return int
The command's exit code (0 on success, a different integer on failure). | [
"Execute",
"a",
"command",
"using",
"STDIN",
"STDERR",
"and",
"STDOUT",
"directly",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Shell.php#L49-L68 |
platformsh/platformsh-cli | src/Service/Shell.php | Shell.execute | public function execute(array $args, $dir = null, $mustRun = false, $quiet = true, array $env = [], $timeout = 3600)
{
$process = new Process($args, null, null, null, $timeout);
// Avoid adding 'exec' to every command. It is not needed in this
// context as we do not need to send signals to the process. Also it
// causes compatibility issues, at least with the shell built-in command
// 'command' on Travis containers.
// See https://github.com/symfony/symfony/issues/23495
$process->setCommandLine($process->getCommandLine());
if ($timeout === null) {
set_time_limit(0);
}
$this->stdErr->writeln(
"Running command: <info>" . $process->getCommandLine() . "</info>",
OutputInterface::VERBOSITY_VERBOSE
);
if (!empty($env)) {
$this->showEnvMessage($env);
$process->setEnv($env + $this->getParentEnv());
}
if ($dir && is_dir($dir)) {
$process->setWorkingDirectory($dir);
$this->showWorkingDirMessage($dir);
}
$result = $this->runProcess($process, $mustRun, $quiet);
return is_int($result) ? $result === 0 : $result;
} | php | public function execute(array $args, $dir = null, $mustRun = false, $quiet = true, array $env = [], $timeout = 3600)
{
$process = new Process($args, null, null, null, $timeout);
// Avoid adding 'exec' to every command. It is not needed in this
// context as we do not need to send signals to the process. Also it
// causes compatibility issues, at least with the shell built-in command
// 'command' on Travis containers.
// See https://github.com/symfony/symfony/issues/23495
$process->setCommandLine($process->getCommandLine());
if ($timeout === null) {
set_time_limit(0);
}
$this->stdErr->writeln(
"Running command: <info>" . $process->getCommandLine() . "</info>",
OutputInterface::VERBOSITY_VERBOSE
);
if (!empty($env)) {
$this->showEnvMessage($env);
$process->setEnv($env + $this->getParentEnv());
}
if ($dir && is_dir($dir)) {
$process->setWorkingDirectory($dir);
$this->showWorkingDirMessage($dir);
}
$result = $this->runProcess($process, $mustRun, $quiet);
return is_int($result) ? $result === 0 : $result;
} | [
"public",
"function",
"execute",
"(",
"array",
"$",
"args",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
",",
"$",
"quiet",
"=",
"true",
",",
"array",
"$",
"env",
"=",
"[",
"]",
",",
"$",
"timeout",
"=",
"3600",
")",
"{",
"$... | Execute a command.
@param array $args
@param string|null $dir
@param bool $mustRun
@param bool $quiet
@param array $env
@param int|null $timeout
@throws \Symfony\Component\Process\Exception\RuntimeException
If $mustRun is enabled and the command fails.
@return bool|string
False if the command fails, true if it succeeds with no output, or a
string if it succeeds with output. | [
"Execute",
"a",
"command",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Shell.php#L87-L120 |
platformsh/platformsh-cli | src/Service/Shell.php | Shell.getParentEnv | protected function getParentEnv()
{
if (PHP_VERSION_ID >= 70100) {
return getenv();
}
// In PHP <7.1 there isn't a way to read all of the current environment
// variables. If PHP is running with a variables_order that includes
// 'e', then $_ENV should be populated.
if (!empty($_ENV) && stripos(ini_get('variables_order'), 'e') !== false) {
return $_ENV;
}
// If $_ENV is empty, then we can only use a whitelist of all the
// variables that we might want to use.
$candidates = [
'TERM',
'TERM_SESSION_ID',
'TMPDIR',
'SSH_AGENT_PID',
'SSH_AUTH_SOCK',
'PATH',
'LANG',
'LC_ALL',
'LC_CTYPE',
'PAGER',
'LESS',
];
$variables = [];
foreach ($candidates as $name) {
$variables[$name] = getenv($name);
}
return array_filter($variables, function ($value) {
return $value !== false;
});
} | php | protected function getParentEnv()
{
if (PHP_VERSION_ID >= 70100) {
return getenv();
}
// In PHP <7.1 there isn't a way to read all of the current environment
// variables. If PHP is running with a variables_order that includes
// 'e', then $_ENV should be populated.
if (!empty($_ENV) && stripos(ini_get('variables_order'), 'e') !== false) {
return $_ENV;
}
// If $_ENV is empty, then we can only use a whitelist of all the
// variables that we might want to use.
$candidates = [
'TERM',
'TERM_SESSION_ID',
'TMPDIR',
'SSH_AGENT_PID',
'SSH_AUTH_SOCK',
'PATH',
'LANG',
'LC_ALL',
'LC_CTYPE',
'PAGER',
'LESS',
];
$variables = [];
foreach ($candidates as $name) {
$variables[$name] = getenv($name);
}
return array_filter($variables, function ($value) {
return $value !== false;
});
} | [
"protected",
"function",
"getParentEnv",
"(",
")",
"{",
"if",
"(",
"PHP_VERSION_ID",
">=",
"70100",
")",
"{",
"return",
"getenv",
"(",
")",
";",
"}",
"// In PHP <7.1 there isn't a way to read all of the current environment",
"// variables. If PHP is running with a variables_o... | Attempt to read useful environment variables from the parent process.
@return array | [
"Attempt",
"to",
"read",
"useful",
"environment",
"variables",
"from",
"the",
"parent",
"process",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Shell.php#L151-L186 |
platformsh/platformsh-cli | src/Service/Shell.php | Shell.runProcess | protected function runProcess(Process $process, $mustRun = false, $quiet = true)
{
try {
$process->mustRun($quiet ? null : function ($type, $buffer) {
$output = $type === Process::ERR ? $this->stdErr : $this->output;
$output->write(preg_replace('/^/m', ' ', $buffer));
});
} catch (ProcessFailedException $e) {
if (!$mustRun) {
return $process->getExitCode();
}
// The default for Symfony's ProcessFailedException is to print the
// entire STDOUT and STDERR. But if $quiet is disabled, then the user
// will have already seen the command's output. So we need to
// re-throw the exception with our own ProcessFailedException, which
// will generate a much shorter message.
throw new \Platformsh\Cli\Exception\ProcessFailedException($process, $quiet);
}
$output = $process->getOutput();
return $output ? rtrim($output) : true;
} | php | protected function runProcess(Process $process, $mustRun = false, $quiet = true)
{
try {
$process->mustRun($quiet ? null : function ($type, $buffer) {
$output = $type === Process::ERR ? $this->stdErr : $this->output;
$output->write(preg_replace('/^/m', ' ', $buffer));
});
} catch (ProcessFailedException $e) {
if (!$mustRun) {
return $process->getExitCode();
}
// The default for Symfony's ProcessFailedException is to print the
// entire STDOUT and STDERR. But if $quiet is disabled, then the user
// will have already seen the command's output. So we need to
// re-throw the exception with our own ProcessFailedException, which
// will generate a much shorter message.
throw new \Platformsh\Cli\Exception\ProcessFailedException($process, $quiet);
}
$output = $process->getOutput();
return $output ? rtrim($output) : true;
} | [
"protected",
"function",
"runProcess",
"(",
"Process",
"$",
"process",
",",
"$",
"mustRun",
"=",
"false",
",",
"$",
"quiet",
"=",
"true",
")",
"{",
"try",
"{",
"$",
"process",
"->",
"mustRun",
"(",
"$",
"quiet",
"?",
"null",
":",
"function",
"(",
"$"... | Run a process.
@param Process $process
@param bool $mustRun
@param bool $quiet
@throws \Symfony\Component\Process\Exception\RuntimeException
If the process fails or times out, and $mustRun is true.
@return int|string
The exit code of the process if it fails, true if it succeeds with no
output, or a string if it succeeds with output. | [
"Run",
"a",
"process",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Shell.php#L202-L223 |
platformsh/platformsh-cli | src/Service/Shell.php | Shell.findWhere | protected function findWhere($command, $noticeOnError = true)
{
static $result;
if (!isset($result[$command])) {
if (is_executable($command)) {
$result[$command] = $command;
} else {
$args = ['command', '-v', $command];
if (OsUtil::isWindows()) {
$args = ['where', $command];
}
$result[$command] = $this->execute($args, null, false, true);
if ($result[$command] === false && $noticeOnError) {
trigger_error(sprintf("Failed to find command via: %s", implode(' ', $args)), E_USER_NOTICE);
}
}
}
return $result[$command];
} | php | protected function findWhere($command, $noticeOnError = true)
{
static $result;
if (!isset($result[$command])) {
if (is_executable($command)) {
$result[$command] = $command;
} else {
$args = ['command', '-v', $command];
if (OsUtil::isWindows()) {
$args = ['where', $command];
}
$result[$command] = $this->execute($args, null, false, true);
if ($result[$command] === false && $noticeOnError) {
trigger_error(sprintf("Failed to find command via: %s", implode(' ', $args)), E_USER_NOTICE);
}
}
}
return $result[$command];
} | [
"protected",
"function",
"findWhere",
"(",
"$",
"command",
",",
"$",
"noticeOnError",
"=",
"true",
")",
"{",
"static",
"$",
"result",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"result",
"[",
"$",
"command",
"]",
")",
")",
"{",
"if",
"(",
"is_executable... | Run 'where' or equivalent on a command.
@param string $command
@param bool $noticeOnError
@return string|bool
A list of command paths (one per line) or false on failure. | [
"Run",
"where",
"or",
"equivalent",
"on",
"a",
"command",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Shell.php#L234-L253 |
platformsh/platformsh-cli | src/Service/Shell.php | Shell.resolveCommand | public function resolveCommand($command)
{
if ($fullPaths = $this->findWhere($command)) {
$fullPaths = preg_split('/[\r\n]/', trim($fullPaths));
$command = end($fullPaths);
}
return $command;
} | php | public function resolveCommand($command)
{
if ($fullPaths = $this->findWhere($command)) {
$fullPaths = preg_split('/[\r\n]/', trim($fullPaths));
$command = end($fullPaths);
}
return $command;
} | [
"public",
"function",
"resolveCommand",
"(",
"$",
"command",
")",
"{",
"if",
"(",
"$",
"fullPaths",
"=",
"$",
"this",
"->",
"findWhere",
"(",
"$",
"command",
")",
")",
"{",
"$",
"fullPaths",
"=",
"preg_split",
"(",
"'/[\\r\\n]/'",
",",
"trim",
"(",
"$"... | Find the absolute path to an executable.
@param string $command
@return string | [
"Find",
"the",
"absolute",
"path",
"to",
"an",
"executable",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Shell.php#L274-L282 |
platformsh/platformsh-cli | src/Command/Tunnel/TunnelOpenCommand.php | TunnelOpenCommand.configure | protected function configure()
{
$this
->setName('tunnel:open')
->setDescription("Open SSH tunnels to an app's relationships");
$this->addProjectOption();
$this->addEnvironmentOption();
$this->addAppOption();
Ssh::configureInput($this->getDefinition());
$this->setHelp(<<<EOF
This command opens SSH tunnels to all of the relationships of an application.
Connections can then be made to the application's services as if they were
local, for example a local MySQL client can be used, or the Solr web
administration endpoint can be accessed through a local browser.
This command requires the posix and pcntl PHP extensions (as multiple
background CLI processes are created to keep the SSH tunnels open). The
<info>tunnel:single</info> command can be used on systems without these
extensions.
EOF
);
} | php | protected function configure()
{
$this
->setName('tunnel:open')
->setDescription("Open SSH tunnels to an app's relationships");
$this->addProjectOption();
$this->addEnvironmentOption();
$this->addAppOption();
Ssh::configureInput($this->getDefinition());
$this->setHelp(<<<EOF
This command opens SSH tunnels to all of the relationships of an application.
Connections can then be made to the application's services as if they were
local, for example a local MySQL client can be used, or the Solr web
administration endpoint can be accessed through a local browser.
This command requires the posix and pcntl PHP extensions (as multiple
background CLI processes are created to keep the SSH tunnels open). The
<info>tunnel:single</info> command can be used on systems without these
extensions.
EOF
);
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'tunnel:open'",
")",
"->",
"setDescription",
"(",
"\"Open SSH tunnels to an app's relationships\"",
")",
";",
"$",
"this",
"->",
"addProjectOption",
"(",
")",
";",
"$",
"thi... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Tunnel/TunnelOpenCommand.php#L14-L36 |
platformsh/platformsh-cli | src/Command/Tunnel/TunnelOpenCommand.php | TunnelOpenCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->checkSupport();
$this->validateInput($input);
$project = $this->getSelectedProject();
$environment = $this->getSelectedEnvironment();
if ($environment->id === 'master') {
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$confirmText = 'Are you sure you want to open SSH tunnel(s) to the'
. ' <comment>master</comment> (production) environment?';
if (!$questionHelper->confirm($confirmText, false)) {
return 1;
}
$this->stdErr->writeln('');
}
$appName = $this->selectApp($input);
$sshUrl = $environment->getSshUrl($appName);
/** @var \Platformsh\Cli\Service\Relationships $relationshipsService */
$relationshipsService = $this->getService('relationships');
$relationships = $relationshipsService->getRelationships($sshUrl);
if (!$relationships) {
$this->stdErr->writeln('No relationships found.');
return 1;
}
$logFile = $this->config()->getWritableUserDir() . '/tunnels.log';
if (!$log = $this->openLog($logFile)) {
$this->stdErr->writeln(sprintf('Failed to open log file for writing: %s', $logFile));
return 1;
}
/** @var \Platformsh\Cli\Service\Ssh $ssh */
$ssh = $this->getService('ssh');
$sshArgs = $ssh->getSshArgs();
$log->setVerbosity($output->getVerbosity());
$processManager = new ProcessManager();
$processManager->fork();
$error = false;
$processIds = [];
foreach ($relationships as $relationship => $services) {
foreach ($services as $serviceKey => $service) {
$remoteHost = $service['host'];
$remotePort = $service['port'];
$localPort = $this->getPort();
$tunnel = [
'projectId' => $project->id,
'environmentId' => $environment->id,
'appName' => $appName,
'relationship' => $relationship,
'serviceKey' => $serviceKey,
'remotePort' => $remotePort,
'remoteHost' => $remoteHost,
'localPort' => $localPort,
'service' => $service,
'pid' => null,
];
$relationshipString = $this->formatTunnelRelationship($tunnel);
if ($openTunnelInfo = $this->isTunnelOpen($tunnel)) {
$this->stdErr->writeln(sprintf(
'A tunnel is already open on port %s for the relationship: <info>%s</info>',
$openTunnelInfo['localPort'],
$relationshipString
));
continue;
}
$process = $this->createTunnelProcess($sshUrl, $remoteHost, $remotePort, $localPort, $sshArgs);
$pidFile = $this->getPidFile($tunnel);
try {
$pid = $processManager->startProcess($process, $pidFile, $log);
} catch (\Exception $e) {
$this->stdErr->writeln(sprintf(
'Failed to open tunnel for relationship <error>%s</error>: %s',
$relationshipString,
$e->getMessage()
));
$error = true;
continue;
}
// Wait a very small time to capture any immediate errors.
usleep(100000);
if (!$process->isRunning() && !$process->isSuccessful()) {
$this->stdErr->writeln(trim($process->getErrorOutput()));
$this->stdErr->writeln(sprintf(
'Failed to open tunnel for relationship: <error>%s</error>',
$relationshipString
));
unlink($pidFile);
$error = true;
continue;
}
// Save information about the tunnel for use in other commands.
$tunnel['pid'] = $pid;
$this->tunnelInfo[] = $tunnel;
$this->saveTunnelInfo();
$this->stdErr->writeln(sprintf(
'SSH tunnel opened on port <info>%s</info> to relationship: <info>%s</info>',
$tunnel['localPort'],
$relationshipString
));
$processIds[] = $pid;
}
}
if (count($processIds)) {
$this->stdErr->writeln("Logs are written to: $logFile");
}
if (!$error) {
$executable = $this->config()->get('application.executable');
$variable = $this->config()->get('service.env_prefix') . 'RELATIONSHIPS';
$this->stdErr->writeln('');
$this->stdErr->writeln("List tunnels with: <info>$executable tunnels</info>");
$this->stdErr->writeln("View tunnel details with: <info>$executable tunnel:info</info>");
$this->stdErr->writeln("Close tunnels with: <info>$executable tunnel:close</info>");
$this->stdErr->writeln('');
$this->stdErr->writeln(
"Save encoded tunnel details to the $variable variable using:"
. "\n <info>export $variable=\"$($executable tunnel:info --encode)\"</info>"
);
}
$processManager->killParent($error);
$processManager->monitor($log);
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->checkSupport();
$this->validateInput($input);
$project = $this->getSelectedProject();
$environment = $this->getSelectedEnvironment();
if ($environment->id === 'master') {
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$confirmText = 'Are you sure you want to open SSH tunnel(s) to the'
. ' <comment>master</comment> (production) environment?';
if (!$questionHelper->confirm($confirmText, false)) {
return 1;
}
$this->stdErr->writeln('');
}
$appName = $this->selectApp($input);
$sshUrl = $environment->getSshUrl($appName);
/** @var \Platformsh\Cli\Service\Relationships $relationshipsService */
$relationshipsService = $this->getService('relationships');
$relationships = $relationshipsService->getRelationships($sshUrl);
if (!$relationships) {
$this->stdErr->writeln('No relationships found.');
return 1;
}
$logFile = $this->config()->getWritableUserDir() . '/tunnels.log';
if (!$log = $this->openLog($logFile)) {
$this->stdErr->writeln(sprintf('Failed to open log file for writing: %s', $logFile));
return 1;
}
/** @var \Platformsh\Cli\Service\Ssh $ssh */
$ssh = $this->getService('ssh');
$sshArgs = $ssh->getSshArgs();
$log->setVerbosity($output->getVerbosity());
$processManager = new ProcessManager();
$processManager->fork();
$error = false;
$processIds = [];
foreach ($relationships as $relationship => $services) {
foreach ($services as $serviceKey => $service) {
$remoteHost = $service['host'];
$remotePort = $service['port'];
$localPort = $this->getPort();
$tunnel = [
'projectId' => $project->id,
'environmentId' => $environment->id,
'appName' => $appName,
'relationship' => $relationship,
'serviceKey' => $serviceKey,
'remotePort' => $remotePort,
'remoteHost' => $remoteHost,
'localPort' => $localPort,
'service' => $service,
'pid' => null,
];
$relationshipString = $this->formatTunnelRelationship($tunnel);
if ($openTunnelInfo = $this->isTunnelOpen($tunnel)) {
$this->stdErr->writeln(sprintf(
'A tunnel is already open on port %s for the relationship: <info>%s</info>',
$openTunnelInfo['localPort'],
$relationshipString
));
continue;
}
$process = $this->createTunnelProcess($sshUrl, $remoteHost, $remotePort, $localPort, $sshArgs);
$pidFile = $this->getPidFile($tunnel);
try {
$pid = $processManager->startProcess($process, $pidFile, $log);
} catch (\Exception $e) {
$this->stdErr->writeln(sprintf(
'Failed to open tunnel for relationship <error>%s</error>: %s',
$relationshipString,
$e->getMessage()
));
$error = true;
continue;
}
// Wait a very small time to capture any immediate errors.
usleep(100000);
if (!$process->isRunning() && !$process->isSuccessful()) {
$this->stdErr->writeln(trim($process->getErrorOutput()));
$this->stdErr->writeln(sprintf(
'Failed to open tunnel for relationship: <error>%s</error>',
$relationshipString
));
unlink($pidFile);
$error = true;
continue;
}
// Save information about the tunnel for use in other commands.
$tunnel['pid'] = $pid;
$this->tunnelInfo[] = $tunnel;
$this->saveTunnelInfo();
$this->stdErr->writeln(sprintf(
'SSH tunnel opened on port <info>%s</info> to relationship: <info>%s</info>',
$tunnel['localPort'],
$relationshipString
));
$processIds[] = $pid;
}
}
if (count($processIds)) {
$this->stdErr->writeln("Logs are written to: $logFile");
}
if (!$error) {
$executable = $this->config()->get('application.executable');
$variable = $this->config()->get('service.env_prefix') . 'RELATIONSHIPS';
$this->stdErr->writeln('');
$this->stdErr->writeln("List tunnels with: <info>$executable tunnels</info>");
$this->stdErr->writeln("View tunnel details with: <info>$executable tunnel:info</info>");
$this->stdErr->writeln("Close tunnels with: <info>$executable tunnel:close</info>");
$this->stdErr->writeln('');
$this->stdErr->writeln(
"Save encoded tunnel details to the $variable variable using:"
. "\n <info>export $variable=\"$($executable tunnel:info --encode)\"</info>"
);
}
$processManager->killParent($error);
$processManager->monitor($log);
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"checkSupport",
"(",
")",
";",
"$",
"this",
"->",
"validateInput",
"(",
"$",
"input",
")",
";",
"$",
"project",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Tunnel/TunnelOpenCommand.php#L41-L183 |
platformsh/platformsh-cli | src/Service/Api.php | Api.loadTokenFromFile | protected function loadTokenFromFile($filename)
{
if (strpos($filename, '/') !== 0 && strpos($filename, '\\') !== 0) {
$filename = $this->config->getUserConfigDir() . '/' . $filename;
}
$content = file_get_contents($filename);
if ($content === false) {
throw new \RuntimeException('Failed to read file: ' . $filename);
}
return trim($content);
} | php | protected function loadTokenFromFile($filename)
{
if (strpos($filename, '/') !== 0 && strpos($filename, '\\') !== 0) {
$filename = $this->config->getUserConfigDir() . '/' . $filename;
}
$content = file_get_contents($filename);
if ($content === false) {
throw new \RuntimeException('Failed to read file: ' . $filename);
}
return trim($content);
} | [
"protected",
"function",
"loadTokenFromFile",
"(",
"$",
"filename",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"filename",
",",
"'/'",
")",
"!==",
"0",
"&&",
"strpos",
"(",
"$",
"filename",
",",
"'\\\\'",
")",
"!==",
"0",
")",
"{",
"$",
"filename",
"="... | Load an API token from a file.
@param string $filename
A filename, either relative to the user config directory, or absolute.
@return string | [
"Load",
"an",
"API",
"token",
"from",
"a",
"file",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L129-L141 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getUserAgent | protected function getUserAgent()
{
return sprintf(
'%s/%s (%s; %s; PHP %s)',
str_replace(' ', '-', $this->config->get('application.name')),
$this->config->getVersion(),
php_uname('s'),
php_uname('r'),
PHP_VERSION
);
} | php | protected function getUserAgent()
{
return sprintf(
'%s/%s (%s; %s; PHP %s)',
str_replace(' ', '-', $this->config->get('application.name')),
$this->config->getVersion(),
php_uname('s'),
php_uname('r'),
PHP_VERSION
);
} | [
"protected",
"function",
"getUserAgent",
"(",
")",
"{",
"return",
"sprintf",
"(",
"'%s/%s (%s; %s; PHP %s)'",
",",
"str_replace",
"(",
"' '",
",",
"'-'",
",",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'application.name'",
")",
")",
",",
"$",
"this",
... | Get an HTTP User Agent string representing this application.
@return string | [
"Get",
"an",
"HTTP",
"User",
"Agent",
"string",
"representing",
"this",
"application",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L158-L168 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getClient | public function getClient($autoLogin = true, $reset = false)
{
if (!isset(self::$client) || $reset) {
$connectorOptions = [];
$connectorOptions['accounts'] = rtrim($this->config->get('api.accounts_api_url'), '/') . '/';
$connectorOptions['verify'] = !$this->config->get('api.skip_ssl');
$connectorOptions['debug'] = $this->config->get('api.debug') ? STDERR : false;
$connectorOptions['client_id'] = $this->config->get('api.oauth2_client_id');
$connectorOptions['user_agent'] = $this->getUserAgent();
$connectorOptions['api_token'] = $this->apiToken;
$connectorOptions['api_token_type'] = $this->apiTokenType;
// Proxy support with the http_proxy or https_proxy environment
// variables.
if (PHP_SAPI === 'cli') {
$proxies = [];
foreach (['https', 'http'] as $scheme) {
$proxies[$scheme] = str_replace('http://', 'tcp://', getenv($scheme . '_proxy'));
}
$proxies = array_filter($proxies);
if (count($proxies)) {
$connectorOptions['proxy'] = count($proxies) == 1 ? reset($proxies) : $proxies;
}
}
$connector = new Connector($connectorOptions);
// Set up a persistent session to store OAuth2 tokens. By default,
// this will be stored in a JSON file:
// $HOME/.platformsh/.session/sess-cli-default/sess-cli-default.json
$session = $connector->getSession();
$session->setId('cli-' . $this->sessionId);
$this->sessionStorage = KeychainStorage::isSupported()
&& $this->config->isExperimentEnabled('use_keychain')
? new KeychainStorage($this->config->get('application.name'))
: new File($this->config->getSessionDir());
$session->setStorage($this->sessionStorage);
// Ensure session data is (re-)loaded every time.
// @todo move this to the Session
if (!$session->getData()) {
$session->load(true);
}
self::$client = new PlatformClient($connector);
if ($autoLogin && !$connector->isLoggedIn()) {
$this->dispatcher->dispatch('login_required');
}
try {
$connector->getClient()->getEmitter()->on('error', function (ErrorEvent $event) {
if ($event->getResponse() && $event->getResponse()->getStatusCode() === 403) {
$this->on403($event);
}
});
} catch (\RuntimeException $e) {
// Ignore errors if the user is not logged in at this stage.
}
}
return self::$client;
} | php | public function getClient($autoLogin = true, $reset = false)
{
if (!isset(self::$client) || $reset) {
$connectorOptions = [];
$connectorOptions['accounts'] = rtrim($this->config->get('api.accounts_api_url'), '/') . '/';
$connectorOptions['verify'] = !$this->config->get('api.skip_ssl');
$connectorOptions['debug'] = $this->config->get('api.debug') ? STDERR : false;
$connectorOptions['client_id'] = $this->config->get('api.oauth2_client_id');
$connectorOptions['user_agent'] = $this->getUserAgent();
$connectorOptions['api_token'] = $this->apiToken;
$connectorOptions['api_token_type'] = $this->apiTokenType;
// Proxy support with the http_proxy or https_proxy environment
// variables.
if (PHP_SAPI === 'cli') {
$proxies = [];
foreach (['https', 'http'] as $scheme) {
$proxies[$scheme] = str_replace('http://', 'tcp://', getenv($scheme . '_proxy'));
}
$proxies = array_filter($proxies);
if (count($proxies)) {
$connectorOptions['proxy'] = count($proxies) == 1 ? reset($proxies) : $proxies;
}
}
$connector = new Connector($connectorOptions);
// Set up a persistent session to store OAuth2 tokens. By default,
// this will be stored in a JSON file:
// $HOME/.platformsh/.session/sess-cli-default/sess-cli-default.json
$session = $connector->getSession();
$session->setId('cli-' . $this->sessionId);
$this->sessionStorage = KeychainStorage::isSupported()
&& $this->config->isExperimentEnabled('use_keychain')
? new KeychainStorage($this->config->get('application.name'))
: new File($this->config->getSessionDir());
$session->setStorage($this->sessionStorage);
// Ensure session data is (re-)loaded every time.
// @todo move this to the Session
if (!$session->getData()) {
$session->load(true);
}
self::$client = new PlatformClient($connector);
if ($autoLogin && !$connector->isLoggedIn()) {
$this->dispatcher->dispatch('login_required');
}
try {
$connector->getClient()->getEmitter()->on('error', function (ErrorEvent $event) {
if ($event->getResponse() && $event->getResponse()->getStatusCode() === 403) {
$this->on403($event);
}
});
} catch (\RuntimeException $e) {
// Ignore errors if the user is not logged in at this stage.
}
}
return self::$client;
} | [
"public",
"function",
"getClient",
"(",
"$",
"autoLogin",
"=",
"true",
",",
"$",
"reset",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"client",
")",
"||",
"$",
"reset",
")",
"{",
"$",
"connectorOptions",
"=",
"[",
"]",
... | Get the API client object.
@param bool $autoLogin Whether to log in, if the client is not already
authenticated (default: true).
@param bool $reset Whether to re-initialize the client.
@return PlatformClient | [
"Get",
"the",
"API",
"client",
"object",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L179-L242 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getProjects | public function getProjects($refresh = null)
{
$cacheKey = sprintf('%s:projects', $this->sessionId);
/** @var Project[] $projects */
$projects = [];
$cached = $this->cache->fetch($cacheKey);
if ($refresh === false && !$cached) {
return [];
} elseif ($refresh || !$cached) {
foreach ($this->getClient()->getProjects() as $project) {
$projects[$project->id] = $project;
}
$cachedProjects = [];
foreach ($projects as $id => $project) {
$cachedProjects[$id] = $project->getData();
$cachedProjects[$id]['_endpoint'] = $project->getUri(true);
}
$this->cache->save($cacheKey, $cachedProjects, $this->config->get('api.projects_ttl'));
} else {
$guzzleClient = $this->getHttpClient();
foreach ((array) $cached as $id => $data) {
$projects[$id] = new Project($data, $data['_endpoint'], $guzzleClient);
}
}
return $projects;
} | php | public function getProjects($refresh = null)
{
$cacheKey = sprintf('%s:projects', $this->sessionId);
/** @var Project[] $projects */
$projects = [];
$cached = $this->cache->fetch($cacheKey);
if ($refresh === false && !$cached) {
return [];
} elseif ($refresh || !$cached) {
foreach ($this->getClient()->getProjects() as $project) {
$projects[$project->id] = $project;
}
$cachedProjects = [];
foreach ($projects as $id => $project) {
$cachedProjects[$id] = $project->getData();
$cachedProjects[$id]['_endpoint'] = $project->getUri(true);
}
$this->cache->save($cacheKey, $cachedProjects, $this->config->get('api.projects_ttl'));
} else {
$guzzleClient = $this->getHttpClient();
foreach ((array) $cached as $id => $data) {
$projects[$id] = new Project($data, $data['_endpoint'], $guzzleClient);
}
}
return $projects;
} | [
"public",
"function",
"getProjects",
"(",
"$",
"refresh",
"=",
"null",
")",
"{",
"$",
"cacheKey",
"=",
"sprintf",
"(",
"'%s:projects'",
",",
"$",
"this",
"->",
"sessionId",
")",
";",
"/** @var Project[] $projects */",
"$",
"projects",
"=",
"[",
"]",
";",
"... | Return the user's projects.
@param bool|null $refresh Whether to refresh the list of projects.
@return Project[] The user's projects, keyed by project ID. | [
"Return",
"the",
"user",
"s",
"projects",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L251-L282 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getProject | public function getProject($id, $host = null, $refresh = null)
{
// Find the project in the user's main project list. This uses a
// separate cache.
$projects = $this->getProjects($refresh);
if (isset($projects[$id])) {
return $projects[$id];
}
// Find the project directly.
$cacheKey = sprintf('%s:project:%s:%s', $this->sessionId, $id, $host);
$cached = $this->cache->fetch($cacheKey);
if ($refresh || !$cached) {
$scheme = 'https';
if ($host !== null && (($pos = strpos($host, '//')) !== false)) {
$scheme = parse_url($host, PHP_URL_SCHEME);
$host = substr($host, $pos + 2);
}
$project = $this->getClient()
->getProject($id, $host, $scheme !== 'http');
if ($project) {
$toCache = $project->getData();
$toCache['_endpoint'] = $project->getUri(true);
$this->cache->save($cacheKey, $toCache, $this->config->get('api.projects_ttl'));
}
} else {
$guzzleClient = $this->getHttpClient();
$baseUrl = $cached['_endpoint'];
unset($cached['_endpoint']);
$project = new Project($cached, $baseUrl, $guzzleClient);
}
return $project;
} | php | public function getProject($id, $host = null, $refresh = null)
{
// Find the project in the user's main project list. This uses a
// separate cache.
$projects = $this->getProjects($refresh);
if (isset($projects[$id])) {
return $projects[$id];
}
// Find the project directly.
$cacheKey = sprintf('%s:project:%s:%s', $this->sessionId, $id, $host);
$cached = $this->cache->fetch($cacheKey);
if ($refresh || !$cached) {
$scheme = 'https';
if ($host !== null && (($pos = strpos($host, '//')) !== false)) {
$scheme = parse_url($host, PHP_URL_SCHEME);
$host = substr($host, $pos + 2);
}
$project = $this->getClient()
->getProject($id, $host, $scheme !== 'http');
if ($project) {
$toCache = $project->getData();
$toCache['_endpoint'] = $project->getUri(true);
$this->cache->save($cacheKey, $toCache, $this->config->get('api.projects_ttl'));
}
} else {
$guzzleClient = $this->getHttpClient();
$baseUrl = $cached['_endpoint'];
unset($cached['_endpoint']);
$project = new Project($cached, $baseUrl, $guzzleClient);
}
return $project;
} | [
"public",
"function",
"getProject",
"(",
"$",
"id",
",",
"$",
"host",
"=",
"null",
",",
"$",
"refresh",
"=",
"null",
")",
"{",
"// Find the project in the user's main project list. This uses a",
"// separate cache.",
"$",
"projects",
"=",
"$",
"this",
"->",
"getPr... | Return the user's project with the given ID.
@param string $id The project ID.
@param string|null $host The project's hostname.
@param bool|null $refresh Whether to bypass the cache.
@return Project|false | [
"Return",
"the",
"user",
"s",
"project",
"with",
"the",
"given",
"ID",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L293-L326 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getEnvironments | public function getEnvironments(Project $project, $refresh = null, $events = true)
{
$projectId = $project->id;
if (!$refresh && isset(self::$environmentsCache[$projectId])) {
return self::$environmentsCache[$projectId];
}
$cacheKey = 'environments:' . $projectId;
$cached = $this->cache->fetch($cacheKey);
if ($refresh === false && !$cached) {
return [];
} elseif ($refresh || !$cached) {
$environments = [];
$toCache = [];
foreach ($project->getEnvironments() as $environment) {
$environments[$environment->id] = $environment;
$toCache[$environment->id] = $environment->getData();
}
// Dispatch an event if the list of environments has changed.
if ($events && (!$cached || array_diff_key($environments, $cached))) {
$this->dispatcher->dispatch(
'environments_changed',
new EnvironmentsChangedEvent($project, $environments)
);
}
$this->cache->save($cacheKey, $toCache, $this->config->get('api.environments_ttl'));
self::$environmentsCacheRefreshed = true;
} else {
$environments = [];
$endpoint = $project->getUri();
$guzzleClient = $this->getHttpClient();
foreach ((array) $cached as $id => $data) {
$environments[$id] = new Environment($data, $endpoint, $guzzleClient, true);
}
}
self::$environmentsCache[$projectId] = $environments;
return $environments;
} | php | public function getEnvironments(Project $project, $refresh = null, $events = true)
{
$projectId = $project->id;
if (!$refresh && isset(self::$environmentsCache[$projectId])) {
return self::$environmentsCache[$projectId];
}
$cacheKey = 'environments:' . $projectId;
$cached = $this->cache->fetch($cacheKey);
if ($refresh === false && !$cached) {
return [];
} elseif ($refresh || !$cached) {
$environments = [];
$toCache = [];
foreach ($project->getEnvironments() as $environment) {
$environments[$environment->id] = $environment;
$toCache[$environment->id] = $environment->getData();
}
// Dispatch an event if the list of environments has changed.
if ($events && (!$cached || array_diff_key($environments, $cached))) {
$this->dispatcher->dispatch(
'environments_changed',
new EnvironmentsChangedEvent($project, $environments)
);
}
$this->cache->save($cacheKey, $toCache, $this->config->get('api.environments_ttl'));
self::$environmentsCacheRefreshed = true;
} else {
$environments = [];
$endpoint = $project->getUri();
$guzzleClient = $this->getHttpClient();
foreach ((array) $cached as $id => $data) {
$environments[$id] = new Environment($data, $endpoint, $guzzleClient, true);
}
}
self::$environmentsCache[$projectId] = $environments;
return $environments;
} | [
"public",
"function",
"getEnvironments",
"(",
"Project",
"$",
"project",
",",
"$",
"refresh",
"=",
"null",
",",
"$",
"events",
"=",
"true",
")",
"{",
"$",
"projectId",
"=",
"$",
"project",
"->",
"id",
";",
"if",
"(",
"!",
"$",
"refresh",
"&&",
"isset... | Return the user's environments.
@param Project $project The project.
@param bool|null $refresh Whether to refresh the list.
@param bool $events Whether to update Drush aliases if the list changes.
@return Environment[] The user's environments, keyed by ID. | [
"Return",
"the",
"user",
"s",
"environments",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L337-L380 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getEnvironment | public function getEnvironment($id, Project $project, $refresh = null, $tryMachineName = false)
{
// Statically cache not found environments.
$cacheKey = $project->id . ':' . $id . ($tryMachineName ? ':mn' : '');
if (!$refresh && isset(self::$notFound[$cacheKey])) {
return false;
}
$environments = $this->getEnvironments($project, $refresh);
// Look for the environment by ID.
if (isset($environments[$id])) {
return $environments[$id];
}
// Retry directly if the environment was not found in the cache.
if ($refresh === null) {
if ($environment = $project->getEnvironment($id)) {
// If the environment was found directly, the cache must be out
// of date.
$this->clearEnvironmentsCache($project->id);
return $environment;
}
}
// Look for the environment by machine name.
if ($tryMachineName) {
foreach ($environments as $environment) {
if ($environment->machine_name === $id) {
return $environment;
}
}
}
self::$notFound[$cacheKey] = true;
return false;
} | php | public function getEnvironment($id, Project $project, $refresh = null, $tryMachineName = false)
{
// Statically cache not found environments.
$cacheKey = $project->id . ':' . $id . ($tryMachineName ? ':mn' : '');
if (!$refresh && isset(self::$notFound[$cacheKey])) {
return false;
}
$environments = $this->getEnvironments($project, $refresh);
// Look for the environment by ID.
if (isset($environments[$id])) {
return $environments[$id];
}
// Retry directly if the environment was not found in the cache.
if ($refresh === null) {
if ($environment = $project->getEnvironment($id)) {
// If the environment was found directly, the cache must be out
// of date.
$this->clearEnvironmentsCache($project->id);
return $environment;
}
}
// Look for the environment by machine name.
if ($tryMachineName) {
foreach ($environments as $environment) {
if ($environment->machine_name === $id) {
return $environment;
}
}
}
self::$notFound[$cacheKey] = true;
return false;
} | [
"public",
"function",
"getEnvironment",
"(",
"$",
"id",
",",
"Project",
"$",
"project",
",",
"$",
"refresh",
"=",
"null",
",",
"$",
"tryMachineName",
"=",
"false",
")",
"{",
"// Statically cache not found environments.",
"$",
"cacheKey",
"=",
"$",
"project",
"... | Get a single environment.
@param string $id The environment ID to load.
@param Project $project The project.
@param bool|null $refresh Whether to refresh the list of environments.
@param bool $tryMachineName Whether to retry, treating the ID as a
machine name.
@return Environment|false The environment, or false if not found. | [
"Get",
"a",
"single",
"environment",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L393-L430 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getMyAccount | public function getMyAccount($reset = false)
{
$cacheKey = sprintf('%s:my-account', $this->sessionId);
if ($reset || !($info = $this->cache->fetch($cacheKey))) {
$info = $this->getClient()->getAccountInfo($reset);
$this->cache->save($cacheKey, $info, $this->config->get('api.users_ttl'));
}
return $info;
} | php | public function getMyAccount($reset = false)
{
$cacheKey = sprintf('%s:my-account', $this->sessionId);
if ($reset || !($info = $this->cache->fetch($cacheKey))) {
$info = $this->getClient()->getAccountInfo($reset);
$this->cache->save($cacheKey, $info, $this->config->get('api.users_ttl'));
}
return $info;
} | [
"public",
"function",
"getMyAccount",
"(",
"$",
"reset",
"=",
"false",
")",
"{",
"$",
"cacheKey",
"=",
"sprintf",
"(",
"'%s:my-account'",
",",
"$",
"this",
"->",
"sessionId",
")",
";",
"if",
"(",
"$",
"reset",
"||",
"!",
"(",
"$",
"info",
"=",
"$",
... | Get the current user's account info.
@param bool $reset
@return array
An array containing at least 'username', 'id', 'mail', and
'display_name'. | [
"Get",
"the",
"current",
"user",
"s",
"account",
"info",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L441-L450 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getAccount | public function getAccount(ProjectAccess $user, $reset = false)
{
if (isset(self::$accountsCache[$user->id]) && !$reset) {
return self::$accountsCache[$user->id];
}
$cacheKey = 'account:' . $user->id;
if ($reset || !($details = $this->cache->fetch($cacheKey))) {
$details = $user->getAccount()->getProperties();
$this->cache->save($cacheKey, $details, $this->config->get('api.users_ttl'));
self::$accountsCache[$user->id] = $details;
}
return $details;
} | php | public function getAccount(ProjectAccess $user, $reset = false)
{
if (isset(self::$accountsCache[$user->id]) && !$reset) {
return self::$accountsCache[$user->id];
}
$cacheKey = 'account:' . $user->id;
if ($reset || !($details = $this->cache->fetch($cacheKey))) {
$details = $user->getAccount()->getProperties();
$this->cache->save($cacheKey, $details, $this->config->get('api.users_ttl'));
self::$accountsCache[$user->id] = $details;
}
return $details;
} | [
"public",
"function",
"getAccount",
"(",
"ProjectAccess",
"$",
"user",
",",
"$",
"reset",
"=",
"false",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"accountsCache",
"[",
"$",
"user",
"->",
"id",
"]",
")",
"&&",
"!",
"$",
"reset",
")",
"{"... | Get a user's account info.
@param ProjectAccess $user
@param bool $reset
@return array
An array containing 'email' and 'display_name'. | [
"Get",
"a",
"user",
"s",
"account",
"info",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L461-L475 |
platformsh/platformsh-cli | src/Service/Api.php | Api.clearEnvironmentsCache | public function clearEnvironmentsCache($projectId)
{
$this->cache->delete('environments:' . $projectId);
unset(self::$environmentsCache[$projectId]);
foreach (array_keys(self::$notFound) as $key) {
if (strpos($key, $projectId . ':') === 0) {
unset(self::$notFound[$key]);
}
}
} | php | public function clearEnvironmentsCache($projectId)
{
$this->cache->delete('environments:' . $projectId);
unset(self::$environmentsCache[$projectId]);
foreach (array_keys(self::$notFound) as $key) {
if (strpos($key, $projectId . ':') === 0) {
unset(self::$notFound[$key]);
}
}
} | [
"public",
"function",
"clearEnvironmentsCache",
"(",
"$",
"projectId",
")",
"{",
"$",
"this",
"->",
"cache",
"->",
"delete",
"(",
"'environments:'",
".",
"$",
"projectId",
")",
";",
"unset",
"(",
"self",
"::",
"$",
"environmentsCache",
"[",
"$",
"projectId",... | Clear the environments cache for a project.
Use this after creating/deleting/updating environment(s).
@param string $projectId | [
"Clear",
"the",
"environments",
"cache",
"for",
"a",
"project",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L484-L493 |
platformsh/platformsh-cli | src/Service/Api.php | Api.clearProjectsCache | public function clearProjectsCache()
{
$this->cache->delete(sprintf('%s:projects', $this->sessionId));
$this->cache->delete(sprintf('%s:my-account', $this->sessionId));
} | php | public function clearProjectsCache()
{
$this->cache->delete(sprintf('%s:projects', $this->sessionId));
$this->cache->delete(sprintf('%s:my-account', $this->sessionId));
} | [
"public",
"function",
"clearProjectsCache",
"(",
")",
"{",
"$",
"this",
"->",
"cache",
"->",
"delete",
"(",
"sprintf",
"(",
"'%s:projects'",
",",
"$",
"this",
"->",
"sessionId",
")",
")",
";",
"$",
"this",
"->",
"cache",
"->",
"delete",
"(",
"sprintf",
... | Clear the projects cache. | [
"Clear",
"the",
"projects",
"cache",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L498-L502 |
platformsh/platformsh-cli | src/Service/Api.php | Api.sortResources | public static function sortResources(array &$resources, $propertyPath)
{
uasort($resources, function (ApiResource $a, ApiResource $b) use ($propertyPath) {
$valueA = static::getNestedProperty($a, $propertyPath, false);
$valueB = static::getNestedProperty($b, $propertyPath, false);
switch (gettype($valueA)) {
case 'string':
return strcasecmp($valueA, $valueB);
case 'integer':
case 'double':
case 'boolean':
return $valueA - $valueB;
}
return 0;
});
return $resources;
} | php | public static function sortResources(array &$resources, $propertyPath)
{
uasort($resources, function (ApiResource $a, ApiResource $b) use ($propertyPath) {
$valueA = static::getNestedProperty($a, $propertyPath, false);
$valueB = static::getNestedProperty($b, $propertyPath, false);
switch (gettype($valueA)) {
case 'string':
return strcasecmp($valueA, $valueB);
case 'integer':
case 'double':
case 'boolean':
return $valueA - $valueB;
}
return 0;
});
return $resources;
} | [
"public",
"static",
"function",
"sortResources",
"(",
"array",
"&",
"$",
"resources",
",",
"$",
"propertyPath",
")",
"{",
"uasort",
"(",
"$",
"resources",
",",
"function",
"(",
"ApiResource",
"$",
"a",
",",
"ApiResource",
"$",
"b",
")",
"use",
"(",
"$",
... | Sort resources.
@param ApiResource[] &$resources
@param string $propertyPath
@return ApiResource[] | [
"Sort",
"resources",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L512-L532 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getNestedProperty | public static function getNestedProperty(ApiResource $resource, $propertyPath, $lazyLoad = true)
{
if (!strpos($propertyPath, '.')) {
return $resource->getProperty($propertyPath, true, $lazyLoad);
}
$parents = explode('.', $propertyPath);
$propertyName = array_shift($parents);
$property = $resource->getProperty($propertyName, true, $lazyLoad);
if (!is_array($property)) {
throw new \InvalidArgumentException(sprintf(
'Invalid path "%s": the property "%s" is not an array.',
$propertyPath,
$propertyName
));
}
$value = NestedArrayUtil::getNestedArrayValue($property, $parents, $keyExists);
if (!$keyExists) {
throw new \InvalidArgumentException('Property not found: ' . $propertyPath);
}
return $value;
} | php | public static function getNestedProperty(ApiResource $resource, $propertyPath, $lazyLoad = true)
{
if (!strpos($propertyPath, '.')) {
return $resource->getProperty($propertyPath, true, $lazyLoad);
}
$parents = explode('.', $propertyPath);
$propertyName = array_shift($parents);
$property = $resource->getProperty($propertyName, true, $lazyLoad);
if (!is_array($property)) {
throw new \InvalidArgumentException(sprintf(
'Invalid path "%s": the property "%s" is not an array.',
$propertyPath,
$propertyName
));
}
$value = NestedArrayUtil::getNestedArrayValue($property, $parents, $keyExists);
if (!$keyExists) {
throw new \InvalidArgumentException('Property not found: ' . $propertyPath);
}
return $value;
} | [
"public",
"static",
"function",
"getNestedProperty",
"(",
"ApiResource",
"$",
"resource",
",",
"$",
"propertyPath",
",",
"$",
"lazyLoad",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"strpos",
"(",
"$",
"propertyPath",
",",
"'.'",
")",
")",
"{",
"return",
"$",... | Get a nested property of a resource, via a dot-separated string path.
@param ApiResource $resource
@param string $propertyPath
@param bool $lazyLoad
@throws \InvalidArgumentException if the property is not found.
@return mixed | [
"Get",
"a",
"nested",
"property",
"of",
"a",
"resource",
"via",
"a",
"dot",
"-",
"separated",
"string",
"path",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L545-L567 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getProjectAccesses | public function getProjectAccesses(Project $project, $reset = false)
{
if ($reset || !isset(self::$projectAccessesCache[$project->id])) {
self::$projectAccessesCache[$project->id] = $project->getUsers();
}
return self::$projectAccessesCache[$project->id];
} | php | public function getProjectAccesses(Project $project, $reset = false)
{
if ($reset || !isset(self::$projectAccessesCache[$project->id])) {
self::$projectAccessesCache[$project->id] = $project->getUsers();
}
return self::$projectAccessesCache[$project->id];
} | [
"public",
"function",
"getProjectAccesses",
"(",
"Project",
"$",
"project",
",",
"$",
"reset",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"reset",
"||",
"!",
"isset",
"(",
"self",
"::",
"$",
"projectAccessesCache",
"[",
"$",
"project",
"->",
"id",
"]",
")... | Load project users ("project access" records).
@param \Platformsh\Client\Model\Project $project
@param bool $reset
@return ProjectAccess[] | [
"Load",
"project",
"users",
"(",
"project",
"access",
"records",
")",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L585-L592 |
platformsh/platformsh-cli | src/Service/Api.php | Api.loadProjectAccessByEmail | public function loadProjectAccessByEmail(Project $project, $email, $reset = false)
{
foreach ($this->getProjectAccesses($project, $reset) as $user) {
$account = $this->getAccount($user);
if ($account['email'] === $email) {
return $user;
}
}
return false;
} | php | public function loadProjectAccessByEmail(Project $project, $email, $reset = false)
{
foreach ($this->getProjectAccesses($project, $reset) as $user) {
$account = $this->getAccount($user);
if ($account['email'] === $email) {
return $user;
}
}
return false;
} | [
"public",
"function",
"loadProjectAccessByEmail",
"(",
"Project",
"$",
"project",
",",
"$",
"email",
",",
"$",
"reset",
"=",
"false",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getProjectAccesses",
"(",
"$",
"project",
",",
"$",
"reset",
")",
"as",
"$... | Load a project user ("project access" record) by email address.
@param Project $project
@param string $email
@param bool $reset
@return ProjectAccess|false | [
"Load",
"a",
"project",
"user",
"(",
"project",
"access",
"record",
")",
"by",
"email",
"address",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L603-L613 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getProjectLabel | public function getProjectLabel(Project $project, $tag = 'info')
{
$title = $project->title;
$pattern = strlen($title) > 0 ? '%2$s (%3$s)' : '%3$s';
if ($tag !== false) {
$pattern = strlen($title) > 0 ? '<%1$s>%2$s</%1$s> (%3$s)' : '<%1$s>%3$s</%1$s>';
}
return sprintf($pattern, $tag, $title, $project->id);
} | php | public function getProjectLabel(Project $project, $tag = 'info')
{
$title = $project->title;
$pattern = strlen($title) > 0 ? '%2$s (%3$s)' : '%3$s';
if ($tag !== false) {
$pattern = strlen($title) > 0 ? '<%1$s>%2$s</%1$s> (%3$s)' : '<%1$s>%3$s</%1$s>';
}
return sprintf($pattern, $tag, $title, $project->id);
} | [
"public",
"function",
"getProjectLabel",
"(",
"Project",
"$",
"project",
",",
"$",
"tag",
"=",
"'info'",
")",
"{",
"$",
"title",
"=",
"$",
"project",
"->",
"title",
";",
"$",
"pattern",
"=",
"strlen",
"(",
"$",
"title",
")",
">",
"0",
"?",
"'%2$s (%3... | Returns a project label.
@param Project $project
@param string|false $tag
@return string | [
"Returns",
"a",
"project",
"label",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L623-L632 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getEnvironmentLabel | public function getEnvironmentLabel(Environment $environment, $tag = 'info')
{
$id = $environment->id;
$title = $environment->title;
$use_title = strlen($title) > 0 && $title !== $id;
$pattern = $use_title ? '%2$s (%3$s)' : '%3$s';
if ($tag !== false) {
$pattern = $use_title ? '<%1$s>%2$s</%1$s> (%3$s)' : '<%1$s>%3$s</%1$s>';
}
return sprintf($pattern, $tag, $title, $id);
} | php | public function getEnvironmentLabel(Environment $environment, $tag = 'info')
{
$id = $environment->id;
$title = $environment->title;
$use_title = strlen($title) > 0 && $title !== $id;
$pattern = $use_title ? '%2$s (%3$s)' : '%3$s';
if ($tag !== false) {
$pattern = $use_title ? '<%1$s>%2$s</%1$s> (%3$s)' : '<%1$s>%3$s</%1$s>';
}
return sprintf($pattern, $tag, $title, $id);
} | [
"public",
"function",
"getEnvironmentLabel",
"(",
"Environment",
"$",
"environment",
",",
"$",
"tag",
"=",
"'info'",
")",
"{",
"$",
"id",
"=",
"$",
"environment",
"->",
"id",
";",
"$",
"title",
"=",
"$",
"environment",
"->",
"title",
";",
"$",
"use_title... | Returns an environment label.
@param Environment $environment
@param string|false $tag
@return string | [
"Returns",
"an",
"environment",
"label",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L642-L653 |
platformsh/platformsh-cli | src/Service/Api.php | Api.matchPartialId | public function matchPartialId($id, array $resources, $name = 'Resource')
{
$matched = array_filter($resources, function (ApiResource $resource) use ($id) {
return strpos($resource->getProperty('id'), $id) === 0;
});
if (count($matched) > 1) {
$matchedIds = array_map(function (ApiResource $resource) {
return $resource->getProperty('id');
}, $matched);
throw new \InvalidArgumentException(sprintf(
'The partial ID "<error>%s</error>" is ambiguous; it matches the following %s IDs: %s',
$id,
strtolower($name),
"\n " . implode("\n ", $matchedIds)
));
} elseif (count($matched) === 0) {
throw new \InvalidArgumentException(sprintf('%s not found: "<error>%s</error>"', $name, $id));
}
return reset($matched);
} | php | public function matchPartialId($id, array $resources, $name = 'Resource')
{
$matched = array_filter($resources, function (ApiResource $resource) use ($id) {
return strpos($resource->getProperty('id'), $id) === 0;
});
if (count($matched) > 1) {
$matchedIds = array_map(function (ApiResource $resource) {
return $resource->getProperty('id');
}, $matched);
throw new \InvalidArgumentException(sprintf(
'The partial ID "<error>%s</error>" is ambiguous; it matches the following %s IDs: %s',
$id,
strtolower($name),
"\n " . implode("\n ", $matchedIds)
));
} elseif (count($matched) === 0) {
throw new \InvalidArgumentException(sprintf('%s not found: "<error>%s</error>"', $name, $id));
}
return reset($matched);
} | [
"public",
"function",
"matchPartialId",
"(",
"$",
"id",
",",
"array",
"$",
"resources",
",",
"$",
"name",
"=",
"'Resource'",
")",
"{",
"$",
"matched",
"=",
"array_filter",
"(",
"$",
"resources",
",",
"function",
"(",
"ApiResource",
"$",
"resource",
")",
... | Get a resource, matching on the beginning of the ID.
@param string $id
@param ApiResource[] $resources
@param string $name
@return ApiResource
The resource, if one (and only one) is matched. | [
"Get",
"a",
"resource",
"matching",
"on",
"the",
"beginning",
"of",
"the",
"ID",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L665-L686 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getAccessToken | public function getAccessToken()
{
$session = $this->getClient()->getConnector()->getSession();
$token = $session->get('accessToken');
$expires = $session->get('expires');
if (!$token || $expires < time()) {
// Force a connection to the API to ensure there is an access token.
$this->getMyAccount(true);
if (!$token = $session->get('accessToken')) {
throw new \RuntimeException('No access token found');
}
}
return $token;
} | php | public function getAccessToken()
{
$session = $this->getClient()->getConnector()->getSession();
$token = $session->get('accessToken');
$expires = $session->get('expires');
if (!$token || $expires < time()) {
// Force a connection to the API to ensure there is an access token.
$this->getMyAccount(true);
if (!$token = $session->get('accessToken')) {
throw new \RuntimeException('No access token found');
}
}
return $token;
} | [
"public",
"function",
"getAccessToken",
"(",
")",
"{",
"$",
"session",
"=",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"getConnector",
"(",
")",
"->",
"getSession",
"(",
")",
";",
"$",
"token",
"=",
"$",
"session",
"->",
"get",
"(",
"'accessToken'... | Returns the OAuth 2 access token.
@return string | [
"Returns",
"the",
"OAuth",
"2",
"access",
"token",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L693-L707 |
platformsh/platformsh-cli | src/Service/Api.php | Api.urlSort | public function urlSort($a, $b)
{
$result = 0;
foreach ([$a, $b] as $key => $url) {
if (parse_url($url, PHP_URL_SCHEME) === 'https') {
$result += $key === 0 ? -2 : 2;
}
}
$result += strlen($a) <= strlen($b) ? -1 : 1;
return $result;
} | php | public function urlSort($a, $b)
{
$result = 0;
foreach ([$a, $b] as $key => $url) {
if (parse_url($url, PHP_URL_SCHEME) === 'https') {
$result += $key === 0 ? -2 : 2;
}
}
$result += strlen($a) <= strlen($b) ? -1 : 1;
return $result;
} | [
"public",
"function",
"urlSort",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"$",
"result",
"=",
"0",
";",
"foreach",
"(",
"[",
"$",
"a",
",",
"$",
"b",
"]",
"as",
"$",
"key",
"=>",
"$",
"url",
")",
"{",
"if",
"(",
"parse_url",
"(",
"$",
"url",... | Sort URLs, preferring shorter ones with HTTPS.
@param string $a
@param string $b
@return int | [
"Sort",
"URLs",
"preferring",
"shorter",
"ones",
"with",
"HTTPS",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L717-L728 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getCurrentDeployment | public function getCurrentDeployment(Environment $environment, $refresh = false)
{
$cacheKey = implode(':', ['current-deployment', $environment->project, $environment->id]);
$data = $this->cache->fetch($cacheKey);
if ($data === false || $refresh) {
$deployment = $environment->getCurrentDeployment();
$data = $deployment->getData();
$data['_uri'] = $deployment->getUri();
$this->cache->save($cacheKey, $data, $this->config->get('api.environments_ttl'));
} else {
$deployment = new EnvironmentDeployment($data, $data['_uri'], $this->getHttpClient(), true);
}
return $deployment;
} | php | public function getCurrentDeployment(Environment $environment, $refresh = false)
{
$cacheKey = implode(':', ['current-deployment', $environment->project, $environment->id]);
$data = $this->cache->fetch($cacheKey);
if ($data === false || $refresh) {
$deployment = $environment->getCurrentDeployment();
$data = $deployment->getData();
$data['_uri'] = $deployment->getUri();
$this->cache->save($cacheKey, $data, $this->config->get('api.environments_ttl'));
} else {
$deployment = new EnvironmentDeployment($data, $data['_uri'], $this->getHttpClient(), true);
}
return $deployment;
} | [
"public",
"function",
"getCurrentDeployment",
"(",
"Environment",
"$",
"environment",
",",
"$",
"refresh",
"=",
"false",
")",
"{",
"$",
"cacheKey",
"=",
"implode",
"(",
"':'",
",",
"[",
"'current-deployment'",
",",
"$",
"environment",
"->",
"project",
",",
"... | Get the current deployment for an environment.
@param Environment $environment
@param bool $refresh
@return EnvironmentDeployment | [
"Get",
"the",
"current",
"deployment",
"for",
"an",
"environment",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L758-L772 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getDefaultEnvironmentId | public function getDefaultEnvironmentId(array $environments)
{
// If there is only one environment, use that.
if (count($environments) <= 1) {
$environment = reset($environments);
return $environment ? $environment->id : null;
}
// Check if there is only one "main" environment.
$main = array_filter($environments, function (Environment $environment) {
return $environment->is_main;
});
if (count($main) === 1) {
$environment = reset($main);
return $environment ? $environment->id : null;
}
// Check if there is a "master" environment.
if (isset($environments['master'])) {
return 'master';
}
return null;
} | php | public function getDefaultEnvironmentId(array $environments)
{
// If there is only one environment, use that.
if (count($environments) <= 1) {
$environment = reset($environments);
return $environment ? $environment->id : null;
}
// Check if there is only one "main" environment.
$main = array_filter($environments, function (Environment $environment) {
return $environment->is_main;
});
if (count($main) === 1) {
$environment = reset($main);
return $environment ? $environment->id : null;
}
// Check if there is a "master" environment.
if (isset($environments['master'])) {
return 'master';
}
return null;
} | [
"public",
"function",
"getDefaultEnvironmentId",
"(",
"array",
"$",
"environments",
")",
"{",
"// If there is only one environment, use that.",
"if",
"(",
"count",
"(",
"$",
"environments",
")",
"<=",
"1",
")",
"{",
"$",
"environment",
"=",
"reset",
"(",
"$",
"e... | Get the default environment in a list.
@param array $environments An array of environments, keyed by ID.
@return string|null | [
"Get",
"the",
"default",
"environment",
"in",
"a",
"list",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L781-L806 |
platformsh/platformsh-cli | src/Service/Api.php | Api.getSiteUrl | public function getSiteUrl(Environment $environment, $appName, EnvironmentDeployment $deployment = null)
{
$deployment = $deployment ?: $this->getCurrentDeployment($environment);
$routes = $deployment->routes;
$appUrls = [];
foreach ($routes as $url => $route) {
if ($route->type === 'upstream' && $route->__get('upstream') === $appName) {
$appUrls[] = $url;
}
}
usort($appUrls, [$this, 'urlSort']);
$siteUrl = reset($appUrls);
if ($siteUrl) {
return $siteUrl;
}
if ($environment->hasLink('public-url')) {
return $environment->getLink('public-url');
}
return null;
} | php | public function getSiteUrl(Environment $environment, $appName, EnvironmentDeployment $deployment = null)
{
$deployment = $deployment ?: $this->getCurrentDeployment($environment);
$routes = $deployment->routes;
$appUrls = [];
foreach ($routes as $url => $route) {
if ($route->type === 'upstream' && $route->__get('upstream') === $appName) {
$appUrls[] = $url;
}
}
usort($appUrls, [$this, 'urlSort']);
$siteUrl = reset($appUrls);
if ($siteUrl) {
return $siteUrl;
}
if ($environment->hasLink('public-url')) {
return $environment->getLink('public-url');
}
return null;
} | [
"public",
"function",
"getSiteUrl",
"(",
"Environment",
"$",
"environment",
",",
"$",
"appName",
",",
"EnvironmentDeployment",
"$",
"deployment",
"=",
"null",
")",
"{",
"$",
"deployment",
"=",
"$",
"deployment",
"?",
":",
"$",
"this",
"->",
"getCurrentDeployme... | Get the preferred site URL for an environment and app.
@param \Platformsh\Client\Model\Environment $environment
@param string $appName
@param \Platformsh\Client\Model\Deployment\EnvironmentDeployment|null $deployment
@return string|null | [
"Get",
"the",
"preferred",
"site",
"URL",
"for",
"an",
"environment",
"and",
"app",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L817-L837 |
platformsh/platformsh-cli | src/Service/Api.php | Api.on403 | private function on403(ErrorEvent $event)
{
$url = $event->getRequest()->getUrl();
$path = parse_url($url, PHP_URL_PATH);
if ($path && strpos($path, '/api/projects/') === 0) {
// Clear the environments cache for environment request errors.
if (preg_match('#^/api/projects/([^/]+?)/environments/#', $path, $matches)) {
$this->clearEnvironmentsCache($matches[1]);
}
// Clear the projects cache for other project request errors.
if (preg_match('#^/api/projects/([^/]+?)[/$]/#', $path, $matches)) {
$this->clearProjectsCache();
}
}
} | php | private function on403(ErrorEvent $event)
{
$url = $event->getRequest()->getUrl();
$path = parse_url($url, PHP_URL_PATH);
if ($path && strpos($path, '/api/projects/') === 0) {
// Clear the environments cache for environment request errors.
if (preg_match('#^/api/projects/([^/]+?)/environments/#', $path, $matches)) {
$this->clearEnvironmentsCache($matches[1]);
}
// Clear the projects cache for other project request errors.
if (preg_match('#^/api/projects/([^/]+?)[/$]/#', $path, $matches)) {
$this->clearProjectsCache();
}
}
} | [
"private",
"function",
"on403",
"(",
"ErrorEvent",
"$",
"event",
")",
"{",
"$",
"url",
"=",
"$",
"event",
"->",
"getRequest",
"(",
")",
"->",
"getUrl",
"(",
")",
";",
"$",
"path",
"=",
"parse_url",
"(",
"$",
"url",
",",
"PHP_URL_PATH",
")",
";",
"i... | React on an API 403 request.
@param \GuzzleHttp\Event\ErrorEvent $event | [
"React",
"on",
"an",
"API",
"403",
"request",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Api.php#L844-L858 |
platformsh/platformsh-cli | src/Service/Identifier.php | Identifier.identify | public function identify($url)
{
$result = $this->parseProjectId($url);
if (empty($result['projectId']) && strpos($url, '.') !== false) {
$result = $this->identifyFromHeaders($url);
}
if (empty($result['projectId'])) {
throw new InvalidArgumentException('Failed to identify project ID from URL: <error>' . $url . '</error>');
}
return $result + ['environmentId' => null, 'host' => null, 'appId' => null];
} | php | public function identify($url)
{
$result = $this->parseProjectId($url);
if (empty($result['projectId']) && strpos($url, '.') !== false) {
$result = $this->identifyFromHeaders($url);
}
if (empty($result['projectId'])) {
throw new InvalidArgumentException('Failed to identify project ID from URL: <error>' . $url . '</error>');
}
return $result + ['environmentId' => null, 'host' => null, 'appId' => null];
} | [
"public",
"function",
"identify",
"(",
"$",
"url",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"parseProjectId",
"(",
"$",
"url",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"result",
"[",
"'projectId'",
"]",
")",
"&&",
"strpos",
"(",
"$",
"url",
... | Identify a project from an ID or URL.
@param string $url
@return array
An array containing keys 'projectId', 'environmentId', 'host', and
'appId'. At least the 'projectId' will be populated. | [
"Identify",
"a",
"project",
"from",
"an",
"ID",
"or",
"URL",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Identifier.php#L47-L58 |
platformsh/platformsh-cli | src/Service/Identifier.php | Identifier.parseProjectId | private function parseProjectId($url)
{
$result = [];
// If it's a plain alphanumeric string, then it's an ID already.
if (!preg_match('/\W/', $url)) {
$result['projectId'] = $url;
return $result;
}
$urlParts = parse_url($url);
if ($urlParts === false || empty($urlParts['host'])) {
return $result;
}
$this->debug('Parsing URL to determine project ID: ' . $url);
$host = $urlParts['host'];
$path = isset($urlParts['path']) ? $urlParts['path'] : '';
$fragment = isset($urlParts['fragment']) ? $urlParts['fragment'] : '';
$site_domains_pattern = '(' . implode('|', array_map('preg_quote', $this->config->get('detection.site_domains'))) . ')';
$site_pattern = '/\-\w+\.[a-z]{2}(\-[0-9])?\.' . $site_domains_pattern . '$/';
if (preg_match($site_pattern, $host)) {
list($env_project_app,) = explode('.', $host, 2);
if (($tripleDashPos = strrpos($env_project_app, '---')) !== false) {
$env_project_app = substr($env_project_app, $tripleDashPos + 3);
}
if (($doubleDashPos = strrpos($env_project_app, '--')) !== false) {
$env_project = substr($env_project_app, 0, $doubleDashPos);
$result['appId'] = substr($env_project_app, $doubleDashPos + 2);
} else {
$env_project = $env_project_app;
}
if (($dashPos = strrpos($env_project, '-')) !== false) {
$result['projectId'] = substr($env_project, $dashPos + 1);
$result['environmentId'] = substr($env_project, 0, $dashPos);
}
return $result;
}
if (strpos($path, '/projects/') !== false || strpos($fragment, '/projects/') !== false) {
$result['host'] = $host;
$result['projectId'] = basename(preg_replace('#/projects(/\w+)/?.*$#', '$1', $url));
if (preg_match('#/environments(/[^/]+)/?.*$#', $url, $matches)) {
$result['environmentId'] = rawurldecode(basename($matches[1]));
}
return $result;
}
if ($this->config->has('detection.console_domain')
&& $host === $this->config->get('detection.console_domain')
&& preg_match('#^/[a-z0-9-]+/([a-z0-9-]+)(/([^/]+))?#', $path, $matches)) {
$result['projectId'] = $matches[1];
if (isset($matches[3])) {
$result['environmentId'] = rawurldecode($matches[3]);
}
return $result;
}
return $result;
} | php | private function parseProjectId($url)
{
$result = [];
// If it's a plain alphanumeric string, then it's an ID already.
if (!preg_match('/\W/', $url)) {
$result['projectId'] = $url;
return $result;
}
$urlParts = parse_url($url);
if ($urlParts === false || empty($urlParts['host'])) {
return $result;
}
$this->debug('Parsing URL to determine project ID: ' . $url);
$host = $urlParts['host'];
$path = isset($urlParts['path']) ? $urlParts['path'] : '';
$fragment = isset($urlParts['fragment']) ? $urlParts['fragment'] : '';
$site_domains_pattern = '(' . implode('|', array_map('preg_quote', $this->config->get('detection.site_domains'))) . ')';
$site_pattern = '/\-\w+\.[a-z]{2}(\-[0-9])?\.' . $site_domains_pattern . '$/';
if (preg_match($site_pattern, $host)) {
list($env_project_app,) = explode('.', $host, 2);
if (($tripleDashPos = strrpos($env_project_app, '---')) !== false) {
$env_project_app = substr($env_project_app, $tripleDashPos + 3);
}
if (($doubleDashPos = strrpos($env_project_app, '--')) !== false) {
$env_project = substr($env_project_app, 0, $doubleDashPos);
$result['appId'] = substr($env_project_app, $doubleDashPos + 2);
} else {
$env_project = $env_project_app;
}
if (($dashPos = strrpos($env_project, '-')) !== false) {
$result['projectId'] = substr($env_project, $dashPos + 1);
$result['environmentId'] = substr($env_project, 0, $dashPos);
}
return $result;
}
if (strpos($path, '/projects/') !== false || strpos($fragment, '/projects/') !== false) {
$result['host'] = $host;
$result['projectId'] = basename(preg_replace('#/projects(/\w+)/?.*$#', '$1', $url));
if (preg_match('#/environments(/[^/]+)/?.*$#', $url, $matches)) {
$result['environmentId'] = rawurldecode(basename($matches[1]));
}
return $result;
}
if ($this->config->has('detection.console_domain')
&& $host === $this->config->get('detection.console_domain')
&& preg_match('#^/[a-z0-9-]+/([a-z0-9-]+)(/([^/]+))?#', $path, $matches)) {
$result['projectId'] = $matches[1];
if (isset($matches[3])) {
$result['environmentId'] = rawurldecode($matches[3]);
}
return $result;
}
return $result;
} | [
"private",
"function",
"parseProjectId",
"(",
"$",
"url",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"// If it's a plain alphanumeric string, then it's an ID already.",
"if",
"(",
"!",
"preg_match",
"(",
"'/\\W/'",
",",
"$",
"url",
")",
")",
"{",
"$",
"resul... | Parse the project ID and possibly other details from a provided URL.
@param string $url
A web UI, API, or public URL of the project.
@return array | [
"Parse",
"the",
"project",
"ID",
"and",
"possibly",
"other",
"details",
"from",
"a",
"provided",
"URL",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Identifier.php#L68-L134 |
platformsh/platformsh-cli | src/Service/Identifier.php | Identifier.identifyFromHeaders | private function identifyFromHeaders($url)
{
if (!strpos($url, '.')) {
throw new \InvalidArgumentException('Invalid URL: ' . $url);
}
if (strpos($url, '//') === false) {
$url = 'https://' . $url;
}
$result = ['projectId' => null, 'environmentId' => null];
$cluster = $this->getClusterHeader($url);
if (!empty($cluster)) {
$this->debug('Identified project cluster: ' . $cluster);
list($result['projectId'], $result['environmentId']) = explode('-', $cluster, 2);
}
return $result;
} | php | private function identifyFromHeaders($url)
{
if (!strpos($url, '.')) {
throw new \InvalidArgumentException('Invalid URL: ' . $url);
}
if (strpos($url, '//') === false) {
$url = 'https://' . $url;
}
$result = ['projectId' => null, 'environmentId' => null];
$cluster = $this->getClusterHeader($url);
if (!empty($cluster)) {
$this->debug('Identified project cluster: ' . $cluster);
list($result['projectId'], $result['environmentId']) = explode('-', $cluster, 2);
}
return $result;
} | [
"private",
"function",
"identifyFromHeaders",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"!",
"strpos",
"(",
"$",
"url",
",",
"'.'",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Invalid URL: '",
".",
"$",
"url",
")",
";",
"}",
"if... | Identify a project and environment from a URL's response headers.
@param string $url
@return array | [
"Identify",
"a",
"project",
"and",
"environment",
"from",
"a",
"URL",
"s",
"response",
"headers",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Identifier.php#L143-L159 |
platformsh/platformsh-cli | src/Service/Identifier.php | Identifier.getClusterHeader | private function getClusterHeader($url)
{
$cacheKey = 'project-cluster:' . $url;
$cluster = $this->cache ? $this->cache->fetch($cacheKey) : false;
if ($cluster === false) {
$this->debug('Making a HEAD request to identify project from URL: ' . $url);
try {
$response = $this->api->getHttpClient()->head($url, [
'auth' => false,
'timeout' => 5,
'connect_timeout' => 5,
'allow_redirects' => false,
]);
} catch (RequestException $e) {
// We can use a failed response, if one exists.
if ($e->getResponse()) {
$response = $e->getResponse();
} else {
$this->debug($e->getMessage());
return false;
}
}
$cluster = $response->getHeaderAsArray($this->config->get('service.header_prefix') . '-cluster');
$canCache = !empty($cluster)
|| ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300);
if ($canCache) {
$this->cache->save($cacheKey, $cluster, 86400);
}
}
return is_array($cluster) ? reset($cluster) : false;
} | php | private function getClusterHeader($url)
{
$cacheKey = 'project-cluster:' . $url;
$cluster = $this->cache ? $this->cache->fetch($cacheKey) : false;
if ($cluster === false) {
$this->debug('Making a HEAD request to identify project from URL: ' . $url);
try {
$response = $this->api->getHttpClient()->head($url, [
'auth' => false,
'timeout' => 5,
'connect_timeout' => 5,
'allow_redirects' => false,
]);
} catch (RequestException $e) {
// We can use a failed response, if one exists.
if ($e->getResponse()) {
$response = $e->getResponse();
} else {
$this->debug($e->getMessage());
return false;
}
}
$cluster = $response->getHeaderAsArray($this->config->get('service.header_prefix') . '-cluster');
$canCache = !empty($cluster)
|| ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300);
if ($canCache) {
$this->cache->save($cacheKey, $cluster, 86400);
}
}
return is_array($cluster) ? reset($cluster) : false;
} | [
"private",
"function",
"getClusterHeader",
"(",
"$",
"url",
")",
"{",
"$",
"cacheKey",
"=",
"'project-cluster:'",
".",
"$",
"url",
";",
"$",
"cluster",
"=",
"$",
"this",
"->",
"cache",
"?",
"$",
"this",
"->",
"cache",
"->",
"fetch",
"(",
"$",
"cacheKey... | Get a project cluster from its URL.
@param string $url
@return string|false | [
"Get",
"a",
"project",
"cluster",
"from",
"its",
"URL",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Identifier.php#L168-L200 |
platformsh/platformsh-cli | src/Command/Route/RouteListCommand.php | RouteListCommand.configure | protected function configure()
{
$this
->setName('route:list')
->setAliases(['routes'])
->setDescription('List all routes for an environment')
->addArgument('environment', InputArgument::OPTIONAL, 'The environment ID');
$this->setHiddenAliases(['environment:routes']);
Table::configureInput($this->getDefinition());
$this->addProjectOption()
->addEnvironmentOption();
} | php | protected function configure()
{
$this
->setName('route:list')
->setAliases(['routes'])
->setDescription('List all routes for an environment')
->addArgument('environment', InputArgument::OPTIONAL, 'The environment ID');
$this->setHiddenAliases(['environment:routes']);
Table::configureInput($this->getDefinition());
$this->addProjectOption()
->addEnvironmentOption();
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'route:list'",
")",
"->",
"setAliases",
"(",
"[",
"'routes'",
"]",
")",
"->",
"setDescription",
"(",
"'List all routes for an environment'",
")",
"->",
"addArgument",
"(",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Route/RouteListCommand.php#L16-L27 |
platformsh/platformsh-cli | src/Command/Variable/VariableCommandBase.php | VariableCommandBase.getRequestedLevel | protected function getRequestedLevel(InputInterface $input)
{
$str = $input->getOption('level');
if (empty($str)) {
return null;
}
foreach ([self::LEVEL_PROJECT, self::LEVEL_ENVIRONMENT] as $validLevel) {
if (stripos($validLevel, $str) === 0) {
return $validLevel;
}
}
throw new InvalidArgumentException('Invalid level: ' . $str);
} | php | protected function getRequestedLevel(InputInterface $input)
{
$str = $input->getOption('level');
if (empty($str)) {
return null;
}
foreach ([self::LEVEL_PROJECT, self::LEVEL_ENVIRONMENT] as $validLevel) {
if (stripos($validLevel, $str) === 0) {
return $validLevel;
}
}
throw new InvalidArgumentException('Invalid level: ' . $str);
} | [
"protected",
"function",
"getRequestedLevel",
"(",
"InputInterface",
"$",
"input",
")",
"{",
"$",
"str",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'level'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"str",
")",
")",
"{",
"return",
"null",
";",
"}",
"... | Get the requested variable level.
@param InputInterface $input
@return string|null | [
"Get",
"the",
"requested",
"variable",
"level",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Variable/VariableCommandBase.php#L49-L61 |
platformsh/platformsh-cli | src/Command/Variable/VariableCommandBase.php | VariableCommandBase.getExistingVariable | protected function getExistingVariable($name, $level = null, $messages = true)
{
$output = $messages ? $this->stdErr : new NullOutput();
if ($level === self::LEVEL_ENVIRONMENT || ($this->hasSelectedEnvironment() && $level === null)) {
$variable = $this->getSelectedEnvironment()->getVariable($name);
if ($variable !== false) {
if ($level === null && $this->getSelectedProject()->getVariable($name)) {
$output->writeln('Variable found at both project and environment levels: <error>' . $name . '</error>');
$output->writeln("To select a variable, use the --level option ('" . self::LEVEL_PROJECT . "' or '" . self::LEVEL_ENVIRONMENT . "').");
return false;
}
return $variable;
}
}
if ($level !== self::LEVEL_ENVIRONMENT) {
$variable = $this->getSelectedProject()->getVariable($name);
if ($variable !== false) {
return $variable;
}
}
$output->writeln('Variable not found: <error>' . $name . '</error>');
return false;
} | php | protected function getExistingVariable($name, $level = null, $messages = true)
{
$output = $messages ? $this->stdErr : new NullOutput();
if ($level === self::LEVEL_ENVIRONMENT || ($this->hasSelectedEnvironment() && $level === null)) {
$variable = $this->getSelectedEnvironment()->getVariable($name);
if ($variable !== false) {
if ($level === null && $this->getSelectedProject()->getVariable($name)) {
$output->writeln('Variable found at both project and environment levels: <error>' . $name . '</error>');
$output->writeln("To select a variable, use the --level option ('" . self::LEVEL_PROJECT . "' or '" . self::LEVEL_ENVIRONMENT . "').");
return false;
}
return $variable;
}
}
if ($level !== self::LEVEL_ENVIRONMENT) {
$variable = $this->getSelectedProject()->getVariable($name);
if ($variable !== false) {
return $variable;
}
}
$output->writeln('Variable not found: <error>' . $name . '</error>');
return false;
} | [
"protected",
"function",
"getExistingVariable",
"(",
"$",
"name",
",",
"$",
"level",
"=",
"null",
",",
"$",
"messages",
"=",
"true",
")",
"{",
"$",
"output",
"=",
"$",
"messages",
"?",
"$",
"this",
"->",
"stdErr",
":",
"new",
"NullOutput",
"(",
")",
... | Finds an existing variable by name.
@param string $name
@param string|null $level
@param bool $messages Whether to print error messages to
$this->stdErr if the variable is not found.
@return \Platformsh\Client\Model\ProjectLevelVariable|\Platformsh\Client\Model\Variable|false | [
"Finds",
"an",
"existing",
"variable",
"by",
"name",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Variable/VariableCommandBase.php#L73-L99 |
platformsh/platformsh-cli | src/Command/Variable/VariableCommandBase.php | VariableCommandBase.displayVariable | protected function displayVariable(ApiResource $variable)
{
/** @var \Platformsh\Cli\Service\Table $table */
$table = $this->getService('table');
/** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */
$formatter = $this->getService('property_formatter');
$properties = $variable->getProperties();
$properties['level'] = $this->getVariableLevel($variable);
$headings = [];
$values = [];
foreach ($properties as $key => $value) {
$headings[] = new AdaptiveTableCell($key, ['wrap' => false]);
if ($key === 'value') {
$value = wordwrap($value, 80, "\n", true);
}
$values[] = $formatter->format($value, $key);
}
$table->renderSimple($values, $headings);
} | php | protected function displayVariable(ApiResource $variable)
{
/** @var \Platformsh\Cli\Service\Table $table */
$table = $this->getService('table');
/** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */
$formatter = $this->getService('property_formatter');
$properties = $variable->getProperties();
$properties['level'] = $this->getVariableLevel($variable);
$headings = [];
$values = [];
foreach ($properties as $key => $value) {
$headings[] = new AdaptiveTableCell($key, ['wrap' => false]);
if ($key === 'value') {
$value = wordwrap($value, 80, "\n", true);
}
$values[] = $formatter->format($value, $key);
}
$table->renderSimple($values, $headings);
} | [
"protected",
"function",
"displayVariable",
"(",
"ApiResource",
"$",
"variable",
")",
"{",
"/** @var \\Platformsh\\Cli\\Service\\Table $table */",
"$",
"table",
"=",
"$",
"this",
"->",
"getService",
"(",
"'table'",
")",
";",
"/** @var \\Platformsh\\Cli\\Service\\PropertyFor... | Display a variable to stdout.
@param \Platformsh\Client\Model\Resource $variable | [
"Display",
"a",
"variable",
"to",
"stdout",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Variable/VariableCommandBase.php#L106-L126 |
platformsh/platformsh-cli | src/Command/Variable/VariableCommandBase.php | VariableCommandBase.getVariableLevel | protected function getVariableLevel(ApiResource $variable)
{
if ($variable instanceof EnvironmentLevelVariable) {
return self::LEVEL_ENVIRONMENT;
} elseif ($variable instanceof ProjectLevelVariable) {
return self::LEVEL_PROJECT;
}
throw new \RuntimeException('Variable level not found');
} | php | protected function getVariableLevel(ApiResource $variable)
{
if ($variable instanceof EnvironmentLevelVariable) {
return self::LEVEL_ENVIRONMENT;
} elseif ($variable instanceof ProjectLevelVariable) {
return self::LEVEL_PROJECT;
}
throw new \RuntimeException('Variable level not found');
} | [
"protected",
"function",
"getVariableLevel",
"(",
"ApiResource",
"$",
"variable",
")",
"{",
"if",
"(",
"$",
"variable",
"instanceof",
"EnvironmentLevelVariable",
")",
"{",
"return",
"self",
"::",
"LEVEL_ENVIRONMENT",
";",
"}",
"elseif",
"(",
"$",
"variable",
"in... | @param ApiResource $variable
@return string | [
"@param",
"ApiResource",
"$variable"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Variable/VariableCommandBase.php#L133-L141 |
platformsh/platformsh-cli | src/Command/MultiCommand.php | MultiCommand.showDialogChecklist | protected function showDialogChecklist(array $options, $text = 'Choose item(s)')
{
$width = 80;
$height = 20;
$listHeight = 20;
$command = sprintf(
'dialog --separate-output --checklist %s %d %d %d',
escapeshellarg($text),
$height,
$width,
$listHeight
);
foreach ($options as $tag => $option) {
$command .= sprintf(' %s %s off', escapeshellarg($tag), escapeshellarg($option));
}
$dialogRc = file_get_contents(CLI_ROOT . '/resources/console/dialogrc');
$dialogRcFile = $this->config()->getWritableUserDir() . '/dialogrc';
if ($dialogRc !== false && (file_exists($dialogRcFile) || file_put_contents($dialogRcFile, $dialogRc))) {
putenv('DIALOGRC=' . $dialogRcFile);
}
$pipes = [2 => null];
$process = proc_open($command, [
2 => array('pipe', 'w'),
], $pipes);
// Wait for and read result.
$result = array_filter(explode("\n", trim(stream_get_contents($pipes[2]))));
// Close handles.
if (is_resource($pipes[2])) {
fclose($pipes[2]);
}
proc_close($process);
$this->stdErr->writeln('');
return $result;
} | php | protected function showDialogChecklist(array $options, $text = 'Choose item(s)')
{
$width = 80;
$height = 20;
$listHeight = 20;
$command = sprintf(
'dialog --separate-output --checklist %s %d %d %d',
escapeshellarg($text),
$height,
$width,
$listHeight
);
foreach ($options as $tag => $option) {
$command .= sprintf(' %s %s off', escapeshellarg($tag), escapeshellarg($option));
}
$dialogRc = file_get_contents(CLI_ROOT . '/resources/console/dialogrc');
$dialogRcFile = $this->config()->getWritableUserDir() . '/dialogrc';
if ($dialogRc !== false && (file_exists($dialogRcFile) || file_put_contents($dialogRcFile, $dialogRc))) {
putenv('DIALOGRC=' . $dialogRcFile);
}
$pipes = [2 => null];
$process = proc_open($command, [
2 => array('pipe', 'w'),
], $pipes);
// Wait for and read result.
$result = array_filter(explode("\n", trim(stream_get_contents($pipes[2]))));
// Close handles.
if (is_resource($pipes[2])) {
fclose($pipes[2]);
}
proc_close($process);
$this->stdErr->writeln('');
return $result;
} | [
"protected",
"function",
"showDialogChecklist",
"(",
"array",
"$",
"options",
",",
"$",
"text",
"=",
"'Choose item(s)'",
")",
"{",
"$",
"width",
"=",
"80",
";",
"$",
"height",
"=",
"20",
";",
"$",
"listHeight",
"=",
"20",
";",
"$",
"command",
"=",
"spr... | Show a checklist using the dialog utility.
@param string $text
@param array $options
@return array | [
"Show",
"a",
"checklist",
"using",
"the",
"dialog",
"utility",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/MultiCommand.php#L106-L146 |
platformsh/platformsh-cli | src/Command/MultiCommand.php | MultiCommand.getAllProjects | protected function getAllProjects(InputInterface $input)
{
$projects = $this->api()->getProjects();
if ($input->getOption('sort')) {
$this->api()->sortResources($projects, $input->getOption('sort'));
}
if ($input->getOption('reverse')) {
$projects = array_reverse($projects, true);
}
return $projects;
} | php | protected function getAllProjects(InputInterface $input)
{
$projects = $this->api()->getProjects();
if ($input->getOption('sort')) {
$this->api()->sortResources($projects, $input->getOption('sort'));
}
if ($input->getOption('reverse')) {
$projects = array_reverse($projects, true);
}
return $projects;
} | [
"protected",
"function",
"getAllProjects",
"(",
"InputInterface",
"$",
"input",
")",
"{",
"$",
"projects",
"=",
"$",
"this",
"->",
"api",
"(",
")",
"->",
"getProjects",
"(",
")",
";",
"if",
"(",
"$",
"input",
"->",
"getOption",
"(",
"'sort'",
")",
")",... | Get a list of the user's projects, sorted according to the input.
@param InputInterface $input
@return \Platformsh\Client\Model\Project[] | [
"Get",
"a",
"list",
"of",
"the",
"user",
"s",
"projects",
"sorted",
"according",
"to",
"the",
"input",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/MultiCommand.php#L155-L166 |
platformsh/platformsh-cli | src/Command/MultiCommand.php | MultiCommand.getSelectedProjects | protected function getSelectedProjects(InputInterface $input)
{
$projectList = $input->getOption('projects');
/** @var \Platformsh\Cli\Service\Identifier $identifier */
$identifier = $this->getService('identifier');
if (!empty($projectList)) {
$missing = [];
$selected = [];
foreach ($this->splitProjectList($projectList) as $projectId) {
try {
$result = $identifier->identify($projectId);
} catch (InvalidArgumentException $e) {
$missing[] = $projectId;
continue;
}
$project = $this->api()->getProject($result['projectId'], $result['host']);
if ($project !== false) {
$selected[$project->id] = $project;
} else {
$missing[] = $projectId;
}
}
if (!empty($missing)) {
$this->stdErr->writeln(sprintf('Project ID(s) not found: <error>%s</error>', implode(', ', $missing)));
return false;
}
return $selected;
}
if (!$input->isInteractive()) {
$this->stdErr->writeln('In non-interactive mode, the --projects option must be specified.');
return false;
}
/** @var \Platformsh\Cli\Service\Shell $shell */
$shell = $this->getService('shell');
if (!$shell->commandExists('dialog')) {
$this->stdErr->writeln('The "dialog" utility is required for interactive use.');
$this->stdErr->writeln('You can specify projects via the --projects option.');
return false;
}
$projects = $this->getAllProjects($input);
$projectOptions = [];
foreach ($projects as $project) {
$projectOptions[$project->id] = $project->title ?: $project->id;
}
$projectIds = $this->showDialogChecklist($projectOptions, 'Choose one or more projects');
if (empty($projectIds)) {
return false;
}
$selected = array_intersect_key($projects, array_flip($projectIds));
$this->stdErr->writeln('Selected project(s): ' . implode(',', array_keys($selected)));
$this->stdErr->writeln('');
return $selected;
} | php | protected function getSelectedProjects(InputInterface $input)
{
$projectList = $input->getOption('projects');
/** @var \Platformsh\Cli\Service\Identifier $identifier */
$identifier = $this->getService('identifier');
if (!empty($projectList)) {
$missing = [];
$selected = [];
foreach ($this->splitProjectList($projectList) as $projectId) {
try {
$result = $identifier->identify($projectId);
} catch (InvalidArgumentException $e) {
$missing[] = $projectId;
continue;
}
$project = $this->api()->getProject($result['projectId'], $result['host']);
if ($project !== false) {
$selected[$project->id] = $project;
} else {
$missing[] = $projectId;
}
}
if (!empty($missing)) {
$this->stdErr->writeln(sprintf('Project ID(s) not found: <error>%s</error>', implode(', ', $missing)));
return false;
}
return $selected;
}
if (!$input->isInteractive()) {
$this->stdErr->writeln('In non-interactive mode, the --projects option must be specified.');
return false;
}
/** @var \Platformsh\Cli\Service\Shell $shell */
$shell = $this->getService('shell');
if (!$shell->commandExists('dialog')) {
$this->stdErr->writeln('The "dialog" utility is required for interactive use.');
$this->stdErr->writeln('You can specify projects via the --projects option.');
return false;
}
$projects = $this->getAllProjects($input);
$projectOptions = [];
foreach ($projects as $project) {
$projectOptions[$project->id] = $project->title ?: $project->id;
}
$projectIds = $this->showDialogChecklist($projectOptions, 'Choose one or more projects');
if (empty($projectIds)) {
return false;
}
$selected = array_intersect_key($projects, array_flip($projectIds));
$this->stdErr->writeln('Selected project(s): ' . implode(',', array_keys($selected)));
$this->stdErr->writeln('');
return $selected;
} | [
"protected",
"function",
"getSelectedProjects",
"(",
"InputInterface",
"$",
"input",
")",
"{",
"$",
"projectList",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'projects'",
")",
";",
"/** @var \\Platformsh\\Cli\\Service\\Identifier $identifier */",
"$",
"identifier",
"="... | Get the projects selected by the user.
Projects can be specified via the command-line option --projects (as a
list of project IDs) or, if possible, the user will be prompted with a
checklist via the 'dialog' utility.
@param InputInterface $input
@return \Platformsh\Client\Model\Project[]|false
An array of projects, or false on error. | [
"Get",
"the",
"projects",
"selected",
"by",
"the",
"user",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/MultiCommand.php#L180-L240 |
platformsh/platformsh-cli | src/Command/MultiCommand.php | MultiCommand.completeArgumentValues | public function completeArgumentValues($argumentName, CompletionContext $context)
{
if ($argumentName === 'cmd') {
$commandNames = [];
foreach ($this->getApplication()->all() as $command) {
if ($command instanceof MultiAwareInterface
&& $command->canBeRunMultipleTimes()
&& $command->getDefinition()->hasOption('project')) {
$commandNames[] = $command->getName();
}
}
return $commandNames;
}
return [];
} | php | public function completeArgumentValues($argumentName, CompletionContext $context)
{
if ($argumentName === 'cmd') {
$commandNames = [];
foreach ($this->getApplication()->all() as $command) {
if ($command instanceof MultiAwareInterface
&& $command->canBeRunMultipleTimes()
&& $command->getDefinition()->hasOption('project')) {
$commandNames[] = $command->getName();
}
}
return $commandNames;
}
return [];
} | [
"public",
"function",
"completeArgumentValues",
"(",
"$",
"argumentName",
",",
"CompletionContext",
"$",
"context",
")",
"{",
"if",
"(",
"$",
"argumentName",
"===",
"'cmd'",
")",
"{",
"$",
"commandNames",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"-... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/MultiCommand.php#L265-L281 |
platformsh/platformsh-cli | src/Command/Db/DbSizeCommand.php | DbSizeCommand.psqlQuery | private function psqlQuery(array $database)
{
// I couldn't find a way to run the SUM directly in the database query...
$query = 'SELECT'
. ' sum(pg_relation_size(pg_class.oid))::bigint AS size'
. ' FROM pg_class'
. ' LEFT OUTER JOIN pg_namespace ON (pg_namespace.oid = pg_class.relnamespace)'
. ' GROUP BY pg_class.relkind, nspname'
. ' ORDER BY sum(pg_relation_size(pg_class.oid)) DESC;';
/** @var \Platformsh\Cli\Service\Relationships $relationships */
$relationships = $this->getService('relationships');
$dbUrl = $relationships->getDbCommandArgs('psql', $database, '');
return sprintf(
"psql --echo-hidden -t --no-align %s -c '%s'",
$dbUrl,
$query
);
} | php | private function psqlQuery(array $database)
{
// I couldn't find a way to run the SUM directly in the database query...
$query = 'SELECT'
. ' sum(pg_relation_size(pg_class.oid))::bigint AS size'
. ' FROM pg_class'
. ' LEFT OUTER JOIN pg_namespace ON (pg_namespace.oid = pg_class.relnamespace)'
. ' GROUP BY pg_class.relkind, nspname'
. ' ORDER BY sum(pg_relation_size(pg_class.oid)) DESC;';
/** @var \Platformsh\Cli\Service\Relationships $relationships */
$relationships = $this->getService('relationships');
$dbUrl = $relationships->getDbCommandArgs('psql', $database, '');
return sprintf(
"psql --echo-hidden -t --no-align %s -c '%s'",
$dbUrl,
$query
);
} | [
"private",
"function",
"psqlQuery",
"(",
"array",
"$",
"database",
")",
"{",
"// I couldn't find a way to run the SUM directly in the database query...",
"$",
"query",
"=",
"'SELECT'",
".",
"' sum(pg_relation_size(pg_class.oid))::bigint AS size'",
".",
"' FROM pg_class'",
".",
... | Returns a command to query disk usage for a PostgreSQL database.
@param array $database The database connection details.
@return string | [
"Returns",
"a",
"command",
"to",
"query",
"disk",
"usage",
"for",
"a",
"PostgreSQL",
"database",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Db/DbSizeCommand.php#L142-L161 |
platformsh/platformsh-cli | src/Command/Db/DbSizeCommand.php | DbSizeCommand.mysqlQuery | private function mysqlQuery(array $database)
{
$query = 'SELECT'
. ' ('
. 'SUM(data_length+index_length+data_free)'
. ' + (COUNT(*) * 300 * 1024)'
. ')'
. '/' . (1048576 + 150) . ' AS estimated_actual_disk_usage'
. ' FROM information_schema.tables';
/** @var \Platformsh\Cli\Service\Relationships $relationships */
$relationships = $this->getService('relationships');
$connectionParams = $relationships->getDbCommandArgs('mysql', $database, '');
return sprintf(
"mysql %s --no-auto-rehash --raw --skip-column-names --execute '%s'",
$connectionParams,
$query
);
} | php | private function mysqlQuery(array $database)
{
$query = 'SELECT'
. ' ('
. 'SUM(data_length+index_length+data_free)'
. ' + (COUNT(*) * 300 * 1024)'
. ')'
. '/' . (1048576 + 150) . ' AS estimated_actual_disk_usage'
. ' FROM information_schema.tables';
/** @var \Platformsh\Cli\Service\Relationships $relationships */
$relationships = $this->getService('relationships');
$connectionParams = $relationships->getDbCommandArgs('mysql', $database, '');
return sprintf(
"mysql %s --no-auto-rehash --raw --skip-column-names --execute '%s'",
$connectionParams,
$query
);
} | [
"private",
"function",
"mysqlQuery",
"(",
"array",
"$",
"database",
")",
"{",
"$",
"query",
"=",
"'SELECT'",
".",
"' ('",
".",
"'SUM(data_length+index_length+data_free)'",
".",
"' + (COUNT(*) * 300 * 1024)'",
".",
"')'",
".",
"'/'",
".",
"(",
"1048576",
"+",
"15... | Returns a command to query disk usage for a MySQL database.
@param array $database The database connection details.
@return string | [
"Returns",
"a",
"command",
"to",
"query",
"disk",
"usage",
"for",
"a",
"MySQL",
"database",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Db/DbSizeCommand.php#L170-L189 |
platformsh/platformsh-cli | src/Console/AdaptiveTable.php | AdaptiveTable.addRow | public function addRow($row)
{
if ($row instanceof TableSeparator) {
$this->rowsCopy[] = $row;
return parent::addRow($row);
}
if (!is_array($row)) {
throw new \InvalidArgumentException('A row must be an array or a TableSeparator instance.');
}
$this->rowsCopy[] = array_values($row);
return parent::addRow($row);
} | php | public function addRow($row)
{
if ($row instanceof TableSeparator) {
$this->rowsCopy[] = $row;
return parent::addRow($row);
}
if (!is_array($row)) {
throw new \InvalidArgumentException('A row must be an array or a TableSeparator instance.');
}
$this->rowsCopy[] = array_values($row);
return parent::addRow($row);
} | [
"public",
"function",
"addRow",
"(",
"$",
"row",
")",
"{",
"if",
"(",
"$",
"row",
"instanceof",
"TableSeparator",
")",
"{",
"$",
"this",
"->",
"rowsCopy",
"[",
"]",
"=",
"$",
"row",
";",
"return",
"parent",
"::",
"addRow",
"(",
"$",
"row",
")",
";"... | {@inheritdoc}
Overrides Table->addRow() so the row content can be accessed. | [
"{",
"@inheritdoc",
"}"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/AdaptiveTable.php#L52-L67 |
platformsh/platformsh-cli | src/Console/AdaptiveTable.php | AdaptiveTable.setHeaders | public function setHeaders(array $headers)
{
$headers = array_values($headers);
if (!empty($headers) && !is_array($headers[0])) {
$headers = array($headers);
}
$this->headersCopy = $headers;
return parent::setHeaders($headers);
} | php | public function setHeaders(array $headers)
{
$headers = array_values($headers);
if (!empty($headers) && !is_array($headers[0])) {
$headers = array($headers);
}
$this->headersCopy = $headers;
return parent::setHeaders($headers);
} | [
"public",
"function",
"setHeaders",
"(",
"array",
"$",
"headers",
")",
"{",
"$",
"headers",
"=",
"array_values",
"(",
"$",
"headers",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"headers",
")",
"&&",
"!",
"is_array",
"(",
"$",
"headers",
"[",
"0",
... | {@inheritdoc}
Overrides Table->setHeaders() so the header content can be accessed. | [
"{",
"@inheritdoc",
"}"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/AdaptiveTable.php#L74-L84 |
platformsh/platformsh-cli | src/Console/AdaptiveTable.php | AdaptiveTable.adaptRows | protected function adaptRows()
{
// Go through all headers and rows, wrapping their cells until each
// column meets the max column width.
$maxColumnWidths = $this->getMaxColumnWidths();
$this->setRows($this->adaptCells($this->rowsCopy, $maxColumnWidths));
} | php | protected function adaptRows()
{
// Go through all headers and rows, wrapping their cells until each
// column meets the max column width.
$maxColumnWidths = $this->getMaxColumnWidths();
$this->setRows($this->adaptCells($this->rowsCopy, $maxColumnWidths));
} | [
"protected",
"function",
"adaptRows",
"(",
")",
"{",
"// Go through all headers and rows, wrapping their cells until each",
"// column meets the max column width.",
"$",
"maxColumnWidths",
"=",
"$",
"this",
"->",
"getMaxColumnWidths",
"(",
")",
";",
"$",
"this",
"->",
"setR... | Adapt rows based on the terminal width. | [
"Adapt",
"rows",
"based",
"on",
"the",
"terminal",
"width",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/AdaptiveTable.php#L100-L106 |
platformsh/platformsh-cli | src/Console/AdaptiveTable.php | AdaptiveTable.adaptCells | protected function adaptCells(array $rows, array $maxColumnWidths)
{
foreach ($rows as $rowNum => &$row) {
if ($row instanceof TableSeparator) {
continue;
}
foreach ($row as $column => &$cell) {
$cellWidth = $this->getCellWidth($cell);
if ($cellWidth > $maxColumnWidths[$column]) {
$cell = $this->wrapCell($cell, $maxColumnWidths[$column]);
}
}
}
return $rows;
} | php | protected function adaptCells(array $rows, array $maxColumnWidths)
{
foreach ($rows as $rowNum => &$row) {
if ($row instanceof TableSeparator) {
continue;
}
foreach ($row as $column => &$cell) {
$cellWidth = $this->getCellWidth($cell);
if ($cellWidth > $maxColumnWidths[$column]) {
$cell = $this->wrapCell($cell, $maxColumnWidths[$column]);
}
}
}
return $rows;
} | [
"protected",
"function",
"adaptCells",
"(",
"array",
"$",
"rows",
",",
"array",
"$",
"maxColumnWidths",
")",
"{",
"foreach",
"(",
"$",
"rows",
"as",
"$",
"rowNum",
"=>",
"&",
"$",
"row",
")",
"{",
"if",
"(",
"$",
"row",
"instanceof",
"TableSeparator",
... | Modify table rows, wrapping their cells' content to the max column width.
@param array $rows
@param array $maxColumnWidths
@return array | [
"Modify",
"table",
"rows",
"wrapping",
"their",
"cells",
"content",
"to",
"the",
"max",
"column",
"width",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/AdaptiveTable.php#L116-L131 |
platformsh/platformsh-cli | src/Console/AdaptiveTable.php | AdaptiveTable.wrapCell | protected function wrapCell($contents, $width)
{
// Account for left-indented cells.
if (strpos($contents, ' ') === 0) {
$trimmed = ltrim($contents, ' ');
$indent = Helper::strlen($contents) - Helper::strlen($trimmed);
return str_repeat(' ', $indent) . $this->wrapWithDecoration($trimmed, $width - $indent);
}
return $this->wrapWithDecoration($contents, $width);
} | php | protected function wrapCell($contents, $width)
{
// Account for left-indented cells.
if (strpos($contents, ' ') === 0) {
$trimmed = ltrim($contents, ' ');
$indent = Helper::strlen($contents) - Helper::strlen($trimmed);
return str_repeat(' ', $indent) . $this->wrapWithDecoration($trimmed, $width - $indent);
}
return $this->wrapWithDecoration($contents, $width);
} | [
"protected",
"function",
"wrapCell",
"(",
"$",
"contents",
",",
"$",
"width",
")",
"{",
"// Account for left-indented cells.",
"if",
"(",
"strpos",
"(",
"$",
"contents",
",",
"' '",
")",
"===",
"0",
")",
"{",
"$",
"trimmed",
"=",
"ltrim",
"(",
"$",
"cont... | Word-wrap the contents of a cell, so that they fit inside a max width.
@param string $contents
@param int $width
@return string | [
"Word",
"-",
"wrap",
"the",
"contents",
"of",
"a",
"cell",
"so",
"that",
"they",
"fit",
"inside",
"a",
"max",
"width",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/AdaptiveTable.php#L141-L152 |
platformsh/platformsh-cli | src/Console/AdaptiveTable.php | AdaptiveTable.wrapWithDecoration | public function wrapWithDecoration($formattedText, $maxLength)
{
$plainText = Helper::removeDecoration($this->outputCopy->getFormatter(), $formattedText);
if ($plainText === $formattedText) {
return wordwrap($plainText, $maxLength, "\n", true);
}
// Find all open and closing tags in the formatted text, with their
// offsets, and build a plain text string out of the rest.
$tagRegex = '[a-zA-Z][a-zA-Z0-9,_=;-]*+';
preg_match_all('#</?(?:' . $tagRegex . ')?>#', $formattedText, $matches, PREG_OFFSET_CAPTURE);
$plainText = '';
$tagChunks = [];
$lastTagClose = 0;
foreach ($matches[0] as $match) {
list($tagChunk, $tagOffset) = $match;
if (substr($formattedText, $tagOffset - 1, 1) === '\\') {
continue;
}
$plainText .= substr($formattedText, $lastTagClose, $tagOffset - $lastTagClose);
$tagChunks[$tagOffset] = $tagChunk;
$lastTagClose = $tagOffset + strlen($tagChunk);
}
$plainText .= substr($formattedText, $lastTagClose);
// Wrap the plain text, keeping track of the removed characters in each
// line (caused by trimming).
$remaining = $plainText;
$lines = [];
$removedCharacters = [];
while (!empty($remaining)) {
if (strlen($remaining) > $maxLength) {
$spacePos = strrpos(substr($remaining, 0, $maxLength + 1), ' ');
if ($spacePos !== false) {
$breakPosition = $spacePos + 1;
} else {
$breakPosition = $maxLength;
// Adjust for \< which will be converted to < later.
$breakPosition += substr_count($remaining, '\\<', 0, $breakPosition);
}
$line = substr($remaining, 0, $breakPosition);
$remaining = substr($remaining, $breakPosition);
} else {
$line = $remaining;
$remaining = '';
}
$lineTrimmed = trim($line);
$removedCharacters[] = strlen($line) - strlen($lineTrimmed);
$lines[] = $lineTrimmed;
}
// Interpolate the tags back into the wrapped text.
$remainingTagChunks = $tagChunks;
$lineOffset = 0;
foreach ($lines as $lineNumber => &$line) {
$lineLength = strlen($line) + $removedCharacters[$lineNumber];
foreach ($remainingTagChunks as $tagOffset => $tagChunk) {
// Prefer putting opening tags at the beginning of a line, not
// the end.
if ($tagChunk[1] !== '/' && $tagOffset === $lineOffset + $lineLength) {
continue;
}
if ($tagOffset >= $lineOffset && $tagOffset <= $lineOffset + $lineLength) {
$insertPosition = $tagOffset - $lineOffset;
$line = substr($line, 0, $insertPosition) . $tagChunk . substr($line, $insertPosition);
$lineLength += strlen($tagChunk);
unset($remainingTagChunks[$tagOffset]);
}
}
$lineOffset += $lineLength;
}
$wrapped = implode("\n", $lines) . implode($remainingTagChunks);
// Ensure that tags are closed at the end of each line and re-opened at
// the beginning of the next one.
$wrapped = preg_replace_callback('@(<' . $tagRegex . '>)(((?!(?<!\\\)</).)+)@s', function (array $matches) {
return $matches[1] . str_replace("\n", "</>\n" . $matches[1], $matches[2]);
}, $wrapped);
return $wrapped;
} | php | public function wrapWithDecoration($formattedText, $maxLength)
{
$plainText = Helper::removeDecoration($this->outputCopy->getFormatter(), $formattedText);
if ($plainText === $formattedText) {
return wordwrap($plainText, $maxLength, "\n", true);
}
// Find all open and closing tags in the formatted text, with their
// offsets, and build a plain text string out of the rest.
$tagRegex = '[a-zA-Z][a-zA-Z0-9,_=;-]*+';
preg_match_all('#</?(?:' . $tagRegex . ')?>#', $formattedText, $matches, PREG_OFFSET_CAPTURE);
$plainText = '';
$tagChunks = [];
$lastTagClose = 0;
foreach ($matches[0] as $match) {
list($tagChunk, $tagOffset) = $match;
if (substr($formattedText, $tagOffset - 1, 1) === '\\') {
continue;
}
$plainText .= substr($formattedText, $lastTagClose, $tagOffset - $lastTagClose);
$tagChunks[$tagOffset] = $tagChunk;
$lastTagClose = $tagOffset + strlen($tagChunk);
}
$plainText .= substr($formattedText, $lastTagClose);
// Wrap the plain text, keeping track of the removed characters in each
// line (caused by trimming).
$remaining = $plainText;
$lines = [];
$removedCharacters = [];
while (!empty($remaining)) {
if (strlen($remaining) > $maxLength) {
$spacePos = strrpos(substr($remaining, 0, $maxLength + 1), ' ');
if ($spacePos !== false) {
$breakPosition = $spacePos + 1;
} else {
$breakPosition = $maxLength;
// Adjust for \< which will be converted to < later.
$breakPosition += substr_count($remaining, '\\<', 0, $breakPosition);
}
$line = substr($remaining, 0, $breakPosition);
$remaining = substr($remaining, $breakPosition);
} else {
$line = $remaining;
$remaining = '';
}
$lineTrimmed = trim($line);
$removedCharacters[] = strlen($line) - strlen($lineTrimmed);
$lines[] = $lineTrimmed;
}
// Interpolate the tags back into the wrapped text.
$remainingTagChunks = $tagChunks;
$lineOffset = 0;
foreach ($lines as $lineNumber => &$line) {
$lineLength = strlen($line) + $removedCharacters[$lineNumber];
foreach ($remainingTagChunks as $tagOffset => $tagChunk) {
// Prefer putting opening tags at the beginning of a line, not
// the end.
if ($tagChunk[1] !== '/' && $tagOffset === $lineOffset + $lineLength) {
continue;
}
if ($tagOffset >= $lineOffset && $tagOffset <= $lineOffset + $lineLength) {
$insertPosition = $tagOffset - $lineOffset;
$line = substr($line, 0, $insertPosition) . $tagChunk . substr($line, $insertPosition);
$lineLength += strlen($tagChunk);
unset($remainingTagChunks[$tagOffset]);
}
}
$lineOffset += $lineLength;
}
$wrapped = implode("\n", $lines) . implode($remainingTagChunks);
// Ensure that tags are closed at the end of each line and re-opened at
// the beginning of the next one.
$wrapped = preg_replace_callback('@(<' . $tagRegex . '>)(((?!(?<!\\\)</).)+)@s', function (array $matches) {
return $matches[1] . str_replace("\n", "</>\n" . $matches[1], $matches[2]);
}, $wrapped);
return $wrapped;
} | [
"public",
"function",
"wrapWithDecoration",
"(",
"$",
"formattedText",
",",
"$",
"maxLength",
")",
"{",
"$",
"plainText",
"=",
"Helper",
"::",
"removeDecoration",
"(",
"$",
"this",
"->",
"outputCopy",
"->",
"getFormatter",
"(",
")",
",",
"$",
"formattedText",
... | Word-wraps the contents of a cell, accounting for decoration.
@param string $formattedText
@param int $maxLength
@return string | [
"Word",
"-",
"wraps",
"the",
"contents",
"of",
"a",
"cell",
"accounting",
"for",
"decoration",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/AdaptiveTable.php#L162-L243 |
platformsh/platformsh-cli | src/Console/AdaptiveTable.php | AdaptiveTable.getMaxContentWidth | protected function getMaxContentWidth($columnCount)
{
$style = $this->getStyle();
$verticalBorderQuantity = $columnCount + 1;
$paddingQuantity = $columnCount * 2;
return $this->maxTableWidth
- $verticalBorderQuantity * strlen($style->getVerticalBorderChar())
- $paddingQuantity * strlen($style->getPaddingChar());
} | php | protected function getMaxContentWidth($columnCount)
{
$style = $this->getStyle();
$verticalBorderQuantity = $columnCount + 1;
$paddingQuantity = $columnCount * 2;
return $this->maxTableWidth
- $verticalBorderQuantity * strlen($style->getVerticalBorderChar())
- $paddingQuantity * strlen($style->getPaddingChar());
} | [
"protected",
"function",
"getMaxContentWidth",
"(",
"$",
"columnCount",
")",
"{",
"$",
"style",
"=",
"$",
"this",
"->",
"getStyle",
"(",
")",
";",
"$",
"verticalBorderQuantity",
"=",
"$",
"columnCount",
"+",
"1",
";",
"$",
"paddingQuantity",
"=",
"$",
"col... | Find the maximum content width (excluding decoration) for each table row.
@param int $columnCount
The number of columns in the table.
@return int
The maximum table width, minus the width taken up by decoration. | [
"Find",
"the",
"maximum",
"content",
"width",
"(",
"excluding",
"decoration",
")",
"for",
"each",
"table",
"row",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/AdaptiveTable.php#L328-L337 |
platformsh/platformsh-cli | src/Console/AdaptiveTable.php | AdaptiveTable.getCellWidth | private function getCellWidth($cell)
{
$lineWidths = [0];
foreach (explode(PHP_EOL, $cell) as $line) {
$lineWidths[] = Helper::strlenWithoutDecoration($this->outputCopy->getFormatter(), $line);
}
$cellWidth = max($lineWidths);
if ($cell instanceof TableCell && $cell->getColspan() > 1) {
$cellWidth /= $cell->getColspan();
}
return $cellWidth;
} | php | private function getCellWidth($cell)
{
$lineWidths = [0];
foreach (explode(PHP_EOL, $cell) as $line) {
$lineWidths[] = Helper::strlenWithoutDecoration($this->outputCopy->getFormatter(), $line);
}
$cellWidth = max($lineWidths);
if ($cell instanceof TableCell && $cell->getColspan() > 1) {
$cellWidth /= $cell->getColspan();
}
return $cellWidth;
} | [
"private",
"function",
"getCellWidth",
"(",
"$",
"cell",
")",
"{",
"$",
"lineWidths",
"=",
"[",
"0",
"]",
";",
"foreach",
"(",
"explode",
"(",
"PHP_EOL",
",",
"$",
"cell",
")",
"as",
"$",
"line",
")",
"{",
"$",
"lineWidths",
"[",
"]",
"=",
"Helper"... | Get the default width of a table cell (the length of its longest line).
This is inspired by Table->getCellWidth(), but this also accounts for
multi-line cells.
@param string|TableCell $cell
@return float|int | [
"Get",
"the",
"default",
"width",
"of",
"a",
"table",
"cell",
"(",
"the",
"length",
"of",
"its",
"longest",
"line",
")",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/AdaptiveTable.php#L349-L361 |
platformsh/platformsh-cli | src/Local/DependencyInstaller.php | DependencyInstaller.putEnv | public function putEnv($destination, array $dependencies)
{
$env = [];
$paths = [];
foreach ($dependencies as $stack => $stackDependencies) {
$manager = $this->getManager($stack);
$path = $destination . '/' . $stack;
$paths = array_merge($paths, $manager->getBinPaths($path));
$env = array_merge($env, $manager->getEnvVars($path));
}
$paths = array_filter(array_map('realpath', $paths));
if (!empty($paths)) {
$pathVariable = OsUtil::isWindows() ? 'Path' : 'PATH';
$env[$pathVariable] = implode(':', $paths);
if (getenv($pathVariable)) {
$env[$pathVariable] .= ':' . getenv($pathVariable);
}
}
foreach ($env as $name => $value) {
putenv($name . '=' . $value);
}
} | php | public function putEnv($destination, array $dependencies)
{
$env = [];
$paths = [];
foreach ($dependencies as $stack => $stackDependencies) {
$manager = $this->getManager($stack);
$path = $destination . '/' . $stack;
$paths = array_merge($paths, $manager->getBinPaths($path));
$env = array_merge($env, $manager->getEnvVars($path));
}
$paths = array_filter(array_map('realpath', $paths));
if (!empty($paths)) {
$pathVariable = OsUtil::isWindows() ? 'Path' : 'PATH';
$env[$pathVariable] = implode(':', $paths);
if (getenv($pathVariable)) {
$env[$pathVariable] .= ':' . getenv($pathVariable);
}
}
foreach ($env as $name => $value) {
putenv($name . '=' . $value);
}
} | [
"public",
"function",
"putEnv",
"(",
"$",
"destination",
",",
"array",
"$",
"dependencies",
")",
"{",
"$",
"env",
"=",
"[",
"]",
";",
"$",
"paths",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"dependencies",
"as",
"$",
"stack",
"=>",
"$",
"stackDependen... | Modify the environment to make the installed dependencies available.
@param string $destination
@param array $dependencies | [
"Modify",
"the",
"environment",
"to",
"make",
"the",
"installed",
"dependencies",
"available",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyInstaller.php#L25-L46 |
platformsh/platformsh-cli | src/Local/DependencyInstaller.php | DependencyInstaller.installDependencies | public function installDependencies($destination, array $dependencies, $global = false)
{
$success = true;
foreach ($dependencies as $stack => $stackDependencies) {
$manager = $this->getManager($stack);
$this->output->writeln(sprintf(
"Installing <info>%s</info> dependencies with '%s': %s",
$stack,
$manager->getCommandName(),
implode(', ', array_keys($stackDependencies))
));
if (!$manager->isAvailable()) {
$this->output->writeln(sprintf(
"Cannot install <comment>%s</comment> dependencies: '%s' is not installed.",
$stack,
$manager->getCommandName()
));
if ($manager->getInstallHelp()) {
$this->output->writeln($manager->getInstallHelp());
}
$success = false;
continue;
}
$path = $destination . '/' . $stack;
$this->ensureDirectory($path);
$manager->install($path, $stackDependencies, $global);
}
return $success;
} | php | public function installDependencies($destination, array $dependencies, $global = false)
{
$success = true;
foreach ($dependencies as $stack => $stackDependencies) {
$manager = $this->getManager($stack);
$this->output->writeln(sprintf(
"Installing <info>%s</info> dependencies with '%s': %s",
$stack,
$manager->getCommandName(),
implode(', ', array_keys($stackDependencies))
));
if (!$manager->isAvailable()) {
$this->output->writeln(sprintf(
"Cannot install <comment>%s</comment> dependencies: '%s' is not installed.",
$stack,
$manager->getCommandName()
));
if ($manager->getInstallHelp()) {
$this->output->writeln($manager->getInstallHelp());
}
$success = false;
continue;
}
$path = $destination . '/' . $stack;
$this->ensureDirectory($path);
$manager->install($path, $stackDependencies, $global);
}
return $success;
} | [
"public",
"function",
"installDependencies",
"(",
"$",
"destination",
",",
"array",
"$",
"dependencies",
",",
"$",
"global",
"=",
"false",
")",
"{",
"$",
"success",
"=",
"true",
";",
"foreach",
"(",
"$",
"dependencies",
"as",
"$",
"stack",
"=>",
"$",
"st... | Install dependencies into a directory.
@param string $destination
@param array $dependencies
@param bool $global
@throws \Exception If a dependency fails to install.
@return bool
False if a dependency manager is not available; otherwise true. | [
"Install",
"dependencies",
"into",
"a",
"directory",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyInstaller.php#L60-L89 |
platformsh/platformsh-cli | src/Local/DependencyInstaller.php | DependencyInstaller.getManager | protected function getManager($name)
{
// Python has 'python', 'python2', and 'python3'.
if (strpos('python', $name) === 0) {
return new DependencyManager\Pip($this->shell);
}
$stacks = [
'nodejs' => new DependencyManager\Npm($this->shell),
'ruby' => new DependencyManager\Bundler($this->shell),
'php' => new DependencyManager\Composer($this->shell),
];
if (isset($stacks[$name])) {
return $stacks[$name];
}
throw new \InvalidArgumentException(sprintf('Unknown dependencies stack: %s', $name));
} | php | protected function getManager($name)
{
// Python has 'python', 'python2', and 'python3'.
if (strpos('python', $name) === 0) {
return new DependencyManager\Pip($this->shell);
}
$stacks = [
'nodejs' => new DependencyManager\Npm($this->shell),
'ruby' => new DependencyManager\Bundler($this->shell),
'php' => new DependencyManager\Composer($this->shell),
];
if (isset($stacks[$name])) {
return $stacks[$name];
}
throw new \InvalidArgumentException(sprintf('Unknown dependencies stack: %s', $name));
} | [
"protected",
"function",
"getManager",
"(",
"$",
"name",
")",
"{",
"// Python has 'python', 'python2', and 'python3'.",
"if",
"(",
"strpos",
"(",
"'python'",
",",
"$",
"name",
")",
"===",
"0",
")",
"{",
"return",
"new",
"DependencyManager",
"\\",
"Pip",
"(",
"... | Finds the right dependency manager for a given stack.
@param string $name
@return \Platformsh\Cli\Local\DependencyManager\DependencyManagerInterface | [
"Finds",
"the",
"right",
"dependency",
"manager",
"for",
"a",
"given",
"stack",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyInstaller.php#L108-L125 |
platformsh/platformsh-cli | src/Command/Certificate/CertificateDeleteCommand.php | CertificateDeleteCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$id = $input->getArgument('id');
$project = $this->getSelectedProject();
$certificate = $project->getCertificate($id);
if (!$certificate) {
try {
$certificate = $this->api()->matchPartialId($id, $project->getCertificates(), 'Certificate');
} catch (\InvalidArgumentException $e) {
$this->stdErr->writeln($e->getMessage());
return 1;
}
}
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
if (!$questionHelper->confirm(sprintf('Are you sure you want to delete the certificate <info>%s</info>?', $certificate->id))) {
return 1;
}
try {
$result = $certificate->delete();
} catch (BadResponseException $e) {
if (($response = $e->getResponse()) && $response->getStatusCode() === 403 && $certificate->is_provisioned) {
$this->stdErr->writeln(sprintf('The certificate <error>%s</error> is automatically provisioned; it cannot be deleted.', $certificate->id));
return 1;
}
throw $e;
}
$this->stdErr->writeln(sprintf('The certificate <info>%s</info> has been deleted.', $certificate->id));
if ($this->shouldWait($input)) {
/** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */
$activityMonitor = $this->getService('activity_monitor');
$activityMonitor->waitMultiple($result->getActivities(), $project);
}
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$id = $input->getArgument('id');
$project = $this->getSelectedProject();
$certificate = $project->getCertificate($id);
if (!$certificate) {
try {
$certificate = $this->api()->matchPartialId($id, $project->getCertificates(), 'Certificate');
} catch (\InvalidArgumentException $e) {
$this->stdErr->writeln($e->getMessage());
return 1;
}
}
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
if (!$questionHelper->confirm(sprintf('Are you sure you want to delete the certificate <info>%s</info>?', $certificate->id))) {
return 1;
}
try {
$result = $certificate->delete();
} catch (BadResponseException $e) {
if (($response = $e->getResponse()) && $response->getStatusCode() === 403 && $certificate->is_provisioned) {
$this->stdErr->writeln(sprintf('The certificate <error>%s</error> is automatically provisioned; it cannot be deleted.', $certificate->id));
return 1;
}
throw $e;
}
$this->stdErr->writeln(sprintf('The certificate <info>%s</info> has been deleted.', $certificate->id));
if ($this->shouldWait($input)) {
/** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */
$activityMonitor = $this->getService('activity_monitor');
$activityMonitor->waitMultiple($result->getActivities(), $project);
}
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"validateInput",
"(",
"$",
"input",
")",
";",
"$",
"id",
"=",
"$",
"input",
"->",
"getArgument",
"(",
"'id'",
")"... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Certificate/CertificateDeleteCommand.php#L28-L71 |
platformsh/platformsh-cli | src/Command/Project/ProjectGetCommand.php | ProjectGetCommand.validateInput | protected function validateInput(InputInterface $input, $envNotRequired = false, $selectDefaultEnv = false)
{
if ($input->getOption('depth') !== null && !preg_match('/^[0-9]+$/', $input->getOption('depth'))) {
throw new InvalidArgumentException('The --depth value must be an integer.');
}
if ($input->getOption('project') && $input->getArgument('project')) {
throw new InvalidArgumentException('You cannot use both the --project option and the <project> argument.');
}
$projectId = $input->getOption('project') ?: $input->getArgument('project');
$environmentId = $input->getOption('environment');
$host = $input->getOption('host');
if (empty($projectId)) {
if ($input->isInteractive() && ($projects = $this->api()->getProjects(true))) {
$projectId = $this->offerProjectChoice($projects, 'Enter a number to choose which project to clone:');
} else {
throw new InvalidArgumentException('No project specified');
}
} else {
/** @var \Platformsh\Cli\Service\Identifier $identifier */
$identifier = $this->getService('identifier');
$result = $identifier->identify($projectId);
$projectId = $result['projectId'];
$host = $host ?: $result['host'];
$environmentId = $environmentId !== null ? $environmentId : $result['environmentId'];
}
$project = $this->selectProject($projectId, $host);
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$directory = $input->getArgument('directory');
if (empty($directory)) {
$slugify = new Slugify();
$directory = $project->title ? $slugify->slugify($project->title) : $project->id;
$directory = $questionHelper->askInput('Directory', $directory, [$directory, $projectId]);
}
if ($projectRoot = $this->getProjectRoot()) {
if (strpos(realpath(dirname($directory)), $projectRoot) === 0) {
throw new InvalidArgumentException('A project cannot be cloned inside another project.');
}
}
if (file_exists($directory)) {
throw new InvalidArgumentException('The directory already exists: ' . $directory);
}
if (!$parent = realpath(dirname($directory))) {
throw new InvalidArgumentException("Not a directory: " . dirname($directory));
}
$this->projectRoot = $parent . '/' . basename($directory);
if ($environmentId === null) {
$environments = $this->api()->getEnvironments($project);
$environmentId = isset($environments['master']) ? 'master' : key($environments);
if (count($environments) > 1) {
$environmentId = $questionHelper->askInput('Environment', $environmentId, array_keys($environments));
}
}
$this->selectEnvironment($environmentId);
} | php | protected function validateInput(InputInterface $input, $envNotRequired = false, $selectDefaultEnv = false)
{
if ($input->getOption('depth') !== null && !preg_match('/^[0-9]+$/', $input->getOption('depth'))) {
throw new InvalidArgumentException('The --depth value must be an integer.');
}
if ($input->getOption('project') && $input->getArgument('project')) {
throw new InvalidArgumentException('You cannot use both the --project option and the <project> argument.');
}
$projectId = $input->getOption('project') ?: $input->getArgument('project');
$environmentId = $input->getOption('environment');
$host = $input->getOption('host');
if (empty($projectId)) {
if ($input->isInteractive() && ($projects = $this->api()->getProjects(true))) {
$projectId = $this->offerProjectChoice($projects, 'Enter a number to choose which project to clone:');
} else {
throw new InvalidArgumentException('No project specified');
}
} else {
/** @var \Platformsh\Cli\Service\Identifier $identifier */
$identifier = $this->getService('identifier');
$result = $identifier->identify($projectId);
$projectId = $result['projectId'];
$host = $host ?: $result['host'];
$environmentId = $environmentId !== null ? $environmentId : $result['environmentId'];
}
$project = $this->selectProject($projectId, $host);
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$directory = $input->getArgument('directory');
if (empty($directory)) {
$slugify = new Slugify();
$directory = $project->title ? $slugify->slugify($project->title) : $project->id;
$directory = $questionHelper->askInput('Directory', $directory, [$directory, $projectId]);
}
if ($projectRoot = $this->getProjectRoot()) {
if (strpos(realpath(dirname($directory)), $projectRoot) === 0) {
throw new InvalidArgumentException('A project cannot be cloned inside another project.');
}
}
if (file_exists($directory)) {
throw new InvalidArgumentException('The directory already exists: ' . $directory);
}
if (!$parent = realpath(dirname($directory))) {
throw new InvalidArgumentException("Not a directory: " . dirname($directory));
}
$this->projectRoot = $parent . '/' . basename($directory);
if ($environmentId === null) {
$environments = $this->api()->getEnvironments($project);
$environmentId = isset($environments['master']) ? 'master' : key($environments);
if (count($environments) > 1) {
$environmentId = $questionHelper->askInput('Environment', $environmentId, array_keys($environments));
}
}
$this->selectEnvironment($environmentId);
} | [
"protected",
"function",
"validateInput",
"(",
"InputInterface",
"$",
"input",
",",
"$",
"envNotRequired",
"=",
"false",
",",
"$",
"selectDefaultEnv",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"input",
"->",
"getOption",
"(",
"'depth'",
")",
"!==",
"null",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Project/ProjectGetCommand.php#L196-L257 |
platformsh/platformsh-cli | src/Command/Project/ProjectGetCommand.php | ProjectGetCommand.suggestSshRemedies | protected function suggestSshRemedies()
{
$sshKeys = [];
try {
$sshKeys = $this->api()->getClient(false)->getSshKeys();
} catch (\Exception $e) {
// Ignore exceptions.
}
if (!empty($sshKeys)) {
$this->stdErr->writeln('');
$this->stdErr->writeln('Please check your SSH credentials');
$this->stdErr->writeln(sprintf(
'You can list your keys with: <comment>%s ssh-keys</comment>',
$this->config()->get('application.executable')
));
} else {
$this->stdErr->writeln(sprintf(
'You probably need to add an SSH key, with: <comment>%s ssh-key:add</comment>',
$this->config()->get('application.executable')
));
}
} | php | protected function suggestSshRemedies()
{
$sshKeys = [];
try {
$sshKeys = $this->api()->getClient(false)->getSshKeys();
} catch (\Exception $e) {
// Ignore exceptions.
}
if (!empty($sshKeys)) {
$this->stdErr->writeln('');
$this->stdErr->writeln('Please check your SSH credentials');
$this->stdErr->writeln(sprintf(
'You can list your keys with: <comment>%s ssh-keys</comment>',
$this->config()->get('application.executable')
));
} else {
$this->stdErr->writeln(sprintf(
'You probably need to add an SSH key, with: <comment>%s ssh-key:add</comment>',
$this->config()->get('application.executable')
));
}
} | [
"protected",
"function",
"suggestSshRemedies",
"(",
")",
"{",
"$",
"sshKeys",
"=",
"[",
"]",
";",
"try",
"{",
"$",
"sshKeys",
"=",
"$",
"this",
"->",
"api",
"(",
")",
"->",
"getClient",
"(",
"false",
")",
"->",
"getSshKeys",
"(",
")",
";",
"}",
"ca... | Suggest SSH key commands for the user, if the Git connection fails. | [
"Suggest",
"SSH",
"key",
"commands",
"for",
"the",
"user",
"if",
"the",
"Git",
"connection",
"fails",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Project/ProjectGetCommand.php#L262-L284 |
platformsh/platformsh-cli | src/Util/PortUtil.php | PortUtil.getPort | public static function getPort($start = 3000, $hostname = null, $end = null)
{
$end = $end ?: $start + 30;
for ($port = $start; $port <= $end; $port++) {
if (static::validatePort($port) && !static::isPortInUse($port, $hostname)) {
return $port;
}
}
throw new \Exception(sprintf('Failed to find an available port between %d and %d', $start, $end));
} | php | public static function getPort($start = 3000, $hostname = null, $end = null)
{
$end = $end ?: $start + 30;
for ($port = $start; $port <= $end; $port++) {
if (static::validatePort($port) && !static::isPortInUse($port, $hostname)) {
return $port;
}
}
throw new \Exception(sprintf('Failed to find an available port between %d and %d', $start, $end));
} | [
"public",
"static",
"function",
"getPort",
"(",
"$",
"start",
"=",
"3000",
",",
"$",
"hostname",
"=",
"null",
",",
"$",
"end",
"=",
"null",
")",
"{",
"$",
"end",
"=",
"$",
"end",
"?",
":",
"$",
"start",
"+",
"30",
";",
"for",
"(",
"$",
"port",
... | Get the next available valid port.
@param int $start The starting port number.
@param string|null $hostname The hostname, defaults to 127.0.0.1.
@param int|null $end The maximum port number to try (defaults to
$start + 30);
@throws \Exception on failure
@return int | [
"Get",
"the",
"next",
"available",
"valid",
"port",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/PortUtil.php#L31-L40 |
platformsh/platformsh-cli | src/Util/PortUtil.php | PortUtil.validatePort | public static function validatePort($port)
{
if (!is_numeric($port) || $port <= 1023 || $port > 65535) {
return false;
}
return !in_array($port, self::$unsafePorts);
} | php | public static function validatePort($port)
{
if (!is_numeric($port) || $port <= 1023 || $port > 65535) {
return false;
}
return !in_array($port, self::$unsafePorts);
} | [
"public",
"static",
"function",
"validatePort",
"(",
"$",
"port",
")",
"{",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"port",
")",
"||",
"$",
"port",
"<=",
"1023",
"||",
"$",
"port",
">",
"65535",
")",
"{",
"return",
"false",
";",
"}",
"return",
"!",... | Validate a port number.
@param int|string $port
@return bool | [
"Validate",
"a",
"port",
"number",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/PortUtil.php#L49-L56 |
platformsh/platformsh-cli | src/Util/PortUtil.php | PortUtil.isPortInUse | public static function isPortInUse($port, $hostname = null)
{
$fp = @fsockopen($hostname !== null ? $hostname : '127.0.0.1', $port, $errno, $errstr, 10);
if ($fp !== false) {
fclose($fp);
return true;
}
return false;
} | php | public static function isPortInUse($port, $hostname = null)
{
$fp = @fsockopen($hostname !== null ? $hostname : '127.0.0.1', $port, $errno, $errstr, 10);
if ($fp !== false) {
fclose($fp);
return true;
}
return false;
} | [
"public",
"static",
"function",
"isPortInUse",
"(",
"$",
"port",
",",
"$",
"hostname",
"=",
"null",
")",
"{",
"$",
"fp",
"=",
"@",
"fsockopen",
"(",
"$",
"hostname",
"!==",
"null",
"?",
"$",
"hostname",
":",
"'127.0.0.1'",
",",
"$",
"port",
",",
"$",... | Check whether a port is open.
@param int $port
@param string|null $hostname
@return bool | [
"Check",
"whether",
"a",
"port",
"is",
"open",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/PortUtil.php#L66-L76 |
platformsh/platformsh-cli | src/Command/Environment/EnvironmentInfoCommand.php | EnvironmentInfoCommand.configure | protected function configure()
{
$this
->setName('environment:info')
->addArgument('property', InputArgument::OPTIONAL, 'The name of the property')
->addArgument('value', InputArgument::OPTIONAL, 'Set a new value for the property')
->addOption('refresh', null, InputOption::VALUE_NONE, 'Whether to refresh the cache')
->setDescription('Read or set properties for an environment');
PropertyFormatter::configureInput($this->getDefinition());
Table::configureInput($this->getDefinition());
$this->addProjectOption()
->addEnvironmentOption()
->addWaitOptions();
$this->addExample('Read all environment properties')
->addExample("Show the environment's status", 'status')
->addExample('Show the date the environment was created', 'created_at')
->addExample('Enable email sending', 'enable_smtp true')
->addExample('Change the environment title', 'title "New feature"')
->addExample("Change the environment's parent branch", 'parent sprint-2');
$this->setHiddenAliases(['environment:metadata']);
} | php | protected function configure()
{
$this
->setName('environment:info')
->addArgument('property', InputArgument::OPTIONAL, 'The name of the property')
->addArgument('value', InputArgument::OPTIONAL, 'Set a new value for the property')
->addOption('refresh', null, InputOption::VALUE_NONE, 'Whether to refresh the cache')
->setDescription('Read or set properties for an environment');
PropertyFormatter::configureInput($this->getDefinition());
Table::configureInput($this->getDefinition());
$this->addProjectOption()
->addEnvironmentOption()
->addWaitOptions();
$this->addExample('Read all environment properties')
->addExample("Show the environment's status", 'status')
->addExample('Show the date the environment was created', 'created_at')
->addExample('Enable email sending', 'enable_smtp true')
->addExample('Change the environment title', 'title "New feature"')
->addExample("Change the environment's parent branch", 'parent sprint-2');
$this->setHiddenAliases(['environment:metadata']);
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'environment:info'",
")",
"->",
"addArgument",
"(",
"'property'",
",",
"InputArgument",
"::",
"OPTIONAL",
",",
"'The name of the property'",
")",
"->",
"addArgument",
"(",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentInfoCommand.php#L22-L42 |
platformsh/platformsh-cli | src/Command/Environment/EnvironmentInfoCommand.php | EnvironmentInfoCommand.listProperties | protected function listProperties(Environment $environment)
{
$headings = [];
$values = [];
foreach ($environment->getProperties() as $key => $value) {
$headings[] = new AdaptiveTableCell($key, ['wrap' => false]);
$values[] = $this->formatter->format($value, $key);
}
/** @var \Platformsh\Cli\Service\Table $table */
$table = $this->getService('table');
$table->renderSimple($values, $headings);
return 0;
} | php | protected function listProperties(Environment $environment)
{
$headings = [];
$values = [];
foreach ($environment->getProperties() as $key => $value) {
$headings[] = new AdaptiveTableCell($key, ['wrap' => false]);
$values[] = $this->formatter->format($value, $key);
}
/** @var \Platformsh\Cli\Service\Table $table */
$table = $this->getService('table');
$table->renderSimple($values, $headings);
return 0;
} | [
"protected",
"function",
"listProperties",
"(",
"Environment",
"$",
"environment",
")",
"{",
"$",
"headings",
"=",
"[",
"]",
";",
"$",
"values",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"environment",
"->",
"getProperties",
"(",
")",
"as",
"$",
"key",
... | @param Environment $environment
@return int | [
"@param",
"Environment",
"$environment"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentInfoCommand.php#L85-L98 |
platformsh/platformsh-cli | src/Command/Environment/EnvironmentInfoCommand.php | EnvironmentInfoCommand.setProperty | protected function setProperty($property, $value, Environment $environment, $noWait)
{
if (!$this->validateValue($property, $value)) {
return 1;
}
$type = $this->getType($property);
if ($type === 'boolean' && $value === 'false') {
$value = false;
}
settype($value, $type);
$currentValue = $environment->getProperty($property, false);
if ($currentValue === $value) {
$this->stdErr->writeln(sprintf(
'Property <info>%s</info> already set as: %s',
$property,
$this->formatter->format($environment->getProperty($property, false), $property)
));
return 0;
}
$result = $environment->update([$property => $value]);
$this->stdErr->writeln(sprintf(
'Property <info>%s</info> set to: %s',
$property,
$this->formatter->format($environment->$property, $property)
));
$this->api()->clearEnvironmentsCache($environment->project);
$rebuildProperties = ['enable_smtp', 'restrict_robots'];
$success = true;
if ($result->countActivities() && !$noWait) {
/** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */
$activityMonitor = $this->getService('activity_monitor');
$success = $activityMonitor->waitMultiple($result->getActivities(), $this->getSelectedProject());
} elseif (!$result->countActivities() && in_array($property, $rebuildProperties)) {
$this->redeployWarning();
}
return $success ? 0 : 1;
} | php | protected function setProperty($property, $value, Environment $environment, $noWait)
{
if (!$this->validateValue($property, $value)) {
return 1;
}
$type = $this->getType($property);
if ($type === 'boolean' && $value === 'false') {
$value = false;
}
settype($value, $type);
$currentValue = $environment->getProperty($property, false);
if ($currentValue === $value) {
$this->stdErr->writeln(sprintf(
'Property <info>%s</info> already set as: %s',
$property,
$this->formatter->format($environment->getProperty($property, false), $property)
));
return 0;
}
$result = $environment->update([$property => $value]);
$this->stdErr->writeln(sprintf(
'Property <info>%s</info> set to: %s',
$property,
$this->formatter->format($environment->$property, $property)
));
$this->api()->clearEnvironmentsCache($environment->project);
$rebuildProperties = ['enable_smtp', 'restrict_robots'];
$success = true;
if ($result->countActivities() && !$noWait) {
/** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */
$activityMonitor = $this->getService('activity_monitor');
$success = $activityMonitor->waitMultiple($result->getActivities(), $this->getSelectedProject());
} elseif (!$result->countActivities() && in_array($property, $rebuildProperties)) {
$this->redeployWarning();
}
return $success ? 0 : 1;
} | [
"protected",
"function",
"setProperty",
"(",
"$",
"property",
",",
"$",
"value",
",",
"Environment",
"$",
"environment",
",",
"$",
"noWait",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"validateValue",
"(",
"$",
"property",
",",
"$",
"value",
")",
")"... | @param string $property
@param string $value
@param Environment $environment
@param bool $noWait
@return int | [
"@param",
"string",
"$property",
"@param",
"string",
"$value",
"@param",
"Environment",
"$environment",
"@param",
"bool",
"$noWait"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentInfoCommand.php#L108-L148 |
platformsh/platformsh-cli | src/Command/Environment/EnvironmentInfoCommand.php | EnvironmentInfoCommand.validateValue | protected function validateValue($property, $value)
{
$type = $this->getType($property);
if (!$type) {
$this->stdErr->writeln("Property not writable: <error>$property</error>");
return false;
}
$valid = true;
$message = '';
// @todo find out exactly how these should best be validated
$selectedEnvironment = $this->getSelectedEnvironment();
switch ($property) {
case 'parent':
if ($selectedEnvironment->id === 'master') {
$message = "The master environment cannot have a parent";
$valid = false;
} elseif ($value === $selectedEnvironment->id) {
$message = "An environment cannot be the parent of itself";
$valid = false;
} elseif (!$parentEnvironment = $this->api()->getEnvironment($value, $this->getSelectedProject())) {
$message = "Environment not found: <error>$value</error>";
$valid = false;
} elseif ($parentEnvironment->parent === $selectedEnvironment->id) {
$valid = false;
}
break;
}
switch ($type) {
case 'boolean':
$valid = in_array($value, ['1', '0', 'false', 'true']);
break;
}
if (!$valid) {
if ($message) {
$this->stdErr->writeln($message);
} else {
$this->stdErr->writeln("Invalid value for <error>$property</error>: $value");
}
return false;
}
return true;
} | php | protected function validateValue($property, $value)
{
$type = $this->getType($property);
if (!$type) {
$this->stdErr->writeln("Property not writable: <error>$property</error>");
return false;
}
$valid = true;
$message = '';
// @todo find out exactly how these should best be validated
$selectedEnvironment = $this->getSelectedEnvironment();
switch ($property) {
case 'parent':
if ($selectedEnvironment->id === 'master') {
$message = "The master environment cannot have a parent";
$valid = false;
} elseif ($value === $selectedEnvironment->id) {
$message = "An environment cannot be the parent of itself";
$valid = false;
} elseif (!$parentEnvironment = $this->api()->getEnvironment($value, $this->getSelectedProject())) {
$message = "Environment not found: <error>$value</error>";
$valid = false;
} elseif ($parentEnvironment->parent === $selectedEnvironment->id) {
$valid = false;
}
break;
}
switch ($type) {
case 'boolean':
$valid = in_array($value, ['1', '0', 'false', 'true']);
break;
}
if (!$valid) {
if ($message) {
$this->stdErr->writeln($message);
} else {
$this->stdErr->writeln("Invalid value for <error>$property</error>: $value");
}
return false;
}
return true;
} | [
"protected",
"function",
"validateValue",
"(",
"$",
"property",
",",
"$",
"value",
")",
"{",
"$",
"type",
"=",
"$",
"this",
"->",
"getType",
"(",
"$",
"property",
")",
";",
"if",
"(",
"!",
"$",
"type",
")",
"{",
"$",
"this",
"->",
"stdErr",
"->",
... | @param string $property
@param string $value
@return bool | [
"@param",
"string",
"$property",
"@param",
"string",
"$value"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentInfoCommand.php#L175-L219 |
platformsh/platformsh-cli | src/Command/Domain/DomainGetCommand.php | DomainGetCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$project = $this->getSelectedProject();
$domainName = $input->getArgument('name');
if (empty($domainName)) {
if (!$input->isInteractive()) {
$this->stdErr->writeln('The domain name is required.');
return 1;
}
$domains = $project->getDomains();
$options = [];
foreach ($domains as $domain) {
$options[$domain->name] = $domain->name;
}
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$domainName = $questionHelper->choose($options, 'Enter a number to choose a domain:');
}
$domain = $project->getDomain($domainName);
if (!$domain) {
$this->stdErr->writeln('Domain not found: <error>' . $domainName . '</error>');
return 1;
}
/** @var \Platformsh\Cli\Service\PropertyFormatter $propertyFormatter */
$propertyFormatter = $this->getService('property_formatter');
if ($property = $input->getOption('property')) {
$value = $this->api()->getNestedProperty($domain, $property);
$output->writeln($propertyFormatter->format($value, $property));
return 0;
}
$values = [];
$properties = [];
foreach ($domain->getProperties() as $name => $value) {
// Hide the deprecated (irrelevant) property 'wildcard'.
if ($name === 'wildcard') {
continue;
}
$properties[] = $name;
$values[] = $propertyFormatter->format($value, $name);
}
/** @var \Platformsh\Cli\Service\Table $table */
$table = $this->getService('table');
$table->renderSimple($values, $properties);
$this->stdErr->writeln('');
$executable = $this->config()->get('application.executable');
$this->stdErr->writeln([
'To update a domain, run: <info>' . $executable . ' domain:update [domain-name]</info>',
'To delete a domain, run: <info>' . $executable . ' domain:delete [domain-name]</info>',
]);
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$project = $this->getSelectedProject();
$domainName = $input->getArgument('name');
if (empty($domainName)) {
if (!$input->isInteractive()) {
$this->stdErr->writeln('The domain name is required.');
return 1;
}
$domains = $project->getDomains();
$options = [];
foreach ($domains as $domain) {
$options[$domain->name] = $domain->name;
}
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$domainName = $questionHelper->choose($options, 'Enter a number to choose a domain:');
}
$domain = $project->getDomain($domainName);
if (!$domain) {
$this->stdErr->writeln('Domain not found: <error>' . $domainName . '</error>');
return 1;
}
/** @var \Platformsh\Cli\Service\PropertyFormatter $propertyFormatter */
$propertyFormatter = $this->getService('property_formatter');
if ($property = $input->getOption('property')) {
$value = $this->api()->getNestedProperty($domain, $property);
$output->writeln($propertyFormatter->format($value, $property));
return 0;
}
$values = [];
$properties = [];
foreach ($domain->getProperties() as $name => $value) {
// Hide the deprecated (irrelevant) property 'wildcard'.
if ($name === 'wildcard') {
continue;
}
$properties[] = $name;
$values[] = $propertyFormatter->format($value, $name);
}
/** @var \Platformsh\Cli\Service\Table $table */
$table = $this->getService('table');
$table->renderSimple($values, $properties);
$this->stdErr->writeln('');
$executable = $this->config()->get('application.executable');
$this->stdErr->writeln([
'To update a domain, run: <info>' . $executable . ' domain:update [domain-name]</info>',
'To delete a domain, run: <info>' . $executable . ' domain:delete [domain-name]</info>',
]);
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"validateInput",
"(",
"$",
"input",
")",
";",
"$",
"project",
"=",
"$",
"this",
"->",
"getSelectedProject",
"(",
")... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Domain/DomainGetCommand.php#L32-L92 |
platformsh/platformsh-cli | src/Local/LocalBuild.php | LocalBuild.build | public function build(array $settings, $sourceDir, $destination = null, array $apps = [])
{
$this->settings = $settings;
$this->fsHelper->setRelativeLinks(empty($settings['abslinks']));
if (file_exists($sourceDir . '/.git')) {
(new LocalProject())->writeGitExclude($sourceDir);
}
$ids = [];
$success = true;
foreach (LocalApplication::getApplications($sourceDir, $this->config) as $app) {
$id = $app->getId();
$ids[] = $id;
if ($apps && !in_array($id, $apps)) {
continue;
}
$success = $this->buildApp($app, $destination) && $success;
}
$notFounds = array_diff($apps, $ids);
if ($notFounds) {
foreach ($notFounds as $notFound) {
$this->output->writeln("Application not found: <comment>$notFound</comment>");
}
}
if (empty($settings['no-clean'])) {
$this->output->writeln("Cleaning up...");
$this->cleanBuilds($sourceDir);
$this->cleanArchives($sourceDir);
}
return $success;
} | php | public function build(array $settings, $sourceDir, $destination = null, array $apps = [])
{
$this->settings = $settings;
$this->fsHelper->setRelativeLinks(empty($settings['abslinks']));
if (file_exists($sourceDir . '/.git')) {
(new LocalProject())->writeGitExclude($sourceDir);
}
$ids = [];
$success = true;
foreach (LocalApplication::getApplications($sourceDir, $this->config) as $app) {
$id = $app->getId();
$ids[] = $id;
if ($apps && !in_array($id, $apps)) {
continue;
}
$success = $this->buildApp($app, $destination) && $success;
}
$notFounds = array_diff($apps, $ids);
if ($notFounds) {
foreach ($notFounds as $notFound) {
$this->output->writeln("Application not found: <comment>$notFound</comment>");
}
}
if (empty($settings['no-clean'])) {
$this->output->writeln("Cleaning up...");
$this->cleanBuilds($sourceDir);
$this->cleanArchives($sourceDir);
}
return $success;
} | [
"public",
"function",
"build",
"(",
"array",
"$",
"settings",
",",
"$",
"sourceDir",
",",
"$",
"destination",
"=",
"null",
",",
"array",
"$",
"apps",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"settings",
"=",
"$",
"settings",
";",
"$",
"this",
"-... | Build a project from any source directory, targeting any destination.
@param array $settings An array of build settings.
Possible settings:
- clone (bool, default false) Clone the repository to the build
directory before building, where possible.
- copy (bool, default false) Copy files instead of symlinking them,
where possible.
- abslinks (bool, default false) Use absolute paths in symlinks.
- no-archive (bool, default false) Do not archive or use an archive of
the build.
- no-cache (bool, default false) Disable the package cache (if
relevant and if the package manager supports this).
- no-clean (bool, default false) Disable cleaning up old builds or
old build archives.
- no-build-hooks (bool, default false) Disable running build hooks.
- no-deps (bool, default false) Disable installing build
dependencies.
- concurrency (int) Specify a concurrency for Drush Make, if
applicable (when using the Drupal build flavor).
- working-copy (bool, default false) Specify the --working-copy
option to Drush Make, if applicable.
- lock (bool, default false) Create or update a lock
file via Drush Make, if applicable.
- run-deploy-hooks (bool, default false) Run deploy and/or
post_deploy hooks.
@param string $sourceDir The absolute path to the source directory.
@param string $destination Where the web root(s) will be linked (absolute
path).
@param array $apps An array of application names to build.
@throws \Exception on failure
@return bool | [
"Build",
"a",
"project",
"from",
"any",
"source",
"directory",
"targeting",
"any",
"destination",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalBuild.php#L106-L138 |
platformsh/platformsh-cli | src/Local/LocalBuild.php | LocalBuild.getTreeId | public function getTreeId($appRoot)
{
$hashes = [];
// Get a hash representing all the files in the application, excluding
// the project config folder (configured in service.project_config_dir).
$tree = $this->gitHelper->execute(['ls-files', '-s'], $appRoot);
if ($tree === false) {
return false;
}
$tree = preg_replace(
'#^|\n[^\n]+?' . preg_quote($this->config->get('service.project_config_dir')) . '\n|$#',
"\n",
$tree
);
$hashes[] = sha1($tree);
// Include the hashes of untracked and modified files.
$others = $this->gitHelper->execute(
[
'ls-files',
'--modified',
'--others',
'--exclude-standard',
'-x ' . $this->config->get('service.project_config_dir'),
'.',
],
$appRoot
);
if ($others === false) {
return false;
}
$count = 0;
foreach (explode("\n", $others) as $filename) {
if ($count > 5000) {
return false;
}
$filename = "$appRoot/$filename";
if (is_file($filename)) {
$hashes[] = sha1_file($filename);
$count++;
}
}
// Include relevant build settings.
$relevant = ['abslinks', 'copy', 'clone', 'no-cache', 'working-copy', 'lock', 'no-deps'];
$settings = array_intersect_key($this->settings, array_flip($relevant));
$hashes[] = serialize($settings);
$hashes[] = self::BUILD_VERSION;
// Combine them all.
return sha1(implode(' ', $hashes));
} | php | public function getTreeId($appRoot)
{
$hashes = [];
// Get a hash representing all the files in the application, excluding
// the project config folder (configured in service.project_config_dir).
$tree = $this->gitHelper->execute(['ls-files', '-s'], $appRoot);
if ($tree === false) {
return false;
}
$tree = preg_replace(
'#^|\n[^\n]+?' . preg_quote($this->config->get('service.project_config_dir')) . '\n|$#',
"\n",
$tree
);
$hashes[] = sha1($tree);
// Include the hashes of untracked and modified files.
$others = $this->gitHelper->execute(
[
'ls-files',
'--modified',
'--others',
'--exclude-standard',
'-x ' . $this->config->get('service.project_config_dir'),
'.',
],
$appRoot
);
if ($others === false) {
return false;
}
$count = 0;
foreach (explode("\n", $others) as $filename) {
if ($count > 5000) {
return false;
}
$filename = "$appRoot/$filename";
if (is_file($filename)) {
$hashes[] = sha1_file($filename);
$count++;
}
}
// Include relevant build settings.
$relevant = ['abslinks', 'copy', 'clone', 'no-cache', 'working-copy', 'lock', 'no-deps'];
$settings = array_intersect_key($this->settings, array_flip($relevant));
$hashes[] = serialize($settings);
$hashes[] = self::BUILD_VERSION;
// Combine them all.
return sha1(implode(' ', $hashes));
} | [
"public",
"function",
"getTreeId",
"(",
"$",
"appRoot",
")",
"{",
"$",
"hashes",
"=",
"[",
"]",
";",
"// Get a hash representing all the files in the application, excluding",
"// the project config folder (configured in service.project_config_dir).",
"$",
"tree",
"=",
"$",
"t... | Get a hash of the application files.
This should change if any of the application files or build settings
change.
@param string $appRoot
@return string|false | [
"Get",
"a",
"hash",
"of",
"the",
"application",
"files",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalBuild.php#L150-L203 |
platformsh/platformsh-cli | src/Local/LocalBuild.php | LocalBuild.buildApp | protected function buildApp($app, $destination = null)
{
$verbose = $this->output->isVerbose();
$sourceDir = $app->getSourceDir();
$destination = $destination ?: $sourceDir . '/' . $this->config->get('local.web_root');
$appRoot = $app->getRoot();
$appConfig = $app->getConfig();
$appId = $app->getId();
$buildFlavor = $app->getBuildFlavor();
// Find the right build directory.
$buildName = $app->isSingle() ? 'default' : str_replace('/', '-', $appId);
$tmpBuildDir = $sourceDir . '/' . $this->config->get('local.build_dir') . '/' . $buildName . '-tmp';
if (file_exists($tmpBuildDir)) {
if (!$this->fsHelper->remove($tmpBuildDir)) {
$this->output->writeln(sprintf('Failed to remove directory <error>%s</error>', $tmpBuildDir));
return false;
}
}
// If the destination is inside the source directory, ensure it isn't
// copied or symlinked into the build.
if (strpos($destination, $sourceDir) === 0) {
$buildFlavor->addIgnoredFiles([
ltrim(substr($destination, strlen($sourceDir)), '/'),
]);
}
// Warn about a mismatched PHP version.
if (isset($appConfig['type']) && strpos($appConfig['type'], ':')) {
list($stack, $version) = explode(':', $appConfig['type'], 2);
if ($stack === 'php' && version_compare($version, PHP_VERSION, '>')) {
$this->output->writeln(sprintf(
'<comment>Warning:</comment> the application <comment>%s</comment> expects PHP %s, but the system version is %s.',
$appId,
$version,
PHP_VERSION
));
}
}
$buildFlavor->setOutput($this->output);
$buildFlavor->prepare($tmpBuildDir, $app, $this->config, $this->settings);
$archive = false;
if (empty($this->settings['no-archive']) && empty($this->settings['no-cache'])) {
$treeId = $this->getTreeId($appRoot);
if ($treeId) {
if ($verbose) {
$this->output->writeln("Tree ID: $treeId");
}
$archive = $sourceDir . '/' . $this->config->get('local.archive_dir') . '/' . $treeId . '.tar.gz';
}
}
$success = true;
if ($archive && file_exists($archive)) {
$message = "Extracting archive for application <info>$appId</info>";
$this->output->writeln($message);
$this->fsHelper->extractArchive($archive, $tmpBuildDir);
} else {
$message = "Building application <info>$appId</info>";
if (isset($appConfig['type'])) {
$message .= ' (runtime type: ' . $appConfig['type'] . ')';
}
$this->output->writeln($message);
// Install dependencies.
if (isset($appConfig['dependencies'])) {
$depsDir = $sourceDir . '/' . $this->config->get('local.dependencies_dir');
if (!empty($this->settings['no-deps'])) {
$this->output->writeln('Skipping build dependencies');
} else {
$result = $this->dependencyInstaller->installDependencies(
$depsDir,
$appConfig['dependencies']
);
$success = $success && $result;
}
// Use the dependencies' PATH and other environment variables
// for the rest of this process (for the build and build hooks).
$this->dependencyInstaller->putEnv($depsDir, $appConfig['dependencies']);
}
$buildFlavor->build();
if ($this->runPostBuildHooks($appConfig, $buildFlavor->getAppDir()) === false) {
// The user may not care if build hooks fail, but we should
// not archive the result.
$archive = false;
$success = false;
}
if ($archive && $buildFlavor->canArchive()) {
$this->output->writeln("Saving build archive");
if (!is_dir(dirname($archive))) {
mkdir(dirname($archive));
}
$this->fsHelper->archiveDir($tmpBuildDir, $archive);
}
}
// The build is complete. Move the directory.
$buildDir = substr($tmpBuildDir, 0, strlen($tmpBuildDir) - 4);
if (file_exists($buildDir)) {
if (empty($this->settings['no-backup']) && is_dir($buildDir) && !is_link($buildDir)) {
$previousBuildArchive = dirname($buildDir) . '/' . basename($buildDir) . '-old.tar.gz';
$this->output->writeln("Backing up previous build to: " . $previousBuildArchive);
$this->fsHelper->archiveDir($buildDir, $previousBuildArchive);
}
if (!$this->fsHelper->remove($buildDir, true)) {
$this->output->writeln(sprintf('Failed to remove directory <error>%s</error>', $buildDir));
return false;
}
}
if (!rename($tmpBuildDir, $buildDir)) {
$this->output->writeln(sprintf(
'Failed to move temporary build directory into <error>%s</error>',
$buildDir
));
return false;
}
$buildFlavor->setBuildDir($buildDir);
$buildFlavor->install();
$this->runDeployHooks($appConfig, $buildDir);
$webRoot = $buildFlavor->getWebRoot();
// Symlink the built web root ($webRoot) into www or www/appId.
if (!is_dir($webRoot)) {
$this->output->writeln("\nWeb root not found: <error>$webRoot</error>\n");
return false;
}
$localWebRoot = $app->getLocalWebRoot($destination);
$this->fsHelper->symlink($webRoot, $localWebRoot);
$message = "\nBuild complete for application <info>$appId</info>";
$this->output->writeln($message);
$this->output->writeln("Web root: <info>$localWebRoot</info>\n");
return $success;
} | php | protected function buildApp($app, $destination = null)
{
$verbose = $this->output->isVerbose();
$sourceDir = $app->getSourceDir();
$destination = $destination ?: $sourceDir . '/' . $this->config->get('local.web_root');
$appRoot = $app->getRoot();
$appConfig = $app->getConfig();
$appId = $app->getId();
$buildFlavor = $app->getBuildFlavor();
// Find the right build directory.
$buildName = $app->isSingle() ? 'default' : str_replace('/', '-', $appId);
$tmpBuildDir = $sourceDir . '/' . $this->config->get('local.build_dir') . '/' . $buildName . '-tmp';
if (file_exists($tmpBuildDir)) {
if (!$this->fsHelper->remove($tmpBuildDir)) {
$this->output->writeln(sprintf('Failed to remove directory <error>%s</error>', $tmpBuildDir));
return false;
}
}
// If the destination is inside the source directory, ensure it isn't
// copied or symlinked into the build.
if (strpos($destination, $sourceDir) === 0) {
$buildFlavor->addIgnoredFiles([
ltrim(substr($destination, strlen($sourceDir)), '/'),
]);
}
// Warn about a mismatched PHP version.
if (isset($appConfig['type']) && strpos($appConfig['type'], ':')) {
list($stack, $version) = explode(':', $appConfig['type'], 2);
if ($stack === 'php' && version_compare($version, PHP_VERSION, '>')) {
$this->output->writeln(sprintf(
'<comment>Warning:</comment> the application <comment>%s</comment> expects PHP %s, but the system version is %s.',
$appId,
$version,
PHP_VERSION
));
}
}
$buildFlavor->setOutput($this->output);
$buildFlavor->prepare($tmpBuildDir, $app, $this->config, $this->settings);
$archive = false;
if (empty($this->settings['no-archive']) && empty($this->settings['no-cache'])) {
$treeId = $this->getTreeId($appRoot);
if ($treeId) {
if ($verbose) {
$this->output->writeln("Tree ID: $treeId");
}
$archive = $sourceDir . '/' . $this->config->get('local.archive_dir') . '/' . $treeId . '.tar.gz';
}
}
$success = true;
if ($archive && file_exists($archive)) {
$message = "Extracting archive for application <info>$appId</info>";
$this->output->writeln($message);
$this->fsHelper->extractArchive($archive, $tmpBuildDir);
} else {
$message = "Building application <info>$appId</info>";
if (isset($appConfig['type'])) {
$message .= ' (runtime type: ' . $appConfig['type'] . ')';
}
$this->output->writeln($message);
// Install dependencies.
if (isset($appConfig['dependencies'])) {
$depsDir = $sourceDir . '/' . $this->config->get('local.dependencies_dir');
if (!empty($this->settings['no-deps'])) {
$this->output->writeln('Skipping build dependencies');
} else {
$result = $this->dependencyInstaller->installDependencies(
$depsDir,
$appConfig['dependencies']
);
$success = $success && $result;
}
// Use the dependencies' PATH and other environment variables
// for the rest of this process (for the build and build hooks).
$this->dependencyInstaller->putEnv($depsDir, $appConfig['dependencies']);
}
$buildFlavor->build();
if ($this->runPostBuildHooks($appConfig, $buildFlavor->getAppDir()) === false) {
// The user may not care if build hooks fail, but we should
// not archive the result.
$archive = false;
$success = false;
}
if ($archive && $buildFlavor->canArchive()) {
$this->output->writeln("Saving build archive");
if (!is_dir(dirname($archive))) {
mkdir(dirname($archive));
}
$this->fsHelper->archiveDir($tmpBuildDir, $archive);
}
}
// The build is complete. Move the directory.
$buildDir = substr($tmpBuildDir, 0, strlen($tmpBuildDir) - 4);
if (file_exists($buildDir)) {
if (empty($this->settings['no-backup']) && is_dir($buildDir) && !is_link($buildDir)) {
$previousBuildArchive = dirname($buildDir) . '/' . basename($buildDir) . '-old.tar.gz';
$this->output->writeln("Backing up previous build to: " . $previousBuildArchive);
$this->fsHelper->archiveDir($buildDir, $previousBuildArchive);
}
if (!$this->fsHelper->remove($buildDir, true)) {
$this->output->writeln(sprintf('Failed to remove directory <error>%s</error>', $buildDir));
return false;
}
}
if (!rename($tmpBuildDir, $buildDir)) {
$this->output->writeln(sprintf(
'Failed to move temporary build directory into <error>%s</error>',
$buildDir
));
return false;
}
$buildFlavor->setBuildDir($buildDir);
$buildFlavor->install();
$this->runDeployHooks($appConfig, $buildDir);
$webRoot = $buildFlavor->getWebRoot();
// Symlink the built web root ($webRoot) into www or www/appId.
if (!is_dir($webRoot)) {
$this->output->writeln("\nWeb root not found: <error>$webRoot</error>\n");
return false;
}
$localWebRoot = $app->getLocalWebRoot($destination);
$this->fsHelper->symlink($webRoot, $localWebRoot);
$message = "\nBuild complete for application <info>$appId</info>";
$this->output->writeln($message);
$this->output->writeln("Web root: <info>$localWebRoot</info>\n");
return $success;
} | [
"protected",
"function",
"buildApp",
"(",
"$",
"app",
",",
"$",
"destination",
"=",
"null",
")",
"{",
"$",
"verbose",
"=",
"$",
"this",
"->",
"output",
"->",
"isVerbose",
"(",
")",
";",
"$",
"sourceDir",
"=",
"$",
"app",
"->",
"getSourceDir",
"(",
")... | Build a single application.
@param LocalApplication $app
@param string|null $destination
@return bool | [
"Build",
"a",
"single",
"application",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalBuild.php#L213-L368 |
platformsh/platformsh-cli | src/Local/LocalBuild.php | LocalBuild.runPostBuildHooks | protected function runPostBuildHooks(array $appConfig, $buildDir)
{
if (!isset($appConfig['hooks']['build'])) {
return null;
}
if (!empty($this->settings['no-build-hooks'])) {
$this->output->writeln('Skipping post-build hooks');
return null;
}
$this->output->writeln('Running post-build hooks');
return $this->runHook($appConfig['hooks']['build'], $buildDir);
} | php | protected function runPostBuildHooks(array $appConfig, $buildDir)
{
if (!isset($appConfig['hooks']['build'])) {
return null;
}
if (!empty($this->settings['no-build-hooks'])) {
$this->output->writeln('Skipping post-build hooks');
return null;
}
$this->output->writeln('Running post-build hooks');
return $this->runHook($appConfig['hooks']['build'], $buildDir);
} | [
"protected",
"function",
"runPostBuildHooks",
"(",
"array",
"$",
"appConfig",
",",
"$",
"buildDir",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"appConfig",
"[",
"'hooks'",
"]",
"[",
"'build'",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"... | Run post-build hooks.
@param array $appConfig
@param string $buildDir
@return bool|null
False if the build hooks fail, true if they succeed, null if not
applicable. | [
"Run",
"post",
"-",
"build",
"hooks",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalBuild.php#L380-L392 |
platformsh/platformsh-cli | src/Local/LocalBuild.php | LocalBuild.runDeployHooks | protected function runDeployHooks(array $appConfig, $appDir)
{
if (empty($this->settings['run-deploy-hooks'])) {
return null;
}
if (empty($appConfig['hooks']['deploy']) && empty($appConfig['hooks']['post_deploy'])) {
$this->output->writeln('No deploy or post_deploy hooks found');
return null;
}
$result = null;
if (!empty($appConfig['hooks']['deploy'])) {
$this->output->writeln('Running deploy hooks');
$result = $this->runHook($appConfig['hooks']['deploy'], $appDir);
}
if (!empty($appConfig['hooks']['post_deploy']) && $result !== false) {
$this->output->writeln('Running post_deploy hooks');
$result = $this->runHook($appConfig['hooks']['post_deploy'], $appDir);
}
return $result;
} | php | protected function runDeployHooks(array $appConfig, $appDir)
{
if (empty($this->settings['run-deploy-hooks'])) {
return null;
}
if (empty($appConfig['hooks']['deploy']) && empty($appConfig['hooks']['post_deploy'])) {
$this->output->writeln('No deploy or post_deploy hooks found');
return null;
}
$result = null;
if (!empty($appConfig['hooks']['deploy'])) {
$this->output->writeln('Running deploy hooks');
$result = $this->runHook($appConfig['hooks']['deploy'], $appDir);
}
if (!empty($appConfig['hooks']['post_deploy']) && $result !== false) {
$this->output->writeln('Running post_deploy hooks');
$result = $this->runHook($appConfig['hooks']['post_deploy'], $appDir);
}
return $result;
} | [
"protected",
"function",
"runDeployHooks",
"(",
"array",
"$",
"appConfig",
",",
"$",
"appDir",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"settings",
"[",
"'run-deploy-hooks'",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"empt... | Run deploy and post_deploy hooks.
@param array $appConfig
@param string $appDir
@return bool|null
False if the deploy hooks fail, true if they succeed, null if not
applicable. | [
"Run",
"deploy",
"and",
"post_deploy",
"hooks",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalBuild.php#L404-L424 |
platformsh/platformsh-cli | src/Local/LocalBuild.php | LocalBuild.runHook | protected function runHook($hook, $dir)
{
$code = $this->shellHelper->executeSimple(
implode("\n", (array) $hook),
$dir
);
if ($code !== 0) {
$this->output->writeln("<comment>The hook failed with the exit code: $code</comment>");
return false;
}
return true;
} | php | protected function runHook($hook, $dir)
{
$code = $this->shellHelper->executeSimple(
implode("\n", (array) $hook),
$dir
);
if ($code !== 0) {
$this->output->writeln("<comment>The hook failed with the exit code: $code</comment>");
return false;
}
return true;
} | [
"protected",
"function",
"runHook",
"(",
"$",
"hook",
",",
"$",
"dir",
")",
"{",
"$",
"code",
"=",
"$",
"this",
"->",
"shellHelper",
"->",
"executeSimple",
"(",
"implode",
"(",
"\"\\n\"",
",",
"(",
"array",
")",
"$",
"hook",
")",
",",
"$",
"dir",
"... | Run a user-defined hook.
@param string|array $hook
@param string $dir
@return bool | [
"Run",
"a",
"user",
"-",
"defined",
"hook",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalBuild.php#L434-L446 |
platformsh/platformsh-cli | src/Local/LocalBuild.php | LocalBuild.cleanBuilds | public function cleanBuilds($projectRoot, $maxAge = null, $keepMax = 10, $includeActive = false, $quiet = true)
{
// Find all the potentially active symlinks, which might be www itself
// or symlinks inside www. This is so we can avoid deleting the active
// build(s).
$blacklist = [];
if (!$includeActive) {
$blacklist = $this->getActiveBuilds($projectRoot);
}
return $this->cleanDirectory(
$projectRoot . '/' . $this->config->get('local.build_dir'),
$maxAge,
$keepMax,
$blacklist,
$quiet
);
} | php | public function cleanBuilds($projectRoot, $maxAge = null, $keepMax = 10, $includeActive = false, $quiet = true)
{
// Find all the potentially active symlinks, which might be www itself
// or symlinks inside www. This is so we can avoid deleting the active
// build(s).
$blacklist = [];
if (!$includeActive) {
$blacklist = $this->getActiveBuilds($projectRoot);
}
return $this->cleanDirectory(
$projectRoot . '/' . $this->config->get('local.build_dir'),
$maxAge,
$keepMax,
$blacklist,
$quiet
);
} | [
"public",
"function",
"cleanBuilds",
"(",
"$",
"projectRoot",
",",
"$",
"maxAge",
"=",
"null",
",",
"$",
"keepMax",
"=",
"10",
",",
"$",
"includeActive",
"=",
"false",
",",
"$",
"quiet",
"=",
"true",
")",
"{",
"// Find all the potentially active symlinks, whic... | Remove old builds.
This preserves the currently active build.
@param string $projectRoot
@param int|null $maxAge
@param int $keepMax
@param bool $includeActive
@param bool $quiet
@return int[]
The numbers of deleted and kept builds. | [
"Remove",
"old",
"builds",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalBuild.php#L462-L479 |
platformsh/platformsh-cli | src/Local/LocalBuild.php | LocalBuild.getActiveBuilds | protected function getActiveBuilds($projectRoot)
{
$www = $projectRoot . '/' . $this->config->get('local.web_root');
if (!file_exists($www)) {
return [];
}
$links = [$www];
if (!is_link($www) && is_dir($www)) {
$finder = new Finder();
/** @var \Symfony\Component\Finder\SplFileInfo $file */
foreach ($finder->in($www)
->directories()
->depth(0) as $file) {
$links[] = $file->getPathname();
}
}
$activeBuilds = [];
$buildsDir = $projectRoot . '/' . $this->config->get('local.build_dir');
foreach ($links as $link) {
if (is_link($link) && ($target = readlink($link))) {
// Make the target into an absolute path.
$target = $target[0] === DIRECTORY_SEPARATOR ? $target : realpath(dirname($link) . '/' . $target);
if (!$target) {
continue;
}
// Ignore the target if it doesn't point to a build in 'builds'.
if (strpos($target, $buildsDir) === false) {
continue;
}
// The target should just be one level below the 'builds'
// directory, not more.
while (dirname($target) != $buildsDir) {
$target = dirname($target);
if (strpos($target, $buildsDir) === false) {
throw new \Exception('Error resolving active build directory');
}
}
$activeBuilds[] = $target;
}
}
return $activeBuilds;
} | php | protected function getActiveBuilds($projectRoot)
{
$www = $projectRoot . '/' . $this->config->get('local.web_root');
if (!file_exists($www)) {
return [];
}
$links = [$www];
if (!is_link($www) && is_dir($www)) {
$finder = new Finder();
/** @var \Symfony\Component\Finder\SplFileInfo $file */
foreach ($finder->in($www)
->directories()
->depth(0) as $file) {
$links[] = $file->getPathname();
}
}
$activeBuilds = [];
$buildsDir = $projectRoot . '/' . $this->config->get('local.build_dir');
foreach ($links as $link) {
if (is_link($link) && ($target = readlink($link))) {
// Make the target into an absolute path.
$target = $target[0] === DIRECTORY_SEPARATOR ? $target : realpath(dirname($link) . '/' . $target);
if (!$target) {
continue;
}
// Ignore the target if it doesn't point to a build in 'builds'.
if (strpos($target, $buildsDir) === false) {
continue;
}
// The target should just be one level below the 'builds'
// directory, not more.
while (dirname($target) != $buildsDir) {
$target = dirname($target);
if (strpos($target, $buildsDir) === false) {
throw new \Exception('Error resolving active build directory');
}
}
$activeBuilds[] = $target;
}
}
return $activeBuilds;
} | [
"protected",
"function",
"getActiveBuilds",
"(",
"$",
"projectRoot",
")",
"{",
"$",
"www",
"=",
"$",
"projectRoot",
".",
"'/'",
".",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'local.web_root'",
")",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"... | @param string $projectRoot
@throws \Exception If it cannot be determined whether or not a symlink
points to a genuine active build.
@return array The absolute paths to any active builds in the project. | [
"@param",
"string",
"$projectRoot"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalBuild.php#L489-L531 |
platformsh/platformsh-cli | src/Local/LocalBuild.php | LocalBuild.cleanArchives | public function cleanArchives($projectRoot, $maxAge = null, $keepMax = 10, $quiet = true)
{
return $this->cleanDirectory(
$projectRoot . '/' . $this->config->get('local.archive_dir'),
$maxAge,
$keepMax,
[],
$quiet
);
} | php | public function cleanArchives($projectRoot, $maxAge = null, $keepMax = 10, $quiet = true)
{
return $this->cleanDirectory(
$projectRoot . '/' . $this->config->get('local.archive_dir'),
$maxAge,
$keepMax,
[],
$quiet
);
} | [
"public",
"function",
"cleanArchives",
"(",
"$",
"projectRoot",
",",
"$",
"maxAge",
"=",
"null",
",",
"$",
"keepMax",
"=",
"10",
",",
"$",
"quiet",
"=",
"true",
")",
"{",
"return",
"$",
"this",
"->",
"cleanDirectory",
"(",
"$",
"projectRoot",
".",
"'/'... | Remove old build archives.
@param string $projectRoot
@param int|null $maxAge
@param int $keepMax
@param bool $quiet
@return int[]
The numbers of deleted and kept builds. | [
"Remove",
"old",
"build",
"archives",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalBuild.php#L544-L553 |
platformsh/platformsh-cli | src/Local/LocalBuild.php | LocalBuild.cleanDirectory | protected function cleanDirectory($directory, $maxAge = null, $keepMax = 5, array $blacklist = [], $quiet = true)
{
if (!is_dir($directory)) {
return [0, 0];
}
$files = glob($directory . '/*');
if (!$files) {
return [0, 0];
}
// Sort files by modified time (descending).
usort(
$files,
function ($a, $b) {
return filemtime($a) < filemtime($b);
}
);
$now = time();
$numDeleted = 0;
$numKept = 0;
foreach ($files as $filename) {
if (in_array($filename, $blacklist)) {
$numKept++;
continue;
}
if (($keepMax !== null && $numKept >= $keepMax)
|| ($maxAge !== null && $now - filemtime($filename) > $maxAge)) {
if (!$quiet) {
$this->output->writeln("Deleting: " . basename($filename));
}
if ($this->fsHelper->remove($filename)) {
$numDeleted++;
} elseif (!$quiet) {
$this->output->writeln("Failed to delete: <error>" . basename($filename) . "</error>");
}
} else {
$numKept++;
}
}
return [$numDeleted, $numKept];
} | php | protected function cleanDirectory($directory, $maxAge = null, $keepMax = 5, array $blacklist = [], $quiet = true)
{
if (!is_dir($directory)) {
return [0, 0];
}
$files = glob($directory . '/*');
if (!$files) {
return [0, 0];
}
// Sort files by modified time (descending).
usort(
$files,
function ($a, $b) {
return filemtime($a) < filemtime($b);
}
);
$now = time();
$numDeleted = 0;
$numKept = 0;
foreach ($files as $filename) {
if (in_array($filename, $blacklist)) {
$numKept++;
continue;
}
if (($keepMax !== null && $numKept >= $keepMax)
|| ($maxAge !== null && $now - filemtime($filename) > $maxAge)) {
if (!$quiet) {
$this->output->writeln("Deleting: " . basename($filename));
}
if ($this->fsHelper->remove($filename)) {
$numDeleted++;
} elseif (!$quiet) {
$this->output->writeln("Failed to delete: <error>" . basename($filename) . "</error>");
}
} else {
$numKept++;
}
}
return [$numDeleted, $numKept];
} | [
"protected",
"function",
"cleanDirectory",
"(",
"$",
"directory",
",",
"$",
"maxAge",
"=",
"null",
",",
"$",
"keepMax",
"=",
"5",
",",
"array",
"$",
"blacklist",
"=",
"[",
"]",
",",
"$",
"quiet",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"is_dir",
"("... | Remove old files from a directory.
@param string $directory
@param int|null $maxAge
@param int $keepMax
@param array $blacklist
@param bool $quiet
@return int[] | [
"Remove",
"old",
"files",
"from",
"a",
"directory",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalBuild.php#L566-L606 |
platformsh/platformsh-cli | src/Command/Local/LocalDrushAliasesCommand.php | LocalDrushAliasesCommand.ensureDrushConfig | protected function ensureDrushConfig(Drush $drush)
{
if (!is_dir($drush->getSiteAliasDir())) {
return;
}
$drushYml = $drush->getDrushDir() . '/drush.yml';
$drushConfig = [];
if (file_exists($drushYml)) {
$drushConfig = (array) Yaml::parse(file_get_contents($drushYml));
}
$aliasPath = $drush->getSiteAliasDir();
if (getenv('HOME')) {
$aliasPath = str_replace(getenv('HOME') . '/', '${env.home}/', $aliasPath);
}
if (empty($drushConfig['drush']['paths']['alias-path'])
|| !in_array($aliasPath, $drushConfig['drush']['paths']['alias-path'], true)) {
if (file_exists($drushYml)) {
$this->stdErr->writeln('Writing to <info>~/.drush/drush.yml</info> file to configure the global alias-path');
} else {
$this->stdErr->writeln('Creating <info>~/.drush/drush.yml</info> file to configure the global alias-path');
}
$drushConfig['drush']['paths']['alias-path'][] = $aliasPath;
/** @var \Platformsh\Cli\Service\Filesystem $fs */
$fs = $this->getService('fs');
$fs->writeFile($drushYml, Yaml::dump($drushConfig, 5));
}
} | php | protected function ensureDrushConfig(Drush $drush)
{
if (!is_dir($drush->getSiteAliasDir())) {
return;
}
$drushYml = $drush->getDrushDir() . '/drush.yml';
$drushConfig = [];
if (file_exists($drushYml)) {
$drushConfig = (array) Yaml::parse(file_get_contents($drushYml));
}
$aliasPath = $drush->getSiteAliasDir();
if (getenv('HOME')) {
$aliasPath = str_replace(getenv('HOME') . '/', '${env.home}/', $aliasPath);
}
if (empty($drushConfig['drush']['paths']['alias-path'])
|| !in_array($aliasPath, $drushConfig['drush']['paths']['alias-path'], true)) {
if (file_exists($drushYml)) {
$this->stdErr->writeln('Writing to <info>~/.drush/drush.yml</info> file to configure the global alias-path');
} else {
$this->stdErr->writeln('Creating <info>~/.drush/drush.yml</info> file to configure the global alias-path');
}
$drushConfig['drush']['paths']['alias-path'][] = $aliasPath;
/** @var \Platformsh\Cli\Service\Filesystem $fs */
$fs = $this->getService('fs');
$fs->writeFile($drushYml, Yaml::dump($drushConfig, 5));
}
} | [
"protected",
"function",
"ensureDrushConfig",
"(",
"Drush",
"$",
"drush",
")",
"{",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"drush",
"->",
"getSiteAliasDir",
"(",
")",
")",
")",
"{",
"return",
";",
"}",
"$",
"drushYml",
"=",
"$",
"drush",
"->",
"getDrushDi... | Ensure that the .drush/drush.yml file has the right config.
@param \Platformsh\Cli\Service\Drush $drush | [
"Ensure",
"that",
"the",
".",
"drush",
"/",
"drush",
".",
"yml",
"file",
"has",
"the",
"right",
"config",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Local/LocalDrushAliasesCommand.php#L167-L196 |
platformsh/platformsh-cli | src/Command/Local/LocalDrushAliasesCommand.php | LocalDrushAliasesCommand.migrateAliasFiles | protected function migrateAliasFiles(Drush $drush)
{
$newDrushDir = $drush->getHomeDir() . '/.drush/site-aliases';
$oldFilenames = $drush->getLegacyAliasFiles();
if (empty($oldFilenames)) {
return;
}
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$newDrushDirRelative = str_replace($drush->getHomeDir() . '/', '~/', $newDrushDir);
$confirmText = "Do you want to move your global Drush alias files from <comment>~/.drush</comment> to <comment>$newDrushDirRelative</comment>?";
if (!$questionHelper->confirm($confirmText)) {
return;
}
if (!file_exists($newDrushDir) && !mkdir($newDrushDir, 0755, true)) {
$this->stdErr->writeln(sprintf('Failed to create directory: <error>%s</error>', $newDrushDir));
$this->stdErr->writeln('The alias files have not been moved.');
return;
}
$success = true;
foreach ($oldFilenames as $oldFilename) {
$newFilename = $newDrushDir . '/' . basename($oldFilename);
if (file_exists($newFilename)) {
$this->stdErr->writeln("Failed to move file <error>$oldFilename</error>, because the destination file already exists.");
$success = false;
} elseif (!rename($oldFilename, $newFilename)) {
$this->stdErr->writeln("Failed to move file <error>$oldFilename</error> to <error>$newFilename</error>");
$success = false;
}
}
if ($success) {
$this->stdErr->writeln(sprintf('Global Drush alias files have been successfully moved to <info>%s</info>.', $newDrushDirRelative));
}
} | php | protected function migrateAliasFiles(Drush $drush)
{
$newDrushDir = $drush->getHomeDir() . '/.drush/site-aliases';
$oldFilenames = $drush->getLegacyAliasFiles();
if (empty($oldFilenames)) {
return;
}
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$newDrushDirRelative = str_replace($drush->getHomeDir() . '/', '~/', $newDrushDir);
$confirmText = "Do you want to move your global Drush alias files from <comment>~/.drush</comment> to <comment>$newDrushDirRelative</comment>?";
if (!$questionHelper->confirm($confirmText)) {
return;
}
if (!file_exists($newDrushDir) && !mkdir($newDrushDir, 0755, true)) {
$this->stdErr->writeln(sprintf('Failed to create directory: <error>%s</error>', $newDrushDir));
$this->stdErr->writeln('The alias files have not been moved.');
return;
}
$success = true;
foreach ($oldFilenames as $oldFilename) {
$newFilename = $newDrushDir . '/' . basename($oldFilename);
if (file_exists($newFilename)) {
$this->stdErr->writeln("Failed to move file <error>$oldFilename</error>, because the destination file already exists.");
$success = false;
} elseif (!rename($oldFilename, $newFilename)) {
$this->stdErr->writeln("Failed to move file <error>$oldFilename</error> to <error>$newFilename</error>");
$success = false;
}
}
if ($success) {
$this->stdErr->writeln(sprintf('Global Drush alias files have been successfully moved to <info>%s</info>.', $newDrushDirRelative));
}
} | [
"protected",
"function",
"migrateAliasFiles",
"(",
"Drush",
"$",
"drush",
")",
"{",
"$",
"newDrushDir",
"=",
"$",
"drush",
"->",
"getHomeDir",
"(",
")",
".",
"'/.drush/site-aliases'",
";",
"$",
"oldFilenames",
"=",
"$",
"drush",
"->",
"getLegacyAliasFiles",
"(... | Migrate old alias file(s) from ~/.drush to ~/.drush/site-aliases.
@param \Platformsh\Cli\Service\Drush $drush | [
"Migrate",
"old",
"alias",
"file",
"(",
"s",
")",
"from",
"~",
"/",
".",
"drush",
"to",
"~",
"/",
".",
"drush",
"/",
"site",
"-",
"aliases",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Local/LocalDrushAliasesCommand.php#L203-L240 |
platformsh/platformsh-cli | src/Command/Domain/DomainAddCommand.php | DomainAddCommand.configure | protected function configure()
{
$this
->setName('domain:add')
->setDescription('Add a new domain to the project');
$this->addDomainOptions();
$this->addProjectOption()->addWaitOptions();
$this->addExample('Add the domain example.com', 'example.com');
$this->addExample(
'Add the domain secure.example.com with SSL enabled',
'secure.example.com --cert secure-example-com.crt --key secure-example-com.key'
);
} | php | protected function configure()
{
$this
->setName('domain:add')
->setDescription('Add a new domain to the project');
$this->addDomainOptions();
$this->addProjectOption()->addWaitOptions();
$this->addExample('Add the domain example.com', 'example.com');
$this->addExample(
'Add the domain secure.example.com with SSL enabled',
'secure.example.com --cert secure-example-com.crt --key secure-example-com.key'
);
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'domain:add'",
")",
"->",
"setDescription",
"(",
"'Add a new domain to the project'",
")",
";",
"$",
"this",
"->",
"addDomainOptions",
"(",
")",
";",
"$",
"this",
"->",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Domain/DomainAddCommand.php#L14-L26 |
platformsh/platformsh-cli | src/Command/Domain/DomainAddCommand.php | DomainAddCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
if (!$this->validateDomainInput($input)) {
return 1;
}
$project = $this->getSelectedProject();
try {
$this->stdErr->writeln("Adding the domain <info>{$this->domainName}</info>");
$result = $project->addDomain($this->domainName, $this->sslOptions);
} catch (ClientException $e) {
// Catch 409 Conflict errors.
$response = $e->getResponse();
if ($response && $response->getStatusCode() === 409) {
$this->stdErr->writeln("The domain <error>{$this->domainName}</error> already exists on the project.");
$this->stdErr->writeln("Use <info>domain:delete</info> to delete an existing domain");
} else {
$this->handleApiException($e, $project);
}
return 1;
}
if ($this->shouldWait($input)) {
/** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */
$activityMonitor = $this->getService('activity_monitor');
$activityMonitor->waitMultiple($result->getActivities(), $project);
}
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
if (!$this->validateDomainInput($input)) {
return 1;
}
$project = $this->getSelectedProject();
try {
$this->stdErr->writeln("Adding the domain <info>{$this->domainName}</info>");
$result = $project->addDomain($this->domainName, $this->sslOptions);
} catch (ClientException $e) {
// Catch 409 Conflict errors.
$response = $e->getResponse();
if ($response && $response->getStatusCode() === 409) {
$this->stdErr->writeln("The domain <error>{$this->domainName}</error> already exists on the project.");
$this->stdErr->writeln("Use <info>domain:delete</info> to delete an existing domain");
} else {
$this->handleApiException($e, $project);
}
return 1;
}
if ($this->shouldWait($input)) {
/** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */
$activityMonitor = $this->getService('activity_monitor');
$activityMonitor->waitMultiple($result->getActivities(), $project);
}
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"validateInput",
"(",
"$",
"input",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"validateDomainInput",
"(",
"$",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Domain/DomainAddCommand.php#L31-L64 |
platformsh/platformsh-cli | src/Local/LocalApplication.php | LocalApplication.getLocalWebRoot | public function getLocalWebRoot($destination = null)
{
$destination = $destination ?: $this->getSourceDir() . '/' . $this->cliConfig->get('local.web_root');
if ($this->isSingle()) {
return $destination;
}
return $destination . '/' . str_replace('/', '-', $this->getId());
} | php | public function getLocalWebRoot($destination = null)
{
$destination = $destination ?: $this->getSourceDir() . '/' . $this->cliConfig->get('local.web_root');
if ($this->isSingle()) {
return $destination;
}
return $destination . '/' . str_replace('/', '-', $this->getId());
} | [
"public",
"function",
"getLocalWebRoot",
"(",
"$",
"destination",
"=",
"null",
")",
"{",
"$",
"destination",
"=",
"$",
"destination",
"?",
":",
"$",
"this",
"->",
"getSourceDir",
"(",
")",
".",
"'/'",
".",
"$",
"this",
"->",
"cliConfig",
"->",
"get",
"... | Get the absolute path to the local web root of this app.
@param string|null $destination
@return string | [
"Get",
"the",
"absolute",
"path",
"to",
"the",
"local",
"web",
"root",
"of",
"this",
"app",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalApplication.php#L114-L122 |
platformsh/platformsh-cli | src/Local/LocalApplication.php | LocalApplication.getConfigObject | private function getConfigObject()
{
if (!isset($this->config)) {
$config = [];
$file = $this->appRoot . '/' . $this->cliConfig->get('service.app_config_file');
if (file_exists($file)) {
$config = (array) (new YamlParser())->parseFile($file);
}
$this->config = new AppConfig($config);
}
return $this->config;
} | php | private function getConfigObject()
{
if (!isset($this->config)) {
$config = [];
$file = $this->appRoot . '/' . $this->cliConfig->get('service.app_config_file');
if (file_exists($file)) {
$config = (array) (new YamlParser())->parseFile($file);
}
$this->config = new AppConfig($config);
}
return $this->config;
} | [
"private",
"function",
"getConfigObject",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"config",
")",
")",
"{",
"$",
"config",
"=",
"[",
"]",
";",
"$",
"file",
"=",
"$",
"this",
"->",
"appRoot",
".",
"'/'",
".",
"$",
"this",
... | Get the application's configuration as an object.
@throws \Exception if the configuration file cannot be read
@throws InvalidConfigException if config is invalid
@return AppConfig | [
"Get",
"the",
"application",
"s",
"configuration",
"as",
"an",
"object",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalApplication.php#L152-L164 |
platformsh/platformsh-cli | src/Local/LocalApplication.php | LocalApplication.getBuildFlavor | public function getBuildFlavor()
{
$appConfig = $this->getConfig();
if (!isset($appConfig['type'])) {
throw new InvalidConfigException('Application configuration key not found: `type`');
}
$key = isset($appConfig['build']['flavor']) ? $appConfig['build']['flavor'] : 'default';
list($stack, ) = explode(':', $appConfig['type'], 2);
foreach (self::getBuildFlavors() as $candidate) {
if (in_array($key, $candidate->getKeys())
&& ($candidate->getStacks() === [] || in_array($stack, $candidate->getStacks()))) {
return $candidate;
}
}
throw new InvalidConfigException('Build flavor not found: ' . $key);
} | php | public function getBuildFlavor()
{
$appConfig = $this->getConfig();
if (!isset($appConfig['type'])) {
throw new InvalidConfigException('Application configuration key not found: `type`');
}
$key = isset($appConfig['build']['flavor']) ? $appConfig['build']['flavor'] : 'default';
list($stack, ) = explode(':', $appConfig['type'], 2);
foreach (self::getBuildFlavors() as $candidate) {
if (in_array($key, $candidate->getKeys())
&& ($candidate->getStacks() === [] || in_array($stack, $candidate->getStacks()))) {
return $candidate;
}
}
throw new InvalidConfigException('Build flavor not found: ' . $key);
} | [
"public",
"function",
"getBuildFlavor",
"(",
")",
"{",
"$",
"appConfig",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"appConfig",
"[",
"'type'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidConfigException",
"(... | Get the build flavor for the application.
@throws InvalidConfigException If a build flavor is not found.
@return BuildFlavorInterface | [
"Get",
"the",
"build",
"flavor",
"for",
"the",
"application",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalApplication.php#L197-L213 |
platformsh/platformsh-cli | src/Local/LocalApplication.php | LocalApplication.getApplications | public static function getApplications($directory, Config $config = null)
{
// Finder can be extremely slow with a deep directory structure. The
// search depth is limited to safeguard against this.
$finder = new Finder();
$config = $config ?: new Config();
$finder->in($directory)
->ignoreDotFiles(false)
->name($config->get('service.app_config_file'))
->ignoreUnreadableDirs()
->exclude([
'.idea',
$config->get('local.local_dir'),
'builds',
'node_modules',
'vendor',
])
->depth('< 5');
/** @var \Platformsh\Cli\Local\LocalApplication[] $applications */
$applications = [];
/** @var \Symfony\Component\Finder\SplFileInfo $file */
foreach ($finder as $file) {
$appRoot = dirname($file->getRealPath());
$applications[$appRoot] = new LocalApplication($appRoot, $config, $directory);
}
// If there are no application config files found, treat the
// directory as a single application.
if (empty($applications)) {
$applications[$directory] = new LocalApplication($directory, $config, $directory);
}
if (count($applications) === 1) {
foreach ($applications as $application) {
$application->setSingle(true);
break;
}
}
return $applications;
} | php | public static function getApplications($directory, Config $config = null)
{
// Finder can be extremely slow with a deep directory structure. The
// search depth is limited to safeguard against this.
$finder = new Finder();
$config = $config ?: new Config();
$finder->in($directory)
->ignoreDotFiles(false)
->name($config->get('service.app_config_file'))
->ignoreUnreadableDirs()
->exclude([
'.idea',
$config->get('local.local_dir'),
'builds',
'node_modules',
'vendor',
])
->depth('< 5');
/** @var \Platformsh\Cli\Local\LocalApplication[] $applications */
$applications = [];
/** @var \Symfony\Component\Finder\SplFileInfo $file */
foreach ($finder as $file) {
$appRoot = dirname($file->getRealPath());
$applications[$appRoot] = new LocalApplication($appRoot, $config, $directory);
}
// If there are no application config files found, treat the
// directory as a single application.
if (empty($applications)) {
$applications[$directory] = new LocalApplication($directory, $config, $directory);
}
if (count($applications) === 1) {
foreach ($applications as $application) {
$application->setSingle(true);
break;
}
}
return $applications;
} | [
"public",
"static",
"function",
"getApplications",
"(",
"$",
"directory",
",",
"Config",
"$",
"config",
"=",
"null",
")",
"{",
"// Finder can be extremely slow with a deep directory structure. The",
"// search depth is limited to safeguard against this.",
"$",
"finder",
"=",
... | Get a list of applications in a directory.
@param string $directory
The absolute path to a directory.
@param Config|null $config
CLI configuration.
@return LocalApplication[] | [
"Get",
"a",
"list",
"of",
"applications",
"in",
"a",
"directory",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalApplication.php#L225-L267 |
platformsh/platformsh-cli | src/Local/LocalApplication.php | LocalApplication.shouldMoveToRoot | public function shouldMoveToRoot()
{
$config = $this->getConfig();
if (isset($config['move_to_root']) && $config['move_to_root'] === true) {
return true;
}
return $this->getDocumentRoot() === 'public' && !is_dir($this->getRoot() . '/public');
} | php | public function shouldMoveToRoot()
{
$config = $this->getConfig();
if (isset($config['move_to_root']) && $config['move_to_root'] === true) {
return true;
}
return $this->getDocumentRoot() === 'public' && !is_dir($this->getRoot() . '/public');
} | [
"public",
"function",
"shouldMoveToRoot",
"(",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"config",
"[",
"'move_to_root'",
"]",
")",
"&&",
"$",
"config",
"[",
"'move_to_root'",
"]",
"===",... | Check whether the whole app should be moved into the document root.
@return string | [
"Check",
"whether",
"the",
"whole",
"app",
"should",
"be",
"moved",
"into",
"the",
"document",
"root",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalApplication.php#L288-L297 |
platformsh/platformsh-cli | src/Command/Domain/DomainDeleteCommand.php | DomainDeleteCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$name = $input->getArgument('name');
$project = $this->getSelectedProject();
$domain = $project->getDomain($name);
if (!$domain) {
$this->stdErr->writeln("Domain not found: <error>$name</error>");
return 1;
}
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
if (!$questionHelper->confirm("Are you sure you want to delete the domain <info>$name</info>?")) {
return 1;
}
$result = $domain->delete();
$this->stdErr->writeln("The domain <info>$name</info> has been deleted.");
if ($this->shouldWait($input)) {
/** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */
$activityMonitor = $this->getService('activity_monitor');
$activityMonitor->waitMultiple($result->getActivities(), $project);
}
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$name = $input->getArgument('name');
$project = $this->getSelectedProject();
$domain = $project->getDomain($name);
if (!$domain) {
$this->stdErr->writeln("Domain not found: <error>$name</error>");
return 1;
}
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
if (!$questionHelper->confirm("Are you sure you want to delete the domain <info>$name</info>?")) {
return 1;
}
$result = $domain->delete();
$this->stdErr->writeln("The domain <info>$name</info> has been deleted.");
if ($this->shouldWait($input)) {
/** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */
$activityMonitor = $this->getService('activity_monitor');
$activityMonitor->waitMultiple($result->getActivities(), $project);
}
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"validateInput",
"(",
"$",
"input",
")",
";",
"$",
"name",
"=",
"$",
"input",
"->",
"getArgument",
"(",
"'name'",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Domain/DomainDeleteCommand.php#L27-L58 |
platformsh/platformsh-cli | src/Command/Self/SelfReleaseCommand.php | SelfReleaseCommand.getReleaseChangelog | private function getReleaseChangelog($lastVersionTag)
{
$filename = CLI_ROOT . '/release-changelog.md';
if (file_exists($filename)) {
$mTime = filemtime($filename);
$lastVersionDate = $this->getTagDate($lastVersionTag);
if (!$lastVersionDate || !$mTime || $mTime > $lastVersionDate) {
$contents = file_get_contents($filename);
if ($contents === false) {
throw new \RuntimeException('Failed to read file: ' . $filename);
}
$changelog = trim($contents);
}
}
if (empty($changelog)) {
$changelog = $this->getGitChangelog($lastVersionTag);
(new Filesystem())->dumpFile($filename, $changelog);
}
return $changelog;
} | php | private function getReleaseChangelog($lastVersionTag)
{
$filename = CLI_ROOT . '/release-changelog.md';
if (file_exists($filename)) {
$mTime = filemtime($filename);
$lastVersionDate = $this->getTagDate($lastVersionTag);
if (!$lastVersionDate || !$mTime || $mTime > $lastVersionDate) {
$contents = file_get_contents($filename);
if ($contents === false) {
throw new \RuntimeException('Failed to read file: ' . $filename);
}
$changelog = trim($contents);
}
}
if (empty($changelog)) {
$changelog = $this->getGitChangelog($lastVersionTag);
(new Filesystem())->dumpFile($filename, $changelog);
}
return $changelog;
} | [
"private",
"function",
"getReleaseChangelog",
"(",
"$",
"lastVersionTag",
")",
"{",
"$",
"filename",
"=",
"CLI_ROOT",
".",
"'/release-changelog.md'",
";",
"if",
"(",
"file_exists",
"(",
"$",
"filename",
")",
")",
"{",
"$",
"mTime",
"=",
"filemtime",
"(",
"$"... | @param string $lastVersionTag The tag corresponding to the last version.
@return string | [
"@param",
"string",
"$lastVersionTag",
"The",
"tag",
"corresponding",
"to",
"the",
"last",
"version",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Self/SelfReleaseCommand.php#L389-L409 |
platformsh/platformsh-cli | src/Command/Self/SelfReleaseCommand.php | SelfReleaseCommand.getTagDate | private function getTagDate($tagName)
{
/** @var \Platformsh\Cli\Service\Git $git */
$git = $this->getService('git');
$date = $git->execute(['log', '-1', '--format=%aI', 'refs/tags/' . $tagName]);
return is_string($date) ? strtotime(trim($date)) : false;
} | php | private function getTagDate($tagName)
{
/** @var \Platformsh\Cli\Service\Git $git */
$git = $this->getService('git');
$date = $git->execute(['log', '-1', '--format=%aI', 'refs/tags/' . $tagName]);
return is_string($date) ? strtotime(trim($date)) : false;
} | [
"private",
"function",
"getTagDate",
"(",
"$",
"tagName",
")",
"{",
"/** @var \\Platformsh\\Cli\\Service\\Git $git */",
"$",
"git",
"=",
"$",
"this",
"->",
"getService",
"(",
"'git'",
")",
";",
"$",
"date",
"=",
"$",
"git",
"->",
"execute",
"(",
"[",
"'log'"... | Returns the commit date associated with a tag.
@param string $tagName
@return int|false | [
"Returns",
"the",
"commit",
"date",
"associated",
"with",
"a",
"tag",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Self/SelfReleaseCommand.php#L418-L425 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.