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/Service/Drush.php | Drush.execute | public function execute(array $args, $dir = null, $mustRun = false, $quiet = true)
{
array_unshift($args, $this->getDrushExecutable());
return $this->shellHelper->execute($args, $dir, $mustRun, $quiet);
} | php | public function execute(array $args, $dir = null, $mustRun = false, $quiet = true)
{
array_unshift($args, $this->getDrushExecutable());
return $this->shellHelper->execute($args, $dir, $mustRun, $quiet);
} | [
"public",
"function",
"execute",
"(",
"array",
"$",
"args",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
",",
"$",
"quiet",
"=",
"true",
")",
"{",
"array_unshift",
"(",
"$",
"args",
",",
"$",
"this",
"->",
"getDrushExecutable",
"(... | Execute a Drush command.
@param string[] $args
Command arguments (everything after 'drush').
@param string $dir
The working directory.
@param bool $mustRun
Enable exceptions if the command fails.
@param bool $quiet
Suppress command output.
@return string|bool | [
"Execute",
"a",
"Drush",
"command",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Drush.php#L175-L180 |
platformsh/platformsh-cli | src/Service/Drush.php | Drush.getDrushExecutable | protected function getDrushExecutable()
{
if (isset($this->executable)) {
return $this->executable;
}
if ($this->config->has('local.drush_executable')) {
return $this->executable = $this->config->get('local.drush_executable');
}
// Find a locally installed Drush instance: first check the Composer
// 'vendor' directory.
$projectRoot = $this->localProject->getProjectRoot();
$localDir = $projectRoot ?: getcwd();
$drushLocal = $localDir . '/vendor/bin/drush';
if (is_executable($drushLocal)) {
return $this->executable = $drushLocal;
}
// Check the local dependencies directory (created via 'platform
// build').
$drushDep = $localDir . '/' . $this->config->get('local.dependencies_dir') . '/php/vendor/bin/drush';
if (is_executable($drushDep)) {
return $this->executable = $drushDep;
}
// Use the global Drush, if there is one installed.
if ($this->shellHelper->commandExists('drush')) {
return $this->executable = $this->shellHelper->resolveCommand('drush');
}
// Fall back to the Drush that may be installed within the CLI.
$drushCli = CLI_ROOT . '/vendor/bin/drush';
if (is_executable($drushCli)) {
return $this->executable = $drushCli;
}
return $this->executable = 'drush';
} | php | protected function getDrushExecutable()
{
if (isset($this->executable)) {
return $this->executable;
}
if ($this->config->has('local.drush_executable')) {
return $this->executable = $this->config->get('local.drush_executable');
}
// Find a locally installed Drush instance: first check the Composer
// 'vendor' directory.
$projectRoot = $this->localProject->getProjectRoot();
$localDir = $projectRoot ?: getcwd();
$drushLocal = $localDir . '/vendor/bin/drush';
if (is_executable($drushLocal)) {
return $this->executable = $drushLocal;
}
// Check the local dependencies directory (created via 'platform
// build').
$drushDep = $localDir . '/' . $this->config->get('local.dependencies_dir') . '/php/vendor/bin/drush';
if (is_executable($drushDep)) {
return $this->executable = $drushDep;
}
// Use the global Drush, if there is one installed.
if ($this->shellHelper->commandExists('drush')) {
return $this->executable = $this->shellHelper->resolveCommand('drush');
}
// Fall back to the Drush that may be installed within the CLI.
$drushCli = CLI_ROOT . '/vendor/bin/drush';
if (is_executable($drushCli)) {
return $this->executable = $drushCli;
}
return $this->executable = 'drush';
} | [
"protected",
"function",
"getDrushExecutable",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"executable",
")",
")",
"{",
"return",
"$",
"this",
"->",
"executable",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"config",
"->",
"has",
"(",
"'lo... | Get the full path to the Drush executable.
@return string
The absolute path to the executable, or 'drush' if the path is not
known. | [
"Get",
"the",
"full",
"path",
"to",
"the",
"Drush",
"executable",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Drush.php#L189-L227 |
platformsh/platformsh-cli | src/Service/Drush.php | Drush.getAliases | public function getAliases($groupName, $reset = false)
{
if (!$reset && isset($this->aliases[$groupName])) {
return $this->aliases[$groupName];
}
// Drush 9 uses 'site:alias', Drush <9 uses 'site-alias'. Fortunately
// the alias 'sa' exists in both.
$args = [$this->getDrushExecutable(), '@none', 'sa', '--format=json', '@' . $groupName];
$aliases = [];
// Run the command with a 5-second timeout. An exception will be thrown
// if it fails.
try {
$result = $this->shellHelper->execute($args, null, true, true, [], 5);
if (is_string($result)) {
$aliases = (array) json_decode($result, true);
}
} catch (ProcessFailedException $e) {
// The command will fail if the alias is not found. Throw an
// exception for any other failures.
if (stripos($e->getProcess()->getErrorOutput(), 'not found') === false) {
throw $e;
}
}
$this->aliases[$groupName] = $aliases;
return $aliases;
} | php | public function getAliases($groupName, $reset = false)
{
if (!$reset && isset($this->aliases[$groupName])) {
return $this->aliases[$groupName];
}
// Drush 9 uses 'site:alias', Drush <9 uses 'site-alias'. Fortunately
// the alias 'sa' exists in both.
$args = [$this->getDrushExecutable(), '@none', 'sa', '--format=json', '@' . $groupName];
$aliases = [];
// Run the command with a 5-second timeout. An exception will be thrown
// if it fails.
try {
$result = $this->shellHelper->execute($args, null, true, true, [], 5);
if (is_string($result)) {
$aliases = (array) json_decode($result, true);
}
} catch (ProcessFailedException $e) {
// The command will fail if the alias is not found. Throw an
// exception for any other failures.
if (stripos($e->getProcess()->getErrorOutput(), 'not found') === false) {
throw $e;
}
}
$this->aliases[$groupName] = $aliases;
return $aliases;
} | [
"public",
"function",
"getAliases",
"(",
"$",
"groupName",
",",
"$",
"reset",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"reset",
"&&",
"isset",
"(",
"$",
"this",
"->",
"aliases",
"[",
"$",
"groupName",
"]",
")",
")",
"{",
"return",
"$",
"this",
... | Get existing Drush aliases for a group.
@param string $groupName
@param bool $reset
@throws \Exception If the "drush sa" command fails.
@return array | [
"Get",
"existing",
"Drush",
"aliases",
"for",
"a",
"group",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Drush.php#L247-L277 |
platformsh/platformsh-cli | src/Service/Drush.php | Drush.getAliasGroup | public function getAliasGroup(Project $project, $projectRoot)
{
$config = $this->localProject->getProjectConfig($projectRoot);
return !empty($config['alias-group']) ? $config['alias-group'] : $project['id'];
} | php | public function getAliasGroup(Project $project, $projectRoot)
{
$config = $this->localProject->getProjectConfig($projectRoot);
return !empty($config['alias-group']) ? $config['alias-group'] : $project['id'];
} | [
"public",
"function",
"getAliasGroup",
"(",
"Project",
"$",
"project",
",",
"$",
"projectRoot",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"localProject",
"->",
"getProjectConfig",
"(",
"$",
"projectRoot",
")",
";",
"return",
"!",
"empty",
"(",
"$",
... | Get the alias group for a project.
@param Project $project
@param string $projectRoot
@return string | [
"Get",
"the",
"alias",
"group",
"for",
"a",
"project",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Drush.php#L287-L292 |
platformsh/platformsh-cli | src/Service/Drush.php | Drush.createAliases | public function createAliases(Project $project, $projectRoot, $environments, $original = null)
{
if (!$apps = $this->getDrupalApps($projectRoot)) {
return false;
}
$group = $this->getAliasGroup($project, $projectRoot);
$success = true;
foreach ($this->getSiteAliasTypes() as $type) {
$success = $success && $type->createAliases($project, $group, $apps, $environments, $original);
}
return $success;
} | php | public function createAliases(Project $project, $projectRoot, $environments, $original = null)
{
if (!$apps = $this->getDrupalApps($projectRoot)) {
return false;
}
$group = $this->getAliasGroup($project, $projectRoot);
$success = true;
foreach ($this->getSiteAliasTypes() as $type) {
$success = $success && $type->createAliases($project, $group, $apps, $environments, $original);
}
return $success;
} | [
"public",
"function",
"createAliases",
"(",
"Project",
"$",
"project",
",",
"$",
"projectRoot",
",",
"$",
"environments",
",",
"$",
"original",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"apps",
"=",
"$",
"this",
"->",
"getDrupalApps",
"(",
"$",
"proj... | Create Drush aliases for the provided project and environments.
@param Project $project The project
@param string $projectRoot The project root
@param Environment[] $environments The environments
@param string $original The original group name
@return bool True on success, false on failure. | [
"Create",
"Drush",
"aliases",
"for",
"the",
"provided",
"project",
"and",
"environments",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Drush.php#L313-L327 |
platformsh/platformsh-cli | src/Service/Drush.php | Drush.getDrupalApps | public function getDrupalApps($projectRoot)
{
return array_filter(
LocalApplication::getApplications($projectRoot, $this->config),
function (LocalApplication $app) {
return Drupal::isDrupal($app->getRoot());
}
);
} | php | public function getDrupalApps($projectRoot)
{
return array_filter(
LocalApplication::getApplications($projectRoot, $this->config),
function (LocalApplication $app) {
return Drupal::isDrupal($app->getRoot());
}
);
} | [
"public",
"function",
"getDrupalApps",
"(",
"$",
"projectRoot",
")",
"{",
"return",
"array_filter",
"(",
"LocalApplication",
"::",
"getApplications",
"(",
"$",
"projectRoot",
",",
"$",
"this",
"->",
"config",
")",
",",
"function",
"(",
"LocalApplication",
"$",
... | Find Drupal applications in a project.
@param string $projectRoot
@return LocalApplication[] | [
"Find",
"Drupal",
"applications",
"in",
"a",
"project",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Drush.php#L336-L344 |
platformsh/platformsh-cli | src/Command/Variable/VariableDeleteCommand.php | VariableDeleteCommand.configure | protected function configure()
{
$this
->setName('variable:delete')
->addArgument('name', InputArgument::REQUIRED, 'The variable name')
->setDescription('Delete a variable');
$this->addLevelOption();
$this->addProjectOption()
->addEnvironmentOption()
->addWaitOptions();
$this->addExample('Delete the variable "example"', 'example');
} | php | protected function configure()
{
$this
->setName('variable:delete')
->addArgument('name', InputArgument::REQUIRED, 'The variable name')
->setDescription('Delete a variable');
$this->addLevelOption();
$this->addProjectOption()
->addEnvironmentOption()
->addWaitOptions();
$this->addExample('Delete the variable "example"', 'example');
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'variable:delete'",
")",
"->",
"addArgument",
"(",
"'name'",
",",
"InputArgument",
"::",
"REQUIRED",
",",
"'The variable name'",
")",
"->",
"setDescription",
"(",
"'Delete a... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Variable/VariableDeleteCommand.php#L14-L25 |
platformsh/platformsh-cli | src/Command/Certificate/CertificateListCommand.php | CertificateListCommand.getCertificateIssuerByAlias | protected function getCertificateIssuerByAlias(Certificate $cert, $alias) {
foreach ($cert->issuer as $issuer) {
if (isset($issuer['alias'], $issuer['value']) && $issuer['alias'] === $alias) {
return $issuer['value'];
}
}
return false;
} | php | protected function getCertificateIssuerByAlias(Certificate $cert, $alias) {
foreach ($cert->issuer as $issuer) {
if (isset($issuer['alias'], $issuer['value']) && $issuer['alias'] === $alias) {
return $issuer['value'];
}
}
return false;
} | [
"protected",
"function",
"getCertificateIssuerByAlias",
"(",
"Certificate",
"$",
"cert",
",",
"$",
"alias",
")",
"{",
"foreach",
"(",
"$",
"cert",
"->",
"issuer",
"as",
"$",
"issuer",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"issuer",
"[",
"'alias'",
"]",... | @param \Platformsh\Client\Model\Certificate $cert
@param string $alias
@return string|bool | [
"@param",
"\\",
"Platformsh",
"\\",
"Client",
"\\",
"Model",
"\\",
"Certificate",
"$cert",
"@param",
"string",
"$alias"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Certificate/CertificateListCommand.php#L188-L196 |
platformsh/platformsh-cli | src/Command/Service/ServiceListCommand.php | ServiceListCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
// Find a list of deployed services.
$deployment = $this->api()
->getCurrentDeployment($this->getSelectedEnvironment(), $input->getOption('refresh'));
$services = $deployment->services;
if (!count($services)) {
$this->stdErr->writeln('No services found.');
if ($deployment->webapps) {
$this->stdErr->writeln('');
$this->stdErr->writeln(sprintf(
'To list applications, run: <info>%s apps</info>',
$this->config()->get('application.executable')
));
}
return 0;
}
$headers = ['Name', 'Type', 'disk' => 'Disk (MiB)', 'Size'];
$rows = [];
foreach ($services as $name => $service) {
$row = [
$name,
$service->type,
'disk' => $service->disk !== null ? $service->disk : '',
$service->size,
];
$rows[] = $row;
}
/** @var \Platformsh\Cli\Service\Table $table */
$table = $this->getService('table');
if (!$table->formatIsMachineReadable()) {
$this->stdErr->writeln(sprintf(
'Services on the project <info>%s</info>, environment <info>%s</info>:',
$this->api()->getProjectLabel($this->getSelectedProject()),
$this->api()->getEnvironmentLabel($this->getSelectedEnvironment())
));
}
$table->render($rows, $headers);
if (!$table->formatIsMachineReadable() && $deployment->webapps) {
$this->stdErr->writeln('');
$this->stdErr->writeln(sprintf(
'To list applications, run: <info>%s apps</info>',
$this->config()->get('application.executable')
));
}
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
// Find a list of deployed services.
$deployment = $this->api()
->getCurrentDeployment($this->getSelectedEnvironment(), $input->getOption('refresh'));
$services = $deployment->services;
if (!count($services)) {
$this->stdErr->writeln('No services found.');
if ($deployment->webapps) {
$this->stdErr->writeln('');
$this->stdErr->writeln(sprintf(
'To list applications, run: <info>%s apps</info>',
$this->config()->get('application.executable')
));
}
return 0;
}
$headers = ['Name', 'Type', 'disk' => 'Disk (MiB)', 'Size'];
$rows = [];
foreach ($services as $name => $service) {
$row = [
$name,
$service->type,
'disk' => $service->disk !== null ? $service->disk : '',
$service->size,
];
$rows[] = $row;
}
/** @var \Platformsh\Cli\Service\Table $table */
$table = $this->getService('table');
if (!$table->formatIsMachineReadable()) {
$this->stdErr->writeln(sprintf(
'Services on the project <info>%s</info>, environment <info>%s</info>:',
$this->api()->getProjectLabel($this->getSelectedProject()),
$this->api()->getEnvironmentLabel($this->getSelectedEnvironment())
));
}
$table->render($rows, $headers);
if (!$table->formatIsMachineReadable() && $deployment->webapps) {
$this->stdErr->writeln('');
$this->stdErr->writeln(sprintf(
'To list applications, run: <info>%s apps</info>',
$this->config()->get('application.executable')
));
}
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"validateInput",
"(",
"$",
"input",
")",
";",
"// Find a list of deployed services.",
"$",
"deployment",
"=",
"$",
"this"... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Service/ServiceListCommand.php#L29-L86 |
platformsh/platformsh-cli | src/Command/Project/ProjectListCommand.php | ProjectListCommand.filterProjects | protected function filterProjects(array &$projects, array $filters)
{
foreach ($filters as $filter => $value) {
switch ($filter) {
case 'host':
$projects = array_filter($projects, function (Project $project) use ($value) {
return $value === parse_url($project->getUri(), PHP_URL_HOST);
});
break;
case 'title':
$projects = array_filter($projects, function (Project $project) use ($value) {
return stripos($project->title, $value) !== false;
});
break;
case 'my':
$ownerId = $this->api()->getMyAccount()['id'];
$projects = array_filter($projects, function (Project $project) use ($ownerId) {
return $project->owner === $ownerId;
});
break;
}
}
} | php | protected function filterProjects(array &$projects, array $filters)
{
foreach ($filters as $filter => $value) {
switch ($filter) {
case 'host':
$projects = array_filter($projects, function (Project $project) use ($value) {
return $value === parse_url($project->getUri(), PHP_URL_HOST);
});
break;
case 'title':
$projects = array_filter($projects, function (Project $project) use ($value) {
return stripos($project->title, $value) !== false;
});
break;
case 'my':
$ownerId = $this->api()->getMyAccount()['id'];
$projects = array_filter($projects, function (Project $project) use ($ownerId) {
return $project->owner === $ownerId;
});
break;
}
}
} | [
"protected",
"function",
"filterProjects",
"(",
"array",
"&",
"$",
"projects",
",",
"array",
"$",
"filters",
")",
"{",
"foreach",
"(",
"$",
"filters",
"as",
"$",
"filter",
"=>",
"$",
"value",
")",
"{",
"switch",
"(",
"$",
"filter",
")",
"{",
"case",
... | Filter the list of projects.
@param Project[] &$projects
@param mixed[string] $filters | [
"Filter",
"the",
"list",
"of",
"projects",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Project/ProjectListCommand.php#L140-L164 |
platformsh/platformsh-cli | src/Util/Csv.php | Csv.format | public function format(array $data, $appendLineBreak = true)
{
return implode($this->lineBreak, array_map([$this, 'formatRow'], $data))
. ($appendLineBreak ? $this->lineBreak : '');
} | php | public function format(array $data, $appendLineBreak = true)
{
return implode($this->lineBreak, array_map([$this, 'formatRow'], $data))
. ($appendLineBreak ? $this->lineBreak : '');
} | [
"public",
"function",
"format",
"(",
"array",
"$",
"data",
",",
"$",
"appendLineBreak",
"=",
"true",
")",
"{",
"return",
"implode",
"(",
"$",
"this",
"->",
"lineBreak",
",",
"array_map",
"(",
"[",
"$",
"this",
",",
"'formatRow'",
"]",
",",
"$",
"data",... | Format an array of rows as a CSV spreadsheet.
@param array $data
An array of rows. Each row is an array of cells (hopefully the same
number in each row). Each cell must be a string, or a type that can
be cast to a string.
@param bool $appendLineBreak
Whether to add a line break at the end of the final row.
@return string | [
"Format",
"an",
"array",
"of",
"rows",
"as",
"a",
"CSV",
"spreadsheet",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/Csv.php#L40-L44 |
platformsh/platformsh-cli | src/Util/Csv.php | Csv.formatCell | private function formatCell($cell)
{
// Cast cell data to a string.
$cell = (string) $cell;
// Enclose the cell in double quotes, if necessary.
if (strpbrk($cell, '"' . $this->lineBreak . $this->delimiter) !== false) {
$cell = '"' . str_replace('"', '""', $cell) . '"';
}
// Standardize line breaks.
$cell = preg_replace('/\R/u', $this->lineBreak, $cell);
return $cell;
} | php | private function formatCell($cell)
{
// Cast cell data to a string.
$cell = (string) $cell;
// Enclose the cell in double quotes, if necessary.
if (strpbrk($cell, '"' . $this->lineBreak . $this->delimiter) !== false) {
$cell = '"' . str_replace('"', '""', $cell) . '"';
}
// Standardize line breaks.
$cell = preg_replace('/\R/u', $this->lineBreak, $cell);
return $cell;
} | [
"private",
"function",
"formatCell",
"(",
"$",
"cell",
")",
"{",
"// Cast cell data to a string.",
"$",
"cell",
"=",
"(",
"string",
")",
"$",
"cell",
";",
"// Enclose the cell in double quotes, if necessary.",
"if",
"(",
"strpbrk",
"(",
"$",
"cell",
",",
"'\"'",
... | Format a CSV cell.
@param string|object $cell
@return string | [
"Format",
"a",
"CSV",
"cell",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/Csv.php#L65-L79 |
platformsh/platformsh-cli | src/SiteAlias/DrushPhp.php | DrushPhp.formatAliases | protected function formatAliases(array $aliases)
{
$formatted = [];
foreach ($aliases as $aliasName => $newAlias) {
$formatted[] = sprintf(
"\$aliases['%s'] = %s;\n",
str_replace("'", "\\'", $aliasName),
var_export($newAlias, true)
);
}
return implode("\n", $formatted);
} | php | protected function formatAliases(array $aliases)
{
$formatted = [];
foreach ($aliases as $aliasName => $newAlias) {
$formatted[] = sprintf(
"\$aliases['%s'] = %s;\n",
str_replace("'", "\\'", $aliasName),
var_export($newAlias, true)
);
}
return implode("\n", $formatted);
} | [
"protected",
"function",
"formatAliases",
"(",
"array",
"$",
"aliases",
")",
"{",
"$",
"formatted",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"aliases",
"as",
"$",
"aliasName",
"=>",
"$",
"newAlias",
")",
"{",
"$",
"formatted",
"[",
"]",
"=",
"sprintf",... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SiteAlias/DrushPhp.php#L20-L32 |
platformsh/platformsh-cli | src/Command/Activity/ActivityGetCommand.php | ActivityGetCommand.configure | protected function configure()
{
$this
->setName('activity:get')
->addArgument('id', InputArgument::OPTIONAL, 'The activity ID. Defaults to the most recent activity.')
->addOption('type', null, InputOption::VALUE_REQUIRED, 'Filter recent activities by type')
->addOption('all', 'a', InputOption::VALUE_NONE, 'Check recent activities on all environments')
->addOption('property', 'P', InputOption::VALUE_REQUIRED, 'The property to view')
->setDescription('View detailed information on a single activity');
$this->addProjectOption()
->addEnvironmentOption();
Table::configureInput($this->getDefinition());
PropertyFormatter::configureInput($this->getDefinition());
$this->addExample('Find the time a project was created', '--all --type project.create -P completed_at');
$this->addExample('Find the duration (in seconds) of the last activity', '-P duration');
} | php | protected function configure()
{
$this
->setName('activity:get')
->addArgument('id', InputArgument::OPTIONAL, 'The activity ID. Defaults to the most recent activity.')
->addOption('type', null, InputOption::VALUE_REQUIRED, 'Filter recent activities by type')
->addOption('all', 'a', InputOption::VALUE_NONE, 'Check recent activities on all environments')
->addOption('property', 'P', InputOption::VALUE_REQUIRED, 'The property to view')
->setDescription('View detailed information on a single activity');
$this->addProjectOption()
->addEnvironmentOption();
Table::configureInput($this->getDefinition());
PropertyFormatter::configureInput($this->getDefinition());
$this->addExample('Find the time a project was created', '--all --type project.create -P completed_at');
$this->addExample('Find the duration (in seconds) of the last activity', '-P duration');
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'activity:get'",
")",
"->",
"addArgument",
"(",
"'id'",
",",
"InputArgument",
"::",
"OPTIONAL",
",",
"'The activity ID. Defaults to the most recent activity.'",
")",
"->",
"addO... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Activity/ActivityGetCommand.php#L19-L34 |
platformsh/platformsh-cli | src/Command/Activity/ActivityGetCommand.php | ActivityGetCommand.getActivities | private function getActivities(InputInterface $input, $limit = 0)
{
if ($this->hasSelectedEnvironment() && !$input->getOption('all')) {
return $this->getSelectedEnvironment()
->getActivities($limit, $input->getOption('type'));
}
return $this->getSelectedProject()
->getActivities($limit, $input->getOption('type'));
} | php | private function getActivities(InputInterface $input, $limit = 0)
{
if ($this->hasSelectedEnvironment() && !$input->getOption('all')) {
return $this->getSelectedEnvironment()
->getActivities($limit, $input->getOption('type'));
}
return $this->getSelectedProject()
->getActivities($limit, $input->getOption('type'));
} | [
"private",
"function",
"getActivities",
"(",
"InputInterface",
"$",
"input",
",",
"$",
"limit",
"=",
"0",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasSelectedEnvironment",
"(",
")",
"&&",
"!",
"$",
"input",
"->",
"getOption",
"(",
"'all'",
")",
")",
"{... | Get activities on the project or environment.
@param \Symfony\Component\Console\Input\InputInterface $input
@param int $limit
@return \Platformsh\Client\Model\Activity[] | [
"Get",
"activities",
"on",
"the",
"project",
"or",
"environment",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Activity/ActivityGetCommand.php#L131-L140 |
platformsh/platformsh-cli | src/Command/Activity/ActivityGetCommand.php | ActivityGetCommand.getDuration | private function getDuration(Activity $activity, $now = null)
{
if ($activity->isComplete()) {
$end = strtotime($activity->completed_at);
} elseif (!empty($activity->started_at)) {
$now = $now === null ? time() : $now;
$end = $now;
} else {
$end = strtotime($activity->updated_at);
}
$start = !empty($activity->started_at) ? strtotime($activity->started_at) : strtotime($activity->created_at);
return $end !== false && $start !== false && $end - $start > 0 ? $end - $start : null;
} | php | private function getDuration(Activity $activity, $now = null)
{
if ($activity->isComplete()) {
$end = strtotime($activity->completed_at);
} elseif (!empty($activity->started_at)) {
$now = $now === null ? time() : $now;
$end = $now;
} else {
$end = strtotime($activity->updated_at);
}
$start = !empty($activity->started_at) ? strtotime($activity->started_at) : strtotime($activity->created_at);
return $end !== false && $start !== false && $end - $start > 0 ? $end - $start : null;
} | [
"private",
"function",
"getDuration",
"(",
"Activity",
"$",
"activity",
",",
"$",
"now",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"activity",
"->",
"isComplete",
"(",
")",
")",
"{",
"$",
"end",
"=",
"strtotime",
"(",
"$",
"activity",
"->",
"completed_at"... | Calculates the duration of an activity, whether complete or not.
@param \Platformsh\Client\Model\Activity $activity
@param int|null $now
@return int|null | [
"Calculates",
"the",
"duration",
"of",
"an",
"activity",
"whether",
"complete",
"or",
"not",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Activity/ActivityGetCommand.php#L150-L163 |
platformsh/platformsh-cli | src/Command/Server/ServerCommandBase.php | ServerCommandBase.isServerRunningForApp | protected function isServerRunningForApp($appId, $projectRoot)
{
foreach ($this->getServerInfo() as $address => $server) {
if ($server['appId'] === $appId && $server['projectRoot'] === $projectRoot) {
if ($this->isProcessDead($server['pid'])) {
$this->stopServer($address);
continue;
}
return $server;
}
}
return false;
} | php | protected function isServerRunningForApp($appId, $projectRoot)
{
foreach ($this->getServerInfo() as $address => $server) {
if ($server['appId'] === $appId && $server['projectRoot'] === $projectRoot) {
if ($this->isProcessDead($server['pid'])) {
$this->stopServer($address);
continue;
}
return $server;
}
}
return false;
} | [
"protected",
"function",
"isServerRunningForApp",
"(",
"$",
"appId",
",",
"$",
"projectRoot",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getServerInfo",
"(",
")",
"as",
"$",
"address",
"=>",
"$",
"server",
")",
"{",
"if",
"(",
"$",
"server",
"[",
"'... | Check whether another server is running for an app.
@param string $appId
@param string $projectRoot
@return bool|array | [
"Check",
"whether",
"another",
"server",
"is",
"running",
"for",
"an",
"app",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Server/ServerCommandBase.php#L30-L43 |
platformsh/platformsh-cli | src/Command/Server/ServerCommandBase.php | ServerCommandBase.isServerRunningForAddress | protected function isServerRunningForAddress($address)
{
$pidFile = $this->getPidFile($address);
$serverInfo = $this->getServerInfo();
if (file_exists($pidFile)) {
$pid = file_get_contents($pidFile);
} elseif (isset($serverInfo[$address])) {
$pid = $serverInfo[$address]['pid'];
}
if (!empty($pid) && !$this->isProcessDead($pid)) {
return $pid;
} elseif (!empty($pid)) {
// The PID is no longer valid. Delete the lock file and
// continue.
$this->stopServer($address);
}
list($hostname, $port) = explode(':', $address);
return PortUtil::isPortInUse($port, $hostname);
} | php | protected function isServerRunningForAddress($address)
{
$pidFile = $this->getPidFile($address);
$serverInfo = $this->getServerInfo();
if (file_exists($pidFile)) {
$pid = file_get_contents($pidFile);
} elseif (isset($serverInfo[$address])) {
$pid = $serverInfo[$address]['pid'];
}
if (!empty($pid) && !$this->isProcessDead($pid)) {
return $pid;
} elseif (!empty($pid)) {
// The PID is no longer valid. Delete the lock file and
// continue.
$this->stopServer($address);
}
list($hostname, $port) = explode(':', $address);
return PortUtil::isPortInUse($port, $hostname);
} | [
"protected",
"function",
"isServerRunningForAddress",
"(",
"$",
"address",
")",
"{",
"$",
"pidFile",
"=",
"$",
"this",
"->",
"getPidFile",
"(",
"$",
"address",
")",
";",
"$",
"serverInfo",
"=",
"$",
"this",
"->",
"getServerInfo",
"(",
")",
";",
"if",
"("... | Check whether another server is running at an address.
@param string $address
@return bool|int | [
"Check",
"whether",
"another",
"server",
"is",
"running",
"at",
"an",
"address",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Server/ServerCommandBase.php#L65-L86 |
platformsh/platformsh-cli | src/Command/Server/ServerCommandBase.php | ServerCommandBase.getServerInfo | protected function getServerInfo($running = true)
{
if (!isset($this->serverInfo)) {
$this->serverInfo = [];
// @todo move this to State service (in a new major version)
$filename = $this->config()->getWritableUserDir() . '/local-servers.json';
if (file_exists($filename)) {
$this->serverInfo = (array) json_decode(file_get_contents($filename), true);
}
}
if ($running) {
return array_filter($this->serverInfo, function ($server) {
if ($this->isProcessDead($server['pid'])) {
$this->stopServer($server['address']);
return false;
}
return true;
});
}
return $this->serverInfo;
} | php | protected function getServerInfo($running = true)
{
if (!isset($this->serverInfo)) {
$this->serverInfo = [];
// @todo move this to State service (in a new major version)
$filename = $this->config()->getWritableUserDir() . '/local-servers.json';
if (file_exists($filename)) {
$this->serverInfo = (array) json_decode(file_get_contents($filename), true);
}
}
if ($running) {
return array_filter($this->serverInfo, function ($server) {
if ($this->isProcessDead($server['pid'])) {
$this->stopServer($server['address']);
return false;
}
return true;
});
}
return $this->serverInfo;
} | [
"protected",
"function",
"getServerInfo",
"(",
"$",
"running",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"serverInfo",
")",
")",
"{",
"$",
"this",
"->",
"serverInfo",
"=",
"[",
"]",
";",
"// @todo move this to State service (i... | Get info on currently running servers.
@param bool $running
@return array | [
"Get",
"info",
"on",
"currently",
"running",
"servers",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Server/ServerCommandBase.php#L95-L118 |
platformsh/platformsh-cli | src/Command/Server/ServerCommandBase.php | ServerCommandBase.stopServer | protected function stopServer($address, $pid = null)
{
$success = true;
if ($pid && function_exists('posix_kill')) {
/** @noinspection PhpComposerExtensionStubsInspection */
$success = posix_kill($pid, SIGTERM);
if (!$success) {
/** @noinspection PhpComposerExtensionStubsInspection */
$this->stdErr->writeln(sprintf(
'Failed to kill process <error>%d</error> (POSIX error %s)',
$pid,
posix_get_last_error()
));
}
}
$pidFile = $this->getPidFile($address);
if (file_exists($pidFile)) {
$success = unlink($pidFile) && $success;
}
unset($this->serverInfo[$address]);
$this->saveServerInfo();
return $success;
} | php | protected function stopServer($address, $pid = null)
{
$success = true;
if ($pid && function_exists('posix_kill')) {
/** @noinspection PhpComposerExtensionStubsInspection */
$success = posix_kill($pid, SIGTERM);
if (!$success) {
/** @noinspection PhpComposerExtensionStubsInspection */
$this->stdErr->writeln(sprintf(
'Failed to kill process <error>%d</error> (POSIX error %s)',
$pid,
posix_get_last_error()
));
}
}
$pidFile = $this->getPidFile($address);
if (file_exists($pidFile)) {
$success = unlink($pidFile) && $success;
}
unset($this->serverInfo[$address]);
$this->saveServerInfo();
return $success;
} | [
"protected",
"function",
"stopServer",
"(",
"$",
"address",
",",
"$",
"pid",
"=",
"null",
")",
"{",
"$",
"success",
"=",
"true",
";",
"if",
"(",
"$",
"pid",
"&&",
"function_exists",
"(",
"'posix_kill'",
")",
")",
"{",
"/** @noinspection PhpComposerExtensionS... | Stop a running server.
@param string $address
@param int|null $pid
@return bool
True on success, false on failure. | [
"Stop",
"a",
"running",
"server",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Server/ServerCommandBase.php#L141-L164 |
platformsh/platformsh-cli | src/Command/Server/ServerCommandBase.php | ServerCommandBase.getPort | protected function getPort($default = 3000)
{
$ports = [];
foreach ($this->getServerInfo() as $address => $server) {
$ports[] = $server['port'];
}
return PortUtil::getPort($ports ? max($ports) + 1 : $default);
} | php | protected function getPort($default = 3000)
{
$ports = [];
foreach ($this->getServerInfo() as $address => $server) {
$ports[] = $server['port'];
}
return PortUtil::getPort($ports ? max($ports) + 1 : $default);
} | [
"protected",
"function",
"getPort",
"(",
"$",
"default",
"=",
"3000",
")",
"{",
"$",
"ports",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getServerInfo",
"(",
")",
"as",
"$",
"address",
"=>",
"$",
"server",
")",
"{",
"$",
"ports",
"[",
... | Automatically determine the best port for a new server.
@param int $default
@return int | [
"Automatically",
"determine",
"the",
"best",
"port",
"for",
"a",
"new",
"server",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Server/ServerCommandBase.php#L191-L199 |
platformsh/platformsh-cli | src/Command/Server/ServerCommandBase.php | ServerCommandBase.createServerProcess | protected function createServerProcess($address, $docRoot, $projectRoot, array $appConfig, array $env = [])
{
if (isset($appConfig['type'])) {
$type = explode(':', $appConfig['type'], 2);
$version = isset($type[1]) ? $type[1] : false;
if ($type[0] === 'php' && $version && version_compare(PHP_VERSION, $version, '<')) {
$this->stdErr->writeln(sprintf(
'<comment>Warning:</comment> your local PHP version is %s, but the app expects %s',
PHP_VERSION,
$version
));
}
}
$arguments = [];
if (isset($appConfig['web']['commands']['start'])) {
// Bail out. We can't support custom 'start' commands for now.
throw new \Exception(
"Not supported: the CLI doesn't support starting a server with a custom 'start' command"
);
}
$router = $this->createRouter($projectRoot);
$this->showSecurityWarning();
$arguments[] = (new PhpExecutableFinder())->find() ?: PHP_BINARY;
foreach ($this->getServerPhpConfig() as $item => $value) {
$arguments[] = sprintf('-d %s="%s"', $item, $value);
}
$arguments = array_merge($arguments, [
'-t',
$docRoot,
'-S',
$address,
$router,
]);
$process = new Process($arguments);
$process->setTimeout(null);
$env += $this->createEnv($projectRoot, $docRoot, $address, $appConfig);
$process->setEnv($env);
$envPrefix = $this->config()->get('service.env_prefix');
if (isset($env[$envPrefix . 'APP_DIR'])) {
$process->setWorkingDirectory($env[$envPrefix . 'APP_DIR']);
}
return $process;
} | php | protected function createServerProcess($address, $docRoot, $projectRoot, array $appConfig, array $env = [])
{
if (isset($appConfig['type'])) {
$type = explode(':', $appConfig['type'], 2);
$version = isset($type[1]) ? $type[1] : false;
if ($type[0] === 'php' && $version && version_compare(PHP_VERSION, $version, '<')) {
$this->stdErr->writeln(sprintf(
'<comment>Warning:</comment> your local PHP version is %s, but the app expects %s',
PHP_VERSION,
$version
));
}
}
$arguments = [];
if (isset($appConfig['web']['commands']['start'])) {
// Bail out. We can't support custom 'start' commands for now.
throw new \Exception(
"Not supported: the CLI doesn't support starting a server with a custom 'start' command"
);
}
$router = $this->createRouter($projectRoot);
$this->showSecurityWarning();
$arguments[] = (new PhpExecutableFinder())->find() ?: PHP_BINARY;
foreach ($this->getServerPhpConfig() as $item => $value) {
$arguments[] = sprintf('-d %s="%s"', $item, $value);
}
$arguments = array_merge($arguments, [
'-t',
$docRoot,
'-S',
$address,
$router,
]);
$process = new Process($arguments);
$process->setTimeout(null);
$env += $this->createEnv($projectRoot, $docRoot, $address, $appConfig);
$process->setEnv($env);
$envPrefix = $this->config()->get('service.env_prefix');
if (isset($env[$envPrefix . 'APP_DIR'])) {
$process->setWorkingDirectory($env[$envPrefix . 'APP_DIR']);
}
return $process;
} | [
"protected",
"function",
"createServerProcess",
"(",
"$",
"address",
",",
"$",
"docRoot",
",",
"$",
"projectRoot",
",",
"array",
"$",
"appConfig",
",",
"array",
"$",
"env",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"appConfig",
"[",
"'type... | Creates a process to start a web server.
@param string $address
@param string $docRoot
@param string $projectRoot
@param array $appConfig
@param array $env
@throws \Exception
@return Process | [
"Creates",
"a",
"process",
"to",
"start",
"a",
"web",
"server",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Server/ServerCommandBase.php#L226-L277 |
platformsh/platformsh-cli | src/Command/Server/ServerCommandBase.php | ServerCommandBase.getServerPhpConfig | protected function getServerPhpConfig()
{
$phpConfig = [];
// Ensure $_ENV is populated.
$variables_order = ini_get('variables_order');
if (strpos($variables_order, 'E') === false) {
$phpConfig['variables_order'] = 'E' . $variables_order;
}
return $phpConfig;
} | php | protected function getServerPhpConfig()
{
$phpConfig = [];
// Ensure $_ENV is populated.
$variables_order = ini_get('variables_order');
if (strpos($variables_order, 'E') === false) {
$phpConfig['variables_order'] = 'E' . $variables_order;
}
return $phpConfig;
} | [
"protected",
"function",
"getServerPhpConfig",
"(",
")",
"{",
"$",
"phpConfig",
"=",
"[",
"]",
";",
"// Ensure $_ENV is populated.",
"$",
"variables_order",
"=",
"ini_get",
"(",
"'variables_order'",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"variables_order",
","... | Get custom PHP configuration for the built-in web server.
@return array | [
"Get",
"custom",
"PHP",
"configuration",
"for",
"the",
"built",
"-",
"in",
"web",
"server",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Server/ServerCommandBase.php#L284-L295 |
platformsh/platformsh-cli | src/Command/Server/ServerCommandBase.php | ServerCommandBase.createRouter | protected function createRouter($projectRoot)
{
static $created = [];
$router_src = CLI_ROOT . '/resources/router/router.php';
if (!file_exists($router_src)) {
throw new \RuntimeException(sprintf('Router not found: <error>%s</error>', $router_src));
}
$router = $projectRoot . '/' . $this->config()->get('local.local_dir') . '/' . basename($router_src);
if (!isset($created[$router])) {
if (!file_put_contents($router, file_get_contents($router_src))) {
throw new \RuntimeException(sprintf('Could not create router file: <error>%s</error>', $router));
}
$created[$router] = true;
}
return $router;
} | php | protected function createRouter($projectRoot)
{
static $created = [];
$router_src = CLI_ROOT . '/resources/router/router.php';
if (!file_exists($router_src)) {
throw new \RuntimeException(sprintf('Router not found: <error>%s</error>', $router_src));
}
$router = $projectRoot . '/' . $this->config()->get('local.local_dir') . '/' . basename($router_src);
if (!isset($created[$router])) {
if (!file_put_contents($router, file_get_contents($router_src))) {
throw new \RuntimeException(sprintf('Could not create router file: <error>%s</error>', $router));
}
$created[$router] = true;
}
return $router;
} | [
"protected",
"function",
"createRouter",
"(",
"$",
"projectRoot",
")",
"{",
"static",
"$",
"created",
"=",
"[",
"]",
";",
"$",
"router_src",
"=",
"CLI_ROOT",
".",
"'/resources/router/router.php'",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"router_src",
"... | Create a router file.
@param string $projectRoot
@return string
The absolute path to the router file. | [
"Create",
"a",
"router",
"file",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Server/ServerCommandBase.php#L305-L323 |
platformsh/platformsh-cli | src/Command/Server/ServerCommandBase.php | ServerCommandBase.getRoutesList | protected function getRoutesList($projectRoot, $address)
{
/** @var \Platformsh\Cli\Local\LocalProject $localProject */
$localProject = $this->getService('local.project');
$routesConfig = (array) $localProject->readProjectConfigFile($projectRoot, 'routes.yaml');
$routes = [];
foreach ($routesConfig as $route => $config) {
// If the route starts with http://{default}, replace it with the
// $address. This can't accommodate subdomains or HTTPS routes, so
// those are ignored.
$url = strpos($route, 'http://{default}') === 0
? 'http://' . $address . substr($route, 16)
: $route;
if (strpos($url, '{default}') !== false) {
continue;
}
$routes[$url] = $config + ['original_url' => $route];
}
return $routes;
} | php | protected function getRoutesList($projectRoot, $address)
{
/** @var \Platformsh\Cli\Local\LocalProject $localProject */
$localProject = $this->getService('local.project');
$routesConfig = (array) $localProject->readProjectConfigFile($projectRoot, 'routes.yaml');
$routes = [];
foreach ($routesConfig as $route => $config) {
// If the route starts with http://{default}, replace it with the
// $address. This can't accommodate subdomains or HTTPS routes, so
// those are ignored.
$url = strpos($route, 'http://{default}') === 0
? 'http://' . $address . substr($route, 16)
: $route;
if (strpos($url, '{default}') !== false) {
continue;
}
$routes[$url] = $config + ['original_url' => $route];
}
return $routes;
} | [
"protected",
"function",
"getRoutesList",
"(",
"$",
"projectRoot",
",",
"$",
"address",
")",
"{",
"/** @var \\Platformsh\\Cli\\Local\\LocalProject $localProject */",
"$",
"localProject",
"=",
"$",
"this",
"->",
"getService",
"(",
"'local.project'",
")",
";",
"$",
"rou... | @param string $projectRoot
@param string $address
@return array | [
"@param",
"string",
"$projectRoot",
"@param",
"string",
"$address"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Server/ServerCommandBase.php#L346-L367 |
platformsh/platformsh-cli | src/Command/Server/ServerCommandBase.php | ServerCommandBase.createEnv | protected function createEnv($projectRoot, $docRoot, $address, array $appConfig)
{
$realDocRoot = realpath($docRoot);
$envPrefix = $this->config()->get('service.env_prefix');
$env = [
'_PLATFORM_VARIABLES_PREFIX' => $envPrefix,
$envPrefix . 'ENVIRONMENT' => '_local',
$envPrefix . 'APPLICATION' => base64_encode(json_encode($appConfig)),
$envPrefix . 'APPLICATION_NAME' => isset($appConfig['name']) ? $appConfig['name'] : '',
$envPrefix . 'DOCUMENT_ROOT' => $realDocRoot,
$envPrefix . 'ROUTES' => base64_encode(json_encode($this->getRoutesList($projectRoot, $address))),
];
list($env['IP'], $env['PORT']) = explode(':', $address);
if (dirname($realDocRoot, 2) === $projectRoot . '/' . $this->config()->get('local.build_dir')) {
$env[$envPrefix . 'APP_DIR'] = dirname($realDocRoot);
}
if ($projectRoot === $this->getProjectRoot()) {
try {
$project = $this->getCurrentProject();
if ($project) {
$env[$envPrefix . 'PROJECT'] = $project->id;
}
} catch (\Exception $e) {
// Ignore errors
}
}
return $env;
} | php | protected function createEnv($projectRoot, $docRoot, $address, array $appConfig)
{
$realDocRoot = realpath($docRoot);
$envPrefix = $this->config()->get('service.env_prefix');
$env = [
'_PLATFORM_VARIABLES_PREFIX' => $envPrefix,
$envPrefix . 'ENVIRONMENT' => '_local',
$envPrefix . 'APPLICATION' => base64_encode(json_encode($appConfig)),
$envPrefix . 'APPLICATION_NAME' => isset($appConfig['name']) ? $appConfig['name'] : '',
$envPrefix . 'DOCUMENT_ROOT' => $realDocRoot,
$envPrefix . 'ROUTES' => base64_encode(json_encode($this->getRoutesList($projectRoot, $address))),
];
list($env['IP'], $env['PORT']) = explode(':', $address);
if (dirname($realDocRoot, 2) === $projectRoot . '/' . $this->config()->get('local.build_dir')) {
$env[$envPrefix . 'APP_DIR'] = dirname($realDocRoot);
}
if ($projectRoot === $this->getProjectRoot()) {
try {
$project = $this->getCurrentProject();
if ($project) {
$env[$envPrefix . 'PROJECT'] = $project->id;
}
} catch (\Exception $e) {
// Ignore errors
}
}
return $env;
} | [
"protected",
"function",
"createEnv",
"(",
"$",
"projectRoot",
",",
"$",
"docRoot",
",",
"$",
"address",
",",
"array",
"$",
"appConfig",
")",
"{",
"$",
"realDocRoot",
"=",
"realpath",
"(",
"$",
"docRoot",
")",
";",
"$",
"envPrefix",
"=",
"$",
"this",
"... | Create the virtual environment variables for a local server.
@param string $projectRoot
@param string $docRoot
@param string $address
@param array $appConfig
@return array | [
"Create",
"the",
"virtual",
"environment",
"variables",
"for",
"a",
"local",
"server",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Server/ServerCommandBase.php#L379-L410 |
platformsh/platformsh-cli | src/Service/State.php | State.get | public function get($key)
{
$this->load();
$value = NestedArrayUtil::getNestedArrayValue($this->state, explode('.', $key), $exists);
return $exists ? $value : false;
} | php | public function get($key)
{
$this->load();
$value = NestedArrayUtil::getNestedArrayValue($this->state, explode('.', $key), $exists);
return $exists ? $value : false;
} | [
"public",
"function",
"get",
"(",
"$",
"key",
")",
"{",
"$",
"this",
"->",
"load",
"(",
")",
";",
"$",
"value",
"=",
"NestedArrayUtil",
"::",
"getNestedArrayValue",
"(",
"$",
"this",
"->",
"state",
",",
"explode",
"(",
"'.'",
",",
"$",
"key",
")",
... | @param string $key
@return mixed|false
The value, or false if the value does not exist. | [
"@param",
"string",
"$key"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/State.php#L33-L39 |
platformsh/platformsh-cli | src/Service/State.php | State.set | public function set($key, $value, $save = true)
{
$this->load();
NestedArrayUtil::setNestedArrayValue($this->state, explode('.', $key), $value);
if ($save) {
$this->save();
}
} | php | public function set($key, $value, $save = true)
{
$this->load();
NestedArrayUtil::setNestedArrayValue($this->state, explode('.', $key), $value);
if ($save) {
$this->save();
}
} | [
"public",
"function",
"set",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"save",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"load",
"(",
")",
";",
"NestedArrayUtil",
"::",
"setNestedArrayValue",
"(",
"$",
"this",
"->",
"state",
",",
"explode",
"(",
... | Set a state value.
@param string $key
@param mixed $value
@param bool $save | [
"Set",
"a",
"state",
"value",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/State.php#L48-L55 |
platformsh/platformsh-cli | src/Service/State.php | State.load | protected function load()
{
if (!$this->loaded) {
$filename = $this->getFilename();
if (file_exists($filename)) {
$content = file_get_contents($filename);
$this->state = json_decode($content, true) ?: [];
}
$this->loaded = true;
}
} | php | protected function load()
{
if (!$this->loaded) {
$filename = $this->getFilename();
if (file_exists($filename)) {
$content = file_get_contents($filename);
$this->state = json_decode($content, true) ?: [];
}
$this->loaded = true;
}
} | [
"protected",
"function",
"load",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"loaded",
")",
"{",
"$",
"filename",
"=",
"$",
"this",
"->",
"getFilename",
"(",
")",
";",
"if",
"(",
"file_exists",
"(",
"$",
"filename",
")",
")",
"{",
"$",
"con... | Load state. | [
"Load",
"state",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/State.php#L71-L81 |
platformsh/platformsh-cli | src/Command/Integration/IntegrationAddCommand.php | IntegrationAddCommand.configure | protected function configure()
{
$this
->setName('integration:add')
->setDescription('Add an integration to the project');
$this->getForm()->configureInputDefinition($this->getDefinition());
$this->addProjectOption()->addWaitOptions();
$this->addExample(
'Add an integration with a GitHub repository',
'--type github --repository myuser/example-repo --token 9218376e14c2797e0d06e8d2f918d45f --fetch-branches 0'
);
$this->addExample(
'Add an integration with a GitLab repository',
'--type gitlab --repository mygroup/example-repo --token 22fe4d70dfbc20e4f668568a0b5422e2 --base-url https://gitlab.example.com'
);
} | php | protected function configure()
{
$this
->setName('integration:add')
->setDescription('Add an integration to the project');
$this->getForm()->configureInputDefinition($this->getDefinition());
$this->addProjectOption()->addWaitOptions();
$this->addExample(
'Add an integration with a GitHub repository',
'--type github --repository myuser/example-repo --token 9218376e14c2797e0d06e8d2f918d45f --fetch-branches 0'
);
$this->addExample(
'Add an integration with a GitLab repository',
'--type gitlab --repository mygroup/example-repo --token 22fe4d70dfbc20e4f668568a0b5422e2 --base-url https://gitlab.example.com'
);
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'integration:add'",
")",
"->",
"setDescription",
"(",
"'Add an integration to the project'",
")",
";",
"$",
"this",
"->",
"getForm",
"(",
")",
"->",
"configureInputDefinition"... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Integration/IntegrationAddCommand.php#L14-L29 |
platformsh/platformsh-cli | src/Command/User/UserAddCommand.php | UserAddCommand.validateEmail | private function validateEmail($value)
{
if (empty($value)) {
throw new InvalidArgumentException('An email address is required.');
}
if (!$filtered = filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Invalid email address: ' . $value);
}
return $filtered;
} | php | private function validateEmail($value)
{
if (empty($value)) {
throw new InvalidArgumentException('An email address is required.');
}
if (!$filtered = filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Invalid email address: ' . $value);
}
return $filtered;
} | [
"private",
"function",
"validateEmail",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'An email address is required.'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"filtered",
"... | Validate an email address.
@param string $value
@throws \Symfony\Component\Console\Exception\InvalidArgumentException
@return string | [
"Validate",
"an",
"email",
"address",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/User/UserAddCommand.php#L352-L362 |
platformsh/platformsh-cli | src/Command/User/UserAddCommand.php | UserAddCommand.matchRole | private function matchRole($input, array $roles)
{
foreach ($roles as $role) {
if (strpos($role, strtolower($input)) === 0) {
return $role;
}
}
throw new InvalidArgumentException('Invalid role: ' . $input);
} | php | private function matchRole($input, array $roles)
{
foreach ($roles as $role) {
if (strpos($role, strtolower($input)) === 0) {
return $role;
}
}
throw new InvalidArgumentException('Invalid role: ' . $input);
} | [
"private",
"function",
"matchRole",
"(",
"$",
"input",
",",
"array",
"$",
"roles",
")",
"{",
"foreach",
"(",
"$",
"roles",
"as",
"$",
"role",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"role",
",",
"strtolower",
"(",
"$",
"input",
")",
")",
"===",
... | Complete a role name based on an array of allowed roles.
@param string $input
@param string[] $roles
@return string | [
"Complete",
"a",
"role",
"name",
"based",
"on",
"an",
"array",
"of",
"allowed",
"roles",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/User/UserAddCommand.php#L372-L381 |
platformsh/platformsh-cli | src/Command/User/UserAddCommand.php | UserAddCommand.describeRoles | private function describeRoles(array $roles)
{
$withInitials = array_map(function ($role) {
return sprintf('%s (%s)', $role, substr($role, 0, 1));
}, $roles);
$last = array_pop($withInitials);
return implode(' or ', [implode(', ', $withInitials), $last]);
} | php | private function describeRoles(array $roles)
{
$withInitials = array_map(function ($role) {
return sprintf('%s (%s)', $role, substr($role, 0, 1));
}, $roles);
$last = array_pop($withInitials);
return implode(' or ', [implode(', ', $withInitials), $last]);
} | [
"private",
"function",
"describeRoles",
"(",
"array",
"$",
"roles",
")",
"{",
"$",
"withInitials",
"=",
"array_map",
"(",
"function",
"(",
"$",
"role",
")",
"{",
"return",
"sprintf",
"(",
"'%s (%s)'",
",",
"$",
"role",
",",
"substr",
"(",
"$",
"role",
... | Expand roles into a list with abbreviations.
@param string[] $roles
@return string | [
"Expand",
"roles",
"into",
"a",
"list",
"with",
"abbreviations",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/User/UserAddCommand.php#L390-L398 |
platformsh/platformsh-cli | src/Command/User/UserAddCommand.php | UserAddCommand.getUserLabel | private function getUserLabel(ProjectAccess $access)
{
$account = $this->api()->getAccount($access);
return sprintf('<info>%s</info> (%s)', $account['display_name'], $account['email']);
} | php | private function getUserLabel(ProjectAccess $access)
{
$account = $this->api()->getAccount($access);
return sprintf('<info>%s</info> (%s)', $account['display_name'], $account['email']);
} | [
"private",
"function",
"getUserLabel",
"(",
"ProjectAccess",
"$",
"access",
")",
"{",
"$",
"account",
"=",
"$",
"this",
"->",
"api",
"(",
")",
"->",
"getAccount",
"(",
"$",
"access",
")",
";",
"return",
"sprintf",
"(",
"'<info>%s</info> (%s)'",
",",
"$",
... | Return a label describing a user.
@param \Platformsh\Client\Model\ProjectAccess $access
@return string | [
"Return",
"a",
"label",
"describing",
"a",
"user",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/User/UserAddCommand.php#L421-L426 |
platformsh/platformsh-cli | src/Command/User/UserAddCommand.php | UserAddCommand.showProjectRoleForm | private function showProjectRoleForm($defaultRole, InputInterface $input)
{
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$this->stdErr->writeln("The user's project role can be " . $this->describeRoles(ProjectAccess::$roles) . '.');
$this->stdErr->writeln('');
$question = new Question(
sprintf('Project role (default: %s) <question>%s</question>: ', $defaultRole, $this->describeRoleInput(ProjectAccess::$roles)),
$defaultRole
);
$question->setValidator(function ($answer) {
return $this->validateProjectRole($answer);
});
$question->setMaxAttempts(5);
$question->setAutocompleterValues(ProjectAccess::$roles);
return $questionHelper->ask($input, $this->stdErr, $question);
} | php | private function showProjectRoleForm($defaultRole, InputInterface $input)
{
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$this->stdErr->writeln("The user's project role can be " . $this->describeRoles(ProjectAccess::$roles) . '.');
$this->stdErr->writeln('');
$question = new Question(
sprintf('Project role (default: %s) <question>%s</question>: ', $defaultRole, $this->describeRoleInput(ProjectAccess::$roles)),
$defaultRole
);
$question->setValidator(function ($answer) {
return $this->validateProjectRole($answer);
});
$question->setMaxAttempts(5);
$question->setAutocompleterValues(ProjectAccess::$roles);
return $questionHelper->ask($input, $this->stdErr, $question);
} | [
"private",
"function",
"showProjectRoleForm",
"(",
"$",
"defaultRole",
",",
"InputInterface",
"$",
"input",
")",
"{",
"/** @var \\Platformsh\\Cli\\Service\\QuestionHelper $questionHelper */",
"$",
"questionHelper",
"=",
"$",
"this",
"->",
"getService",
"(",
"'question_helpe... | Show the form for entering the project role.
@param string $defaultRole
@param \Symfony\Component\Console\Input\InputInterface $input
@return string | [
"Show",
"the",
"form",
"for",
"entering",
"the",
"project",
"role",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/User/UserAddCommand.php#L436-L454 |
platformsh/platformsh-cli | src/Command/User/UserAddCommand.php | UserAddCommand.getEnvironmentRoles | private function getEnvironmentRoles(ProjectAccess $projectAccess)
{
$environmentRoles = [];
if ($projectAccess->role === ProjectAccess::ROLE_ADMIN) {
return [];
}
// @todo find out why $environment->getUser() has permission issues - it would be a lot faster than this
$progress = new ProgressBar(isset($this->stdErr) && $this->stdErr->isDecorated() ? $this->stdErr : new NullOutput());
$progress->setMessage('Loading environments...');
$progress->setFormat('%message% %current%/%max%');
$environments = $this->api()->getEnvironments($this->getSelectedProject());
$progress->start(count($environments));
foreach ($environments as $environment) {
if ($access = $environment->getUser($projectAccess->id)) {
$environmentRoles[$environment->id] = $access->role;
}
$progress->advance();
}
$progress->finish();
$progress->clear();
return $environmentRoles;
} | php | private function getEnvironmentRoles(ProjectAccess $projectAccess)
{
$environmentRoles = [];
if ($projectAccess->role === ProjectAccess::ROLE_ADMIN) {
return [];
}
// @todo find out why $environment->getUser() has permission issues - it would be a lot faster than this
$progress = new ProgressBar(isset($this->stdErr) && $this->stdErr->isDecorated() ? $this->stdErr : new NullOutput());
$progress->setMessage('Loading environments...');
$progress->setFormat('%message% %current%/%max%');
$environments = $this->api()->getEnvironments($this->getSelectedProject());
$progress->start(count($environments));
foreach ($environments as $environment) {
if ($access = $environment->getUser($projectAccess->id)) {
$environmentRoles[$environment->id] = $access->role;
}
$progress->advance();
}
$progress->finish();
$progress->clear();
return $environmentRoles;
} | [
"private",
"function",
"getEnvironmentRoles",
"(",
"ProjectAccess",
"$",
"projectAccess",
")",
"{",
"$",
"environmentRoles",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"projectAccess",
"->",
"role",
"===",
"ProjectAccess",
"::",
"ROLE_ADMIN",
")",
"{",
"return",
"[",... | Load the user's roles on the project's environments.
@param \Platformsh\Client\Model\ProjectAccess $projectAccess
@return array | [
"Load",
"the",
"user",
"s",
"roles",
"on",
"the",
"project",
"s",
"environments",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/User/UserAddCommand.php#L463-L487 |
platformsh/platformsh-cli | src/Command/User/UserAddCommand.php | UserAddCommand.showEnvironmentRolesForm | private function showEnvironmentRolesForm(array $defaultEnvironmentRoles, InputInterface $input)
{
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$desiredEnvironmentRoles = [];
$validEnvironmentRoles = array_merge(EnvironmentAccess::$roles, ['none']);
$this->stdErr->writeln("The user's environment role(s) can be " . $this->describeRoles($validEnvironmentRoles) . '.');
$initials = $this->describeRoleInput($validEnvironmentRoles);
$this->stdErr->writeln('');
foreach (array_keys($this->api()->getEnvironments($this->getSelectedProject())) as $id) {
$default = isset($defaultEnvironmentRoles[$id]) ? $defaultEnvironmentRoles[$id] : 'none';
$question = new Question(
sprintf('Role on <info>%s</info> (default: %s) <question>%s</question>: ', $id, $default, $initials),
$default
);
$question->setValidator(function ($answer) {
if ($answer === 'q' || $answer === 'quit') {
return $answer;
}
return $this->validateEnvironmentRole($answer);
});
$question->setAutocompleterValues(array_merge($validEnvironmentRoles, ['quit']));
$question->setMaxAttempts(5);
$answer = $questionHelper->ask($input, $this->stdErr, $question);
if ($answer === 'q' || $answer === 'quit') {
break;
} else {
$desiredEnvironmentRoles[$id] = $answer;
}
}
return $desiredEnvironmentRoles;
} | php | private function showEnvironmentRolesForm(array $defaultEnvironmentRoles, InputInterface $input)
{
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$desiredEnvironmentRoles = [];
$validEnvironmentRoles = array_merge(EnvironmentAccess::$roles, ['none']);
$this->stdErr->writeln("The user's environment role(s) can be " . $this->describeRoles($validEnvironmentRoles) . '.');
$initials = $this->describeRoleInput($validEnvironmentRoles);
$this->stdErr->writeln('');
foreach (array_keys($this->api()->getEnvironments($this->getSelectedProject())) as $id) {
$default = isset($defaultEnvironmentRoles[$id]) ? $defaultEnvironmentRoles[$id] : 'none';
$question = new Question(
sprintf('Role on <info>%s</info> (default: %s) <question>%s</question>: ', $id, $default, $initials),
$default
);
$question->setValidator(function ($answer) {
if ($answer === 'q' || $answer === 'quit') {
return $answer;
}
return $this->validateEnvironmentRole($answer);
});
$question->setAutocompleterValues(array_merge($validEnvironmentRoles, ['quit']));
$question->setMaxAttempts(5);
$answer = $questionHelper->ask($input, $this->stdErr, $question);
if ($answer === 'q' || $answer === 'quit') {
break;
} else {
$desiredEnvironmentRoles[$id] = $answer;
}
}
return $desiredEnvironmentRoles;
} | [
"private",
"function",
"showEnvironmentRolesForm",
"(",
"array",
"$",
"defaultEnvironmentRoles",
",",
"InputInterface",
"$",
"input",
")",
"{",
"/** @var \\Platformsh\\Cli\\Service\\QuestionHelper $questionHelper */",
"$",
"questionHelper",
"=",
"$",
"this",
"->",
"getService... | Show the form for entering environment roles.
@param array $defaultEnvironmentRoles
@param \Symfony\Component\Console\Input\InputInterface $input
@return array
The environment roles (keyed by environment ID) including the user's
answers. | [
"Show",
"the",
"form",
"for",
"entering",
"environment",
"roles",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/User/UserAddCommand.php#L499-L532 |
platformsh/platformsh-cli | src/Command/User/UserAddCommand.php | UserAddCommand.getSpecifiedProjectRole | private function getSpecifiedProjectRole(array $roles)
{
foreach ($roles as $role) {
if (strpos($role, ':') === false) {
return $this->validateProjectRole($role);
}
}
return null;
} | php | private function getSpecifiedProjectRole(array $roles)
{
foreach ($roles as $role) {
if (strpos($role, ':') === false) {
return $this->validateProjectRole($role);
}
}
return null;
} | [
"private",
"function",
"getSpecifiedProjectRole",
"(",
"array",
"$",
"roles",
")",
"{",
"foreach",
"(",
"$",
"roles",
"as",
"$",
"role",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"role",
",",
"':'",
")",
"===",
"false",
")",
"{",
"return",
"$",
"this"... | Extract the specified project role from the list (given in --role).
@param array $roles
@return string|null
The project role, or null if none is specified. | [
"Extract",
"the",
"specified",
"project",
"role",
"from",
"the",
"list",
"(",
"given",
"in",
"--",
"role",
")",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/User/UserAddCommand.php#L542-L551 |
platformsh/platformsh-cli | src/Command/User/UserAddCommand.php | UserAddCommand.getSpecifiedEnvironmentRoles | private function getSpecifiedEnvironmentRoles(array $roles)
{
$environmentRoles = [];
$project = $this->getSelectedProject();
$environments = $this->api()->getEnvironments($project);
foreach ($roles as $role) {
if (strpos($role, ':') === false) {
continue;
}
list($id, $role) = explode(':', $role, 2);
$role = $this->validateEnvironmentRole($role);
// Match environment IDs by wildcard.
if (strpos($id, '%') !== false) {
$pattern = '/^' . str_replace('%', '.*', preg_quote($id)) . '$/';
$matched = preg_grep($pattern, array_keys($environments));
if (empty($matched)) {
throw new InvalidArgumentException('No environment IDs match: ' . $id);
}
foreach ($matched as $environmentId) {
$environmentRoles[$environmentId] = $role;
}
continue;
}
if (!$this->api()->getEnvironment($id, $project)) {
throw new InvalidArgumentException('Environment not found: ' . $id);
}
$environmentRoles[$id] = $role;
}
return $environmentRoles;
} | php | private function getSpecifiedEnvironmentRoles(array $roles)
{
$environmentRoles = [];
$project = $this->getSelectedProject();
$environments = $this->api()->getEnvironments($project);
foreach ($roles as $role) {
if (strpos($role, ':') === false) {
continue;
}
list($id, $role) = explode(':', $role, 2);
$role = $this->validateEnvironmentRole($role);
// Match environment IDs by wildcard.
if (strpos($id, '%') !== false) {
$pattern = '/^' . str_replace('%', '.*', preg_quote($id)) . '$/';
$matched = preg_grep($pattern, array_keys($environments));
if (empty($matched)) {
throw new InvalidArgumentException('No environment IDs match: ' . $id);
}
foreach ($matched as $environmentId) {
$environmentRoles[$environmentId] = $role;
}
continue;
}
if (!$this->api()->getEnvironment($id, $project)) {
throw new InvalidArgumentException('Environment not found: ' . $id);
}
$environmentRoles[$id] = $role;
}
return $environmentRoles;
} | [
"private",
"function",
"getSpecifiedEnvironmentRoles",
"(",
"array",
"$",
"roles",
")",
"{",
"$",
"environmentRoles",
"=",
"[",
"]",
";",
"$",
"project",
"=",
"$",
"this",
"->",
"getSelectedProject",
"(",
")",
";",
"$",
"environments",
"=",
"$",
"this",
"-... | Extract the specified environment roles from the list (given in --role).
@param string[] $roles
@return array
An array of environment roles, keyed by environment ID. | [
"Extract",
"the",
"specified",
"environment",
"roles",
"from",
"the",
"list",
"(",
"given",
"in",
"--",
"role",
")",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/User/UserAddCommand.php#L561-L591 |
platformsh/platformsh-cli | src/Command/Commit/CommitListCommand.php | CommitListCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input, false, true);
$environment = $this->getSelectedEnvironment();
$startSha = $input->getArgument('commit');
/** @var \Platformsh\Cli\Service\GitDataApi $gitData */
$gitData = $this->getService('git_data_api');
$startCommit = $gitData->getCommit($environment, $startSha);
if (!$startCommit) {
if ($startSha) {
$this->stdErr->writeln('Commit not found: <error>' . $startSha . '</error>');
} else {
$this->stdErr->writeln('No commits found.');
}
return 1;
}
/** @var Table $table */
$table = $this->getService('table');
if (!$table->formatIsMachineReadable()) {
$this->stdErr->writeln(sprintf(
'Commits on the project %s, environment %s:',
$this->api()->getProjectLabel($this->getSelectedProject()),
$this->api()->getEnvironmentLabel($environment)
));
}
$commits = $this->loadCommitList($environment, $startCommit, $input->getOption('limit'));
/** @var PropertyFormatter $formatter */
$formatter = $this->getService('property_formatter');
$header = ['Date', 'SHA', 'Author', 'Summary'];
$rows = [];
foreach ($commits as $commit) {
$row = [];
$row[] = new AdaptiveTableCell(
$formatter->format($commit->author['date'], 'author.date'),
['wrap' => false]
);
$row[] = new AdaptiveTableCell($commit->sha, ['wrap' => false]);
$row[] = $commit->author['name'];
$row[] = $this->summarize($commit->message);
$rows[] = $row;
}
$table->render($rows, $header);
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input, false, true);
$environment = $this->getSelectedEnvironment();
$startSha = $input->getArgument('commit');
/** @var \Platformsh\Cli\Service\GitDataApi $gitData */
$gitData = $this->getService('git_data_api');
$startCommit = $gitData->getCommit($environment, $startSha);
if (!$startCommit) {
if ($startSha) {
$this->stdErr->writeln('Commit not found: <error>' . $startSha . '</error>');
} else {
$this->stdErr->writeln('No commits found.');
}
return 1;
}
/** @var Table $table */
$table = $this->getService('table');
if (!$table->formatIsMachineReadable()) {
$this->stdErr->writeln(sprintf(
'Commits on the project %s, environment %s:',
$this->api()->getProjectLabel($this->getSelectedProject()),
$this->api()->getEnvironmentLabel($environment)
));
}
$commits = $this->loadCommitList($environment, $startCommit, $input->getOption('limit'));
/** @var PropertyFormatter $formatter */
$formatter = $this->getService('property_formatter');
$header = ['Date', 'SHA', 'Author', 'Summary'];
$rows = [];
foreach ($commits as $commit) {
$row = [];
$row[] = new AdaptiveTableCell(
$formatter->format($commit->author['date'], 'author.date'),
['wrap' => false]
);
$row[] = new AdaptiveTableCell($commit->sha, ['wrap' => false]);
$row[] = $commit->author['name'];
$row[] = $this->summarize($commit->message);
$rows[] = $row;
}
$table->render($rows, $header);
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"validateInput",
"(",
"$",
"input",
",",
"false",
",",
"true",
")",
";",
"$",
"environment",
"=",
"$",
"this",
"-... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Commit/CommitListCommand.php#L46-L98 |
platformsh/platformsh-cli | src/Command/Commit/CommitListCommand.php | CommitListCommand.loadCommitList | private function loadCommitList(Environment $environment, Commit $startCommit, $limit = 10)
{
/** @var Commit[] $commits */
$commits = [$startCommit];
if (!count($startCommit->parents) || $limit === 1) {
return $commits;
}
/** @var \Platformsh\Cli\Service\GitDataApi $gitData */
$gitData = $this->getService('git_data_api');
$progress = new ProgressBar($this->stdErr->isDecorated() ? $this->stdErr : new NullOutput());
$progress->setMessage('Loading...');
$progress->setFormat('%message% %current% (limit: %max%)');
$progress->start($limit);
for ($currentCommit = $startCommit;
count($currentCommit->parents) && count($commits) < $limit;) {
foreach (array_reverse($currentCommit->parents) as $parentSha) {
if (!isset($commits[$parentSha])) {
$commits[$parentSha] = $gitData->getCommit($environment, $parentSha);
}
$currentCommit = $commits[$parentSha];
$progress->advance();
}
}
$progress->clear();
return $commits;
} | php | private function loadCommitList(Environment $environment, Commit $startCommit, $limit = 10)
{
/** @var Commit[] $commits */
$commits = [$startCommit];
if (!count($startCommit->parents) || $limit === 1) {
return $commits;
}
/** @var \Platformsh\Cli\Service\GitDataApi $gitData */
$gitData = $this->getService('git_data_api');
$progress = new ProgressBar($this->stdErr->isDecorated() ? $this->stdErr : new NullOutput());
$progress->setMessage('Loading...');
$progress->setFormat('%message% %current% (limit: %max%)');
$progress->start($limit);
for ($currentCommit = $startCommit;
count($currentCommit->parents) && count($commits) < $limit;) {
foreach (array_reverse($currentCommit->parents) as $parentSha) {
if (!isset($commits[$parentSha])) {
$commits[$parentSha] = $gitData->getCommit($environment, $parentSha);
}
$currentCommit = $commits[$parentSha];
$progress->advance();
}
}
$progress->clear();
return $commits;
} | [
"private",
"function",
"loadCommitList",
"(",
"Environment",
"$",
"environment",
",",
"Commit",
"$",
"startCommit",
",",
"$",
"limit",
"=",
"10",
")",
"{",
"/** @var Commit[] $commits */",
"$",
"commits",
"=",
"[",
"$",
"startCommit",
"]",
";",
"if",
"(",
"!... | Load parent commits, recursively, up to the limit.
@param \Platformsh\Client\Model\Environment $environment
@param \Platformsh\Client\Model\Git\Commit $startCommit
@param int $limit
@return \Platformsh\Client\Model\Git\Commit[] | [
"Load",
"parent",
"commits",
"recursively",
"up",
"to",
"the",
"limit",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Commit/CommitListCommand.php#L109-L137 |
platformsh/platformsh-cli | src/Command/Commit/CommitListCommand.php | CommitListCommand.summarize | private function summarize($message)
{
$message = ltrim($message, "\n");
if ($newLinePos = strpos($message, "\n")) {
$message = substr($message, 0, $newLinePos);
}
return rtrim($message);
} | php | private function summarize($message)
{
$message = ltrim($message, "\n");
if ($newLinePos = strpos($message, "\n")) {
$message = substr($message, 0, $newLinePos);
}
return rtrim($message);
} | [
"private",
"function",
"summarize",
"(",
"$",
"message",
")",
"{",
"$",
"message",
"=",
"ltrim",
"(",
"$",
"message",
",",
"\"\\n\"",
")",
";",
"if",
"(",
"$",
"newLinePos",
"=",
"strpos",
"(",
"$",
"message",
",",
"\"\\n\"",
")",
")",
"{",
"$",
"m... | Summarize a commit message.
@param string $message
@return string | [
"Summarize",
"a",
"commit",
"message",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Commit/CommitListCommand.php#L146-L154 |
platformsh/platformsh-cli | src/Session/KeychainStorage.php | KeychainStorage.load | public function load(SessionInterface $session)
{
$data = $this->exec(array_merge([
'security',
'find-generic-password',
'-w', // Output the data to stdout.
], $this->getKeyIdentifiers($session)));
if (is_string($data)) {
$session->setData($this->deserialize($data));
} else {
// If data doesn't exist in the keychain yet, load it from an old
// file for backwards compatibility.
$this->loadFromFile($session);
}
} | php | public function load(SessionInterface $session)
{
$data = $this->exec(array_merge([
'security',
'find-generic-password',
'-w', // Output the data to stdout.
], $this->getKeyIdentifiers($session)));
if (is_string($data)) {
$session->setData($this->deserialize($data));
} else {
// If data doesn't exist in the keychain yet, load it from an old
// file for backwards compatibility.
$this->loadFromFile($session);
}
} | [
"public",
"function",
"load",
"(",
"SessionInterface",
"$",
"session",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"exec",
"(",
"array_merge",
"(",
"[",
"'security'",
",",
"'find-generic-password'",
",",
"'-w'",
",",
"// Output the data to stdout.",
"]",
",... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Session/KeychainStorage.php#L43-L58 |
platformsh/platformsh-cli | src/Session/KeychainStorage.php | KeychainStorage.loadFromFile | private function loadFromFile(SessionInterface $session)
{
$id = preg_replace('/[^\w\-]+/', '-', $session->getId());
$dir = (new Config())->getSessionDir();
$filename = "$dir/sess-$id/sess-$id.json";
if (is_readable($filename) && ($contents = file_get_contents($filename))) {
$data = json_decode($contents, true) ?: [];
$session->setData($data);
$this->save($session);
// Reload the session from the keychain, and delete the file if
// successful.
if (rename($filename, $filename . '.bak')) {
$this->load($session);
if ($session->getData()) {
unlink($filename . '.bak');
}
}
}
} | php | private function loadFromFile(SessionInterface $session)
{
$id = preg_replace('/[^\w\-]+/', '-', $session->getId());
$dir = (new Config())->getSessionDir();
$filename = "$dir/sess-$id/sess-$id.json";
if (is_readable($filename) && ($contents = file_get_contents($filename))) {
$data = json_decode($contents, true) ?: [];
$session->setData($data);
$this->save($session);
// Reload the session from the keychain, and delete the file if
// successful.
if (rename($filename, $filename . '.bak')) {
$this->load($session);
if ($session->getData()) {
unlink($filename . '.bak');
}
}
}
} | [
"private",
"function",
"loadFromFile",
"(",
"SessionInterface",
"$",
"session",
")",
"{",
"$",
"id",
"=",
"preg_replace",
"(",
"'/[^\\w\\-]+/'",
",",
"'-'",
",",
"$",
"session",
"->",
"getId",
"(",
")",
")",
";",
"$",
"dir",
"=",
"(",
"new",
"Config",
... | Load the session from an old file for backwards compatibility.
@param \Platformsh\Client\Session\SessionInterface $session | [
"Load",
"the",
"session",
"from",
"an",
"old",
"file",
"for",
"backwards",
"compatibility",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Session/KeychainStorage.php#L65-L83 |
platformsh/platformsh-cli | src/Session/KeychainStorage.php | KeychainStorage.save | public function save(SessionInterface $session)
{
$result = $this->exec(array_merge(
[
'security',
'add-generic-password',
'-U', // Update if the key already exists.
],
$this->getKeyIdentifiers($session),
[
// The data ("password") to store. This must be the final
// argument.
'-w' . $this->serialize($session->getData()),
]
));
if ($result === false) {
throw new \RuntimeException('Failed to save the session to the keychain');
}
} | php | public function save(SessionInterface $session)
{
$result = $this->exec(array_merge(
[
'security',
'add-generic-password',
'-U', // Update if the key already exists.
],
$this->getKeyIdentifiers($session),
[
// The data ("password") to store. This must be the final
// argument.
'-w' . $this->serialize($session->getData()),
]
));
if ($result === false) {
throw new \RuntimeException('Failed to save the session to the keychain');
}
} | [
"public",
"function",
"save",
"(",
"SessionInterface",
"$",
"session",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"exec",
"(",
"array_merge",
"(",
"[",
"'security'",
",",
"'add-generic-password'",
",",
"'-U'",
",",
"// Update if the key already exists.",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Session/KeychainStorage.php#L88-L106 |
platformsh/platformsh-cli | src/Session/KeychainStorage.php | KeychainStorage.getKeyIdentifiers | private function getKeyIdentifiers(SessionInterface $session)
{
return [
// Account name:
'-a' . $this->getAccountName(),
// Service name:
'-s' . 'session-' . $session->getId(),
// Label:
'-l' . $this->appName . ': ' . $session->getId(),
];
} | php | private function getKeyIdentifiers(SessionInterface $session)
{
return [
// Account name:
'-a' . $this->getAccountName(),
// Service name:
'-s' . 'session-' . $session->getId(),
// Label:
'-l' . $this->appName . ': ' . $session->getId(),
];
} | [
"private",
"function",
"getKeyIdentifiers",
"(",
"SessionInterface",
"$",
"session",
")",
"{",
"return",
"[",
"// Account name:",
"'-a'",
".",
"$",
"this",
"->",
"getAccountName",
"(",
")",
",",
"// Service name:",
"'-s'",
".",
"'session-'",
".",
"$",
"session",... | Get arguments identifying the key to the 'security' utility.
@param \Platformsh\Client\Session\SessionInterface $session
@return array | [
"Get",
"arguments",
"identifying",
"the",
"key",
"to",
"the",
"security",
"utility",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Session/KeychainStorage.php#L127-L137 |
platformsh/platformsh-cli | src/Session/KeychainStorage.php | KeychainStorage.exec | private static function exec(array $args)
{
$cmd = implode(' ', array_map('escapeshellarg', $args)) . ' 2>/dev/null';
$process = proc_open($cmd, [1 => ['pipe', 'w']], $pipes);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
if (proc_close($process) !== 0) {
return false;
}
return $output;
} | php | private static function exec(array $args)
{
$cmd = implode(' ', array_map('escapeshellarg', $args)) . ' 2>/dev/null';
$process = proc_open($cmd, [1 => ['pipe', 'w']], $pipes);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
if (proc_close($process) !== 0) {
return false;
}
return $output;
} | [
"private",
"static",
"function",
"exec",
"(",
"array",
"$",
"args",
")",
"{",
"$",
"cmd",
"=",
"implode",
"(",
"' '",
",",
"array_map",
"(",
"'escapeshellarg'",
",",
"$",
"args",
")",
")",
".",
"' 2>/dev/null'",
";",
"$",
"process",
"=",
"proc_open",
"... | Execute a command (on OS X) without displaying it or its result.
@param string[] $args
@return string|false The command's stdout output, or false on failure. | [
"Execute",
"a",
"command",
"(",
"on",
"OS",
"X",
")",
"without",
"displaying",
"it",
"or",
"its",
"result",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Session/KeychainStorage.php#L156-L167 |
platformsh/platformsh-cli | src/Session/KeychainStorage.php | KeychainStorage.deserialize | private function deserialize($data)
{
$result = json_decode(base64_decode($data, true), true);
return is_array($result) ? $result : [];
} | php | private function deserialize($data)
{
$result = json_decode(base64_decode($data, true), true);
return is_array($result) ? $result : [];
} | [
"private",
"function",
"deserialize",
"(",
"$",
"data",
")",
"{",
"$",
"result",
"=",
"json_decode",
"(",
"base64_decode",
"(",
"$",
"data",
",",
"true",
")",
",",
"true",
")",
";",
"return",
"is_array",
"(",
"$",
"result",
")",
"?",
"$",
"result",
"... | Deserialize session data.
@param string $data
@return array | [
"Deserialize",
"session",
"data",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Session/KeychainStorage.php#L188-L193 |
platformsh/platformsh-cli | src/SiteAlias/DrushAlias.php | DrushAlias.createAliases | public function createAliases(Project $project, $aliasGroup, array $apps, array $environments, $previousGroup = null)
{
if (!count($apps)) {
return false;
}
// Prepare the Drush directory and file.
$aliasDir = $this->drush->getSiteAliasDir();
if (!is_dir($aliasDir) && !mkdir($aliasDir, 0755, true)) {
throw new \RuntimeException('Drush aliases directory not found: ' . $aliasDir);
}
if (!is_writable($aliasDir)) {
throw new \RuntimeException('Drush aliases directory not writable: ' . $aliasDir);
}
$filename = $this->getFilename($aliasGroup);
if (file_exists($filename) && !is_writable($filename)) {
throw new \RuntimeException("Drush alias file not writable: $filename");
}
// Gather existing aliases.
$existingAliases = $this->getExistingAliases($aliasGroup, $previousGroup);
// Generate the new aliases.
$newAliases = $this->generateNewAliases($apps, $environments);
// Merge new aliases with existing ones.
$newAliases = $this->mergeExisting($newAliases, $existingAliases);
// Add any user-defined (pre-existing) aliases.
$autoRemoveKey = $this->getAutoRemoveKey();
$userDefinedAliases = [];
foreach ($existingAliases as $name => $alias) {
if (!empty($alias[$autoRemoveKey]) || !empty($alias['options'][$autoRemoveKey])) {
// This is probably for a deleted environment.
continue;
}
$userDefinedAliases[$name] = $alias;
}
$aliases = $userDefinedAliases + $newAliases;
// Normalize the aliases.
$aliases = $this->normalize($aliases);
// Format the aliases as a string.
$header = rtrim($this->getHeader($project)) . "\n\n";
$content = $header . $this->formatAliases($aliases);
(new Filesystem())->writeFile($filename, $content);
return true;
} | php | public function createAliases(Project $project, $aliasGroup, array $apps, array $environments, $previousGroup = null)
{
if (!count($apps)) {
return false;
}
// Prepare the Drush directory and file.
$aliasDir = $this->drush->getSiteAliasDir();
if (!is_dir($aliasDir) && !mkdir($aliasDir, 0755, true)) {
throw new \RuntimeException('Drush aliases directory not found: ' . $aliasDir);
}
if (!is_writable($aliasDir)) {
throw new \RuntimeException('Drush aliases directory not writable: ' . $aliasDir);
}
$filename = $this->getFilename($aliasGroup);
if (file_exists($filename) && !is_writable($filename)) {
throw new \RuntimeException("Drush alias file not writable: $filename");
}
// Gather existing aliases.
$existingAliases = $this->getExistingAliases($aliasGroup, $previousGroup);
// Generate the new aliases.
$newAliases = $this->generateNewAliases($apps, $environments);
// Merge new aliases with existing ones.
$newAliases = $this->mergeExisting($newAliases, $existingAliases);
// Add any user-defined (pre-existing) aliases.
$autoRemoveKey = $this->getAutoRemoveKey();
$userDefinedAliases = [];
foreach ($existingAliases as $name => $alias) {
if (!empty($alias[$autoRemoveKey]) || !empty($alias['options'][$autoRemoveKey])) {
// This is probably for a deleted environment.
continue;
}
$userDefinedAliases[$name] = $alias;
}
$aliases = $userDefinedAliases + $newAliases;
// Normalize the aliases.
$aliases = $this->normalize($aliases);
// Format the aliases as a string.
$header = rtrim($this->getHeader($project)) . "\n\n";
$content = $header . $this->formatAliases($aliases);
(new Filesystem())->writeFile($filename, $content);
return true;
} | [
"public",
"function",
"createAliases",
"(",
"Project",
"$",
"project",
",",
"$",
"aliasGroup",
",",
"array",
"$",
"apps",
",",
"array",
"$",
"environments",
",",
"$",
"previousGroup",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"count",
"(",
"$",
"apps",
")... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SiteAlias/DrushAlias.php#L31-L81 |
platformsh/platformsh-cli | src/SiteAlias/DrushAlias.php | DrushAlias.mergeExisting | protected function mergeExisting($new, $existing)
{
foreach ($new as $aliasName => &$newAlias) {
// If the alias already exists, recursively replace existing
// settings with new ones.
if (isset($existing[$aliasName])) {
$newAlias = array_replace_recursive($existing[$aliasName], $newAlias);
}
}
return $new;
} | php | protected function mergeExisting($new, $existing)
{
foreach ($new as $aliasName => &$newAlias) {
// If the alias already exists, recursively replace existing
// settings with new ones.
if (isset($existing[$aliasName])) {
$newAlias = array_replace_recursive($existing[$aliasName], $newAlias);
}
}
return $new;
} | [
"protected",
"function",
"mergeExisting",
"(",
"$",
"new",
",",
"$",
"existing",
")",
"{",
"foreach",
"(",
"$",
"new",
"as",
"$",
"aliasName",
"=>",
"&",
"$",
"newAlias",
")",
"{",
"// If the alias already exists, recursively replace existing",
"// settings with new... | Merge new aliases with existing ones.
@param array $new
@param array $existing
@return array | [
"Merge",
"new",
"aliases",
"with",
"existing",
"ones",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SiteAlias/DrushAlias.php#L91-L102 |
platformsh/platformsh-cli | src/SiteAlias/DrushAlias.php | DrushAlias.getExistingAliases | protected function getExistingAliases($currentGroup, $previousGroup = null)
{
$aliases = [];
foreach (array_filter([$currentGroup, $previousGroup]) as $groupName) {
foreach ($this->drush->getAliases($groupName) as $name => $alias) {
// Remove the group prefix from the alias name.
$name = ltrim($name, '@');
if (strpos($name, $groupName . '.') === 0) {
$name = substr($name, strlen($groupName . '.'));
}
$aliases[$name] = $alias;
}
}
return $aliases;
} | php | protected function getExistingAliases($currentGroup, $previousGroup = null)
{
$aliases = [];
foreach (array_filter([$currentGroup, $previousGroup]) as $groupName) {
foreach ($this->drush->getAliases($groupName) as $name => $alias) {
// Remove the group prefix from the alias name.
$name = ltrim($name, '@');
if (strpos($name, $groupName . '.') === 0) {
$name = substr($name, strlen($groupName . '.'));
}
$aliases[$name] = $alias;
}
}
return $aliases;
} | [
"protected",
"function",
"getExistingAliases",
"(",
"$",
"currentGroup",
",",
"$",
"previousGroup",
"=",
"null",
")",
"{",
"$",
"aliases",
"=",
"[",
"]",
";",
"foreach",
"(",
"array_filter",
"(",
"[",
"$",
"currentGroup",
",",
"$",
"previousGroup",
"]",
")... | Find the existing defined aliases so they can be merged with new ones.
@param string $currentGroup
@param string|null $previousGroup
@return array
The aliases, with their group prefixes removed. | [
"Find",
"the",
"existing",
"defined",
"aliases",
"so",
"they",
"can",
"be",
"merged",
"with",
"new",
"ones",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SiteAlias/DrushAlias.php#L143-L159 |
platformsh/platformsh-cli | src/SiteAlias/DrushAlias.php | DrushAlias.generateNewAliases | protected function generateNewAliases(array $apps, array $environments)
{
$aliases = [];
foreach ($apps as $app) {
$appId = $app->getId();
// Generate an alias for the local environment.
$localAliasName = '_local';
if (count($apps) > 1) {
$localAliasName .= '--' . $appId;
}
$aliases[$localAliasName] = $this->generateLocalAlias($app);
// Generate aliases for the remote environments.
foreach ($environments as $environment) {
$alias = $this->generateRemoteAlias($environment, $app);
if (!$alias) {
continue;
}
$aliasName = $environment->id;
if (count($apps) > 1) {
$aliasName .= '--' . $appId;
}
$aliases[$aliasName] = $alias;
}
}
return $aliases;
} | php | protected function generateNewAliases(array $apps, array $environments)
{
$aliases = [];
foreach ($apps as $app) {
$appId = $app->getId();
// Generate an alias for the local environment.
$localAliasName = '_local';
if (count($apps) > 1) {
$localAliasName .= '--' . $appId;
}
$aliases[$localAliasName] = $this->generateLocalAlias($app);
// Generate aliases for the remote environments.
foreach ($environments as $environment) {
$alias = $this->generateRemoteAlias($environment, $app);
if (!$alias) {
continue;
}
$aliasName = $environment->id;
if (count($apps) > 1) {
$aliasName .= '--' . $appId;
}
$aliases[$aliasName] = $alias;
}
}
return $aliases;
} | [
"protected",
"function",
"generateNewAliases",
"(",
"array",
"$",
"apps",
",",
"array",
"$",
"environments",
")",
"{",
"$",
"aliases",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"apps",
"as",
"$",
"app",
")",
"{",
"$",
"appId",
"=",
"$",
"app",
"->",
... | Generate new aliases.
@param LocalApplication[] $apps
@param array $environments
@return array | [
"Generate",
"new",
"aliases",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SiteAlias/DrushAlias.php#L169-L200 |
platformsh/platformsh-cli | src/SiteAlias/DrushAlias.php | DrushAlias.generateRemoteAlias | protected function generateRemoteAlias(Environment $environment, LocalApplication $app)
{
if (!$environment->hasLink('ssh')) {
return false;
}
$sshUrl = $environment->getSshUrl($app->getName());
$alias = [
'options' => [
$this->getAutoRemoveKey() => true,
],
];
// For most environments, we know the application root directory is
// '/app'. It's different in Enterprise environments.
if ($environment->deployment_target !== 'local') {
$appRoot = $this->drush->getCachedAppRoot($sshUrl);
if ($appRoot) {
$alias['root'] = rtrim($appRoot, '/') . '/' . $app->getDocumentRoot();
}
} else {
$alias['root'] = '/app/' . $app->getDocumentRoot();
}
list($alias['user'], $alias['host']) = explode('@', $sshUrl, 2);
if ($url = $this->getUrl($environment)) {
$alias['uri'] = $url;
}
return $alias;
} | php | protected function generateRemoteAlias(Environment $environment, LocalApplication $app)
{
if (!$environment->hasLink('ssh')) {
return false;
}
$sshUrl = $environment->getSshUrl($app->getName());
$alias = [
'options' => [
$this->getAutoRemoveKey() => true,
],
];
// For most environments, we know the application root directory is
// '/app'. It's different in Enterprise environments.
if ($environment->deployment_target !== 'local') {
$appRoot = $this->drush->getCachedAppRoot($sshUrl);
if ($appRoot) {
$alias['root'] = rtrim($appRoot, '/') . '/' . $app->getDocumentRoot();
}
} else {
$alias['root'] = '/app/' . $app->getDocumentRoot();
}
list($alias['user'], $alias['host']) = explode('@', $sshUrl, 2);
if ($url = $this->getUrl($environment)) {
$alias['uri'] = $url;
}
return $alias;
} | [
"protected",
"function",
"generateRemoteAlias",
"(",
"Environment",
"$",
"environment",
",",
"LocalApplication",
"$",
"app",
")",
"{",
"if",
"(",
"!",
"$",
"environment",
"->",
"hasLink",
"(",
"'ssh'",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"sshU... | Generate a remote Drush alias.
@param Environment $environment
@param LocalApplication $app
@return array|false | [
"Generate",
"a",
"remote",
"Drush",
"alias",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SiteAlias/DrushAlias.php#L237-L269 |
platformsh/platformsh-cli | src/SiteAlias/DrushAlias.php | DrushAlias.getUrl | private function getUrl(Environment $environment)
{
$urls = $environment->getRouteUrls();
usort($urls, function ($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;
});
return reset($urls);
} | php | private function getUrl(Environment $environment)
{
$urls = $environment->getRouteUrls();
usort($urls, function ($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;
});
return reset($urls);
} | [
"private",
"function",
"getUrl",
"(",
"Environment",
"$",
"environment",
")",
"{",
"$",
"urls",
"=",
"$",
"environment",
"->",
"getRouteUrls",
"(",
")",
";",
"usort",
"(",
"$",
"urls",
",",
"function",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"$",
"... | Find a single URL for an environment.
Only one URL may be used for the Drush site alias. This picks the
shortest one available, strongly preferring HTTPS.
@param \Platformsh\Client\Model\Environment $environment
@return string|false A URL, or false if no URLs are found. | [
"Find",
"a",
"single",
"URL",
"for",
"an",
"environment",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SiteAlias/DrushAlias.php#L281-L297 |
platformsh/platformsh-cli | src/SiteAlias/DrushAlias.php | DrushAlias.deleteAliases | public function deleteAliases($group)
{
$filename = $this->getFilename($group);
if (file_exists($filename)) {
unlink($filename);
}
} | php | public function deleteAliases($group)
{
$filename = $this->getFilename($group);
if (file_exists($filename)) {
unlink($filename);
}
} | [
"public",
"function",
"deleteAliases",
"(",
"$",
"group",
")",
"{",
"$",
"filename",
"=",
"$",
"this",
"->",
"getFilename",
"(",
"$",
"group",
")",
";",
"if",
"(",
"file_exists",
"(",
"$",
"filename",
")",
")",
"{",
"unlink",
"(",
"$",
"filename",
")... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SiteAlias/DrushAlias.php#L320-L326 |
platformsh/platformsh-cli | src/SiteAlias/DrushAlias.php | DrushAlias.swapKeys | protected function swapKeys(array $aliases, array $map)
{
return array_map(function ($alias) use ($map) {
foreach ($map as $from => $to) {
if (isset($alias[$from])) {
$alias[$to] = $alias[$from];
unset($alias[$from]);
}
}
return $alias;
}, $aliases);
} | php | protected function swapKeys(array $aliases, array $map)
{
return array_map(function ($alias) use ($map) {
foreach ($map as $from => $to) {
if (isset($alias[$from])) {
$alias[$to] = $alias[$from];
unset($alias[$from]);
}
}
return $alias;
}, $aliases);
} | [
"protected",
"function",
"swapKeys",
"(",
"array",
"$",
"aliases",
",",
"array",
"$",
"map",
")",
"{",
"return",
"array_map",
"(",
"function",
"(",
"$",
"alias",
")",
"use",
"(",
"$",
"map",
")",
"{",
"foreach",
"(",
"$",
"map",
"as",
"$",
"from",
... | Swap the key names in an array of aliases.
@param array $aliases
@param array $map
@return array | [
"Swap",
"the",
"key",
"names",
"in",
"an",
"array",
"of",
"aliases",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SiteAlias/DrushAlias.php#L336-L348 |
platformsh/platformsh-cli | src/Command/App/AppConfigGetCommand.php | AppConfigGetCommand.configure | protected function configure()
{
$this
->setName('app:config-get')
->setDescription('View the configuration of an app')
->addOption('property', 'P', InputOption::VALUE_REQUIRED, 'The configuration property to view')
->addOption('refresh', null, InputOption::VALUE_NONE, 'Whether to refresh the cache');
$this->addProjectOption();
$this->addEnvironmentOption();
$this->addAppOption();
$this->addOption('identity-file', 'i', InputOption::VALUE_REQUIRED, '[Deprecated option, no longer used]');
} | php | protected function configure()
{
$this
->setName('app:config-get')
->setDescription('View the configuration of an app')
->addOption('property', 'P', InputOption::VALUE_REQUIRED, 'The configuration property to view')
->addOption('refresh', null, InputOption::VALUE_NONE, 'Whether to refresh the cache');
$this->addProjectOption();
$this->addEnvironmentOption();
$this->addAppOption();
$this->addOption('identity-file', 'i', InputOption::VALUE_REQUIRED, '[Deprecated option, no longer used]');
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'app:config-get'",
")",
"->",
"setDescription",
"(",
"'View the configuration of an app'",
")",
"->",
"addOption",
"(",
"'property'",
",",
"'P'",
",",
"InputOption",
"::",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/App/AppConfigGetCommand.php#L14-L25 |
platformsh/platformsh-cli | src/Command/App/AppConfigGetCommand.php | AppConfigGetCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$this->warnAboutDeprecatedOptions(['identity-file']);
$appConfig = $this->api()
->getCurrentDeployment($this->getSelectedEnvironment(), $input->getOption('refresh'))
->getWebApp($this->selectApp($input))
->getProperties();
/** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */
$formatter = $this->getService('property_formatter');
$formatter->displayData($output, $appConfig, $input->getOption('property'));
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$this->warnAboutDeprecatedOptions(['identity-file']);
$appConfig = $this->api()
->getCurrentDeployment($this->getSelectedEnvironment(), $input->getOption('refresh'))
->getWebApp($this->selectApp($input))
->getProperties();
/** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */
$formatter = $this->getService('property_formatter');
$formatter->displayData($output, $appConfig, $input->getOption('property'));
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"validateInput",
"(",
"$",
"input",
")",
";",
"$",
"this",
"->",
"warnAboutDeprecatedOptions",
"(",
"[",
"'identity-fil... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/App/AppConfigGetCommand.php#L30-L43 |
platformsh/platformsh-cli | src/Service/Git.php | Git.getVersion | protected function getVersion()
{
static $version;
if (!$version) {
$version = false;
$string = $this->execute(['--version'], false);
if ($string && preg_match('/(^| )([0-9]+[^ ]*)/', $string, $matches)) {
$version = $matches[2];
}
}
return $version;
} | php | protected function getVersion()
{
static $version;
if (!$version) {
$version = false;
$string = $this->execute(['--version'], false);
if ($string && preg_match('/(^| )([0-9]+[^ ]*)/', $string, $matches)) {
$version = $matches[2];
}
}
return $version;
} | [
"protected",
"function",
"getVersion",
"(",
")",
"{",
"static",
"$",
"version",
";",
"if",
"(",
"!",
"$",
"version",
")",
"{",
"$",
"version",
"=",
"false",
";",
"$",
"string",
"=",
"$",
"this",
"->",
"execute",
"(",
"[",
"'--version'",
"]",
",",
"... | Get the installed version of the Git CLI.
@return string|false
The version number, or false on failure. | [
"Get",
"the",
"installed",
"version",
"of",
"the",
"Git",
"CLI",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L41-L53 |
platformsh/platformsh-cli | src/Service/Git.php | Git.getCurrentBranch | public function getCurrentBranch($dir = null, $mustRun = false)
{
$args = ['symbolic-ref', '--short', 'HEAD'];
return $this->execute($args, $dir, $mustRun);
} | php | public function getCurrentBranch($dir = null, $mustRun = false)
{
$args = ['symbolic-ref', '--short', 'HEAD'];
return $this->execute($args, $dir, $mustRun);
} | [
"public",
"function",
"getCurrentBranch",
"(",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
")",
"{",
"$",
"args",
"=",
"[",
"'symbolic-ref'",
",",
"'--short'",
",",
"'HEAD'",
"]",
";",
"return",
"$",
"this",
"->",
"execute",
"(",
"$",
... | Get the current branch name.
@param string $dir
The path to a Git repository.
@param bool $mustRun
Enable exceptions if the Git command fails.
@return string|false | [
"Get",
"the",
"current",
"branch",
"name",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L90-L95 |
platformsh/platformsh-cli | src/Service/Git.php | Git.getMergedBranches | public function getMergedBranches($ref = 'HEAD', $remote = false, $dir = null, $mustRun = false)
{
$args = ['branch', '--list', '--no-column', '--no-color', '--merged', $ref];
if ($remote) {
$args[] = '--remote';
}
$mergedBranches = $this->execute($args, $dir, $mustRun);
$array = array_map(
function ($element) {
return trim($element, ' *');
},
explode("\n", $mergedBranches)
);
return $array;
} | php | public function getMergedBranches($ref = 'HEAD', $remote = false, $dir = null, $mustRun = false)
{
$args = ['branch', '--list', '--no-column', '--no-color', '--merged', $ref];
if ($remote) {
$args[] = '--remote';
}
$mergedBranches = $this->execute($args, $dir, $mustRun);
$array = array_map(
function ($element) {
return trim($element, ' *');
},
explode("\n", $mergedBranches)
);
return $array;
} | [
"public",
"function",
"getMergedBranches",
"(",
"$",
"ref",
"=",
"'HEAD'",
",",
"$",
"remote",
"=",
"false",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
")",
"{",
"$",
"args",
"=",
"[",
"'branch'",
",",
"'--list'",
",",
"'--no-co... | Get a list of branches merged with a specific ref.
@param string $ref
@param bool $remote
@param null $dir
@param bool $mustRun
@return string[] | [
"Get",
"a",
"list",
"of",
"branches",
"merged",
"with",
"a",
"specific",
"ref",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L107-L122 |
platformsh/platformsh-cli | src/Service/Git.php | Git.execute | public function execute(array $args, $dir = null, $mustRun = false, $quiet = true, array $env = [])
{
// If enabled, set the working directory to the repository.
if ($dir !== false) {
$dir = $dir ?: $this->repositoryDir;
}
// Run the command.
array_unshift($args, 'git');
return $this->shellHelper->execute($args, $dir, $mustRun, $quiet, $env + $this->env);
} | php | public function execute(array $args, $dir = null, $mustRun = false, $quiet = true, array $env = [])
{
// If enabled, set the working directory to the repository.
if ($dir !== false) {
$dir = $dir ?: $this->repositoryDir;
}
// Run the command.
array_unshift($args, 'git');
return $this->shellHelper->execute($args, $dir, $mustRun, $quiet, $env + $this->env);
} | [
"public",
"function",
"execute",
"(",
"array",
"$",
"args",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
",",
"$",
"quiet",
"=",
"true",
",",
"array",
"$",
"env",
"=",
"[",
"]",
")",
"{",
"// If enabled, set the working directory to t... | Execute a Git command.
@param string[] $args
Command arguments (everything after 'git').
@param string|false|null $dir
The path to a Git repository. Set to false if the command should not
run inside a repository. Set to null to use the default repository.
@param bool $mustRun
Enable exceptions if the Git command fails.
@param bool $quiet
Suppress command output.
@param array $env
@throws \Symfony\Component\Process\Exception\RuntimeException
If the command fails and $mustRun is enabled.
@return string|bool
The command output, true if there is no output, or false if the command
fails. | [
"Execute",
"a",
"Git",
"command",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L145-L155 |
platformsh/platformsh-cli | src/Service/Git.php | Git.init | public function init($dir, $mustRun = false)
{
if (is_dir($dir . '/.git')) {
throw new \InvalidArgumentException("Already a repository: $dir");
}
return (bool) $this->execute(['init'], $dir, $mustRun, false);
} | php | public function init($dir, $mustRun = false)
{
if (is_dir($dir . '/.git')) {
throw new \InvalidArgumentException("Already a repository: $dir");
}
return (bool) $this->execute(['init'], $dir, $mustRun, false);
} | [
"public",
"function",
"init",
"(",
"$",
"dir",
",",
"$",
"mustRun",
"=",
"false",
")",
"{",
"if",
"(",
"is_dir",
"(",
"$",
"dir",
".",
"'/.git'",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Already a repository: $dir\"",
")",
... | Create a Git repository in a directory.
@param string $dir
@param bool $mustRun
Enable exceptions if the Git command fails.
@return bool | [
"Create",
"a",
"Git",
"repository",
"in",
"a",
"directory",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L166-L173 |
platformsh/platformsh-cli | src/Service/Git.php | Git.remoteRefExists | public function remoteRefExists($url, $ref = null, $heads = true)
{
$args = ['ls-remote', $url];
if ($heads) {
$args[] = '--heads';
}
if ($ref !== null) {
$args[] = $ref;
}
$result = $this->execute($args, false, true);
return !is_bool($result) && strlen($result) > 0;
} | php | public function remoteRefExists($url, $ref = null, $heads = true)
{
$args = ['ls-remote', $url];
if ($heads) {
$args[] = '--heads';
}
if ($ref !== null) {
$args[] = $ref;
}
$result = $this->execute($args, false, true);
return !is_bool($result) && strlen($result) > 0;
} | [
"public",
"function",
"remoteRefExists",
"(",
"$",
"url",
",",
"$",
"ref",
"=",
"null",
",",
"$",
"heads",
"=",
"true",
")",
"{",
"$",
"args",
"=",
"[",
"'ls-remote'",
",",
"$",
"url",
"]",
";",
"if",
"(",
"$",
"heads",
")",
"{",
"$",
"args",
"... | Check whether a remote repository exists.
@param string $url
@param string $ref
@param bool $heads Whether to limit to heads only.
@throws \Symfony\Component\Process\Exception\RuntimeException
If the Git command fails.
@return bool | [
"Check",
"whether",
"a",
"remote",
"repository",
"exists",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L187-L199 |
platformsh/platformsh-cli | src/Service/Git.php | Git.branchExists | public function branchExists($branchName, $dir = null, $mustRun = false)
{
// The porcelain command 'git branch' is less strict about character
// encoding than (otherwise simpler) plumbing commands such as
// 'git show-ref'.
$result = $this->execute(['branch', '--list', '--no-color', '--no-column'], $dir, $mustRun);
$branches = array_map(function ($line) {
return trim(ltrim($line, '* '));
}, explode("\n", $result));
return in_array($branchName, $branches, true);
} | php | public function branchExists($branchName, $dir = null, $mustRun = false)
{
// The porcelain command 'git branch' is less strict about character
// encoding than (otherwise simpler) plumbing commands such as
// 'git show-ref'.
$result = $this->execute(['branch', '--list', '--no-color', '--no-column'], $dir, $mustRun);
$branches = array_map(function ($line) {
return trim(ltrim($line, '* '));
}, explode("\n", $result));
return in_array($branchName, $branches, true);
} | [
"public",
"function",
"branchExists",
"(",
"$",
"branchName",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
")",
"{",
"// The porcelain command 'git branch' is less strict about character",
"// encoding than (otherwise simpler) plumbing commands such as",
"... | Check whether a branch exists.
@param string $branchName
The branch name.
@param string $dir
The path to a Git repository.
@param bool $mustRun
Enable exceptions if the Git command fails.
@return bool | [
"Check",
"whether",
"a",
"branch",
"exists",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L213-L224 |
platformsh/platformsh-cli | src/Service/Git.php | Git.remoteBranchExists | public function remoteBranchExists($remote, $branchName, $dir = null, $mustRun = false)
{
$args = ['ls-remote', $remote, $branchName];
$result = $this->execute($args, $dir, $mustRun);
return is_string($result) && strlen(trim($result));
} | php | public function remoteBranchExists($remote, $branchName, $dir = null, $mustRun = false)
{
$args = ['ls-remote', $remote, $branchName];
$result = $this->execute($args, $dir, $mustRun);
return is_string($result) && strlen(trim($result));
} | [
"public",
"function",
"remoteBranchExists",
"(",
"$",
"remote",
",",
"$",
"branchName",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
")",
"{",
"$",
"args",
"=",
"[",
"'ls-remote'",
",",
"$",
"remote",
",",
"$",
"branchName",
"]",
... | Check whether a branch exists on a remote.
@param string $remote
@param string $branchName
@param null $dir
@param bool $mustRun
@return bool | [
"Check",
"whether",
"a",
"branch",
"exists",
"on",
"a",
"remote",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L236-L242 |
platformsh/platformsh-cli | src/Service/Git.php | Git.checkOutNew | public function checkOutNew($name, $parent = null, $upstream = null, $dir = null, $mustRun = false)
{
$args = ['checkout', '-b', $name];
if ($parent !== null) {
$args[] = $parent;
} elseif ($upstream !== null) {
$args[] = '--track';
$args[] = $upstream;
}
return (bool) $this->execute($args, $dir, $mustRun, false);
} | php | public function checkOutNew($name, $parent = null, $upstream = null, $dir = null, $mustRun = false)
{
$args = ['checkout', '-b', $name];
if ($parent !== null) {
$args[] = $parent;
} elseif ($upstream !== null) {
$args[] = '--track';
$args[] = $upstream;
}
return (bool) $this->execute($args, $dir, $mustRun, false);
} | [
"public",
"function",
"checkOutNew",
"(",
"$",
"name",
",",
"$",
"parent",
"=",
"null",
",",
"$",
"upstream",
"=",
"null",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
")",
"{",
"$",
"args",
"=",
"[",
"'checkout'",
",",
"'-b'",
... | Create a new branch and check it out.
@param string $name
@param string|null $parent
@param string|null $upstream
@param string|null $dir The path to a Git repository.
@param bool $mustRun Enable exceptions if the Git command fails.
@return bool | [
"Create",
"a",
"new",
"branch",
"and",
"check",
"it",
"out",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L255-L266 |
platformsh/platformsh-cli | src/Service/Git.php | Git.fetch | public function fetch($remote, $branch = null, $dir = null, $mustRun = false)
{
$args = ['fetch', $remote];
if ($branch !== null) {
$args[] = $branch;
}
return (bool) $this->execute($args, $dir, $mustRun, false);
} | php | public function fetch($remote, $branch = null, $dir = null, $mustRun = false)
{
$args = ['fetch', $remote];
if ($branch !== null) {
$args[] = $branch;
}
return (bool) $this->execute($args, $dir, $mustRun, false);
} | [
"public",
"function",
"fetch",
"(",
"$",
"remote",
",",
"$",
"branch",
"=",
"null",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
")",
"{",
"$",
"args",
"=",
"[",
"'fetch'",
",",
"$",
"remote",
"]",
";",
"if",
"(",
"$",
"bran... | Fetch from the Git remote.
@param string $remote
@param string|null $branch
@param string|null $dir
@param bool $mustRun
@return bool | [
"Fetch",
"from",
"the",
"Git",
"remote",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L278-L286 |
platformsh/platformsh-cli | src/Service/Git.php | Git.checkOut | public function checkOut($name, $dir = null, $mustRun = false, $quiet = false)
{
return (bool) $this->execute([
'checkout',
$name,
], $dir, $mustRun, $quiet);
} | php | public function checkOut($name, $dir = null, $mustRun = false, $quiet = false)
{
return (bool) $this->execute([
'checkout',
$name,
], $dir, $mustRun, $quiet);
} | [
"public",
"function",
"checkOut",
"(",
"$",
"name",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
",",
"$",
"quiet",
"=",
"false",
")",
"{",
"return",
"(",
"bool",
")",
"$",
"this",
"->",
"execute",
"(",
"[",
"'checkout'",
",",
... | Check out a branch.
@param string $name
@param string|null $dir
The path to a Git repository.
@param bool $mustRun
Enable exceptions if the Git command fails.
@param bool $quiet
@return bool | [
"Check",
"out",
"a",
"branch",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L300-L306 |
platformsh/platformsh-cli | src/Service/Git.php | Git.getUpstream | public function getUpstream($branch = null, $dir = null, $mustRun = false)
{
if ($branch === null) {
$args = ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'];
return $this->execute($args, $dir, $mustRun);
}
$remoteName = $this->getConfig("branch.$branch.remote", $dir, $mustRun);
$remoteBranch = $this->getConfig("branch.$branch.merge", $dir, $mustRun);
if (empty($remoteName) || empty($remoteBranch)) {
return false;
}
return $remoteName . '/' . str_replace('refs/heads/', '', $remoteBranch);
} | php | public function getUpstream($branch = null, $dir = null, $mustRun = false)
{
if ($branch === null) {
$args = ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'];
return $this->execute($args, $dir, $mustRun);
}
$remoteName = $this->getConfig("branch.$branch.remote", $dir, $mustRun);
$remoteBranch = $this->getConfig("branch.$branch.merge", $dir, $mustRun);
if (empty($remoteName) || empty($remoteBranch)) {
return false;
}
return $remoteName . '/' . str_replace('refs/heads/', '', $remoteBranch);
} | [
"public",
"function",
"getUpstream",
"(",
"$",
"branch",
"=",
"null",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"branch",
"===",
"null",
")",
"{",
"$",
"args",
"=",
"[",
"'rev-parse'",
",",
"'--abbre... | Get the upstream for a branch.
@param string $branch
The name of the branch to get the upstream for. Defaults to the current
branch.
@param string|null $dir
The path to a Git repository.
@param bool $mustRun
Enable exceptions if the Git command fails.
@return string|false
The upstream, in the form remote/branch, or false if no upstream is
found. | [
"Get",
"the",
"upstream",
"for",
"a",
"branch",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L323-L338 |
platformsh/platformsh-cli | src/Service/Git.php | Git.setUpstream | public function setUpstream($upstream, $branch = null, $dir = null, $mustRun = false)
{
$args = ['branch'];
if ($upstream !== false) {
$args[] = '--set-upstream-to=' . $upstream;
} else {
$args[] = '--unset-upstream';
}
if ($branch !== null) {
$args[] = $branch;
}
return (bool) $this->execute($args, $dir, $mustRun);
} | php | public function setUpstream($upstream, $branch = null, $dir = null, $mustRun = false)
{
$args = ['branch'];
if ($upstream !== false) {
$args[] = '--set-upstream-to=' . $upstream;
} else {
$args[] = '--unset-upstream';
}
if ($branch !== null) {
$args[] = $branch;
}
return (bool) $this->execute($args, $dir, $mustRun);
} | [
"public",
"function",
"setUpstream",
"(",
"$",
"upstream",
",",
"$",
"branch",
"=",
"null",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
")",
"{",
"$",
"args",
"=",
"[",
"'branch'",
"]",
";",
"if",
"(",
"$",
"upstream",
"!==",
... | Set the upstream for the current branch.
@param string|false $upstream
The upstream name, or false to unset the upstream.
@param string|null $branch
The branch to act on (defaults to the current branch).
@param string|null $dir
The path to a Git repository.
@param bool $mustRun
Enable exceptions if the Git command fails.
@return bool | [
"Set",
"the",
"upstream",
"for",
"the",
"current",
"branch",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L354-L367 |
platformsh/platformsh-cli | src/Service/Git.php | Git.cloneRepo | public function cloneRepo($url, $destination = null, array $args = [], $mustRun = false)
{
$args = array_merge(['clone', $url], $args);
if ($destination) {
$args[] = $destination;
}
return (bool) $this->execute($args, false, $mustRun, false);
} | php | public function cloneRepo($url, $destination = null, array $args = [], $mustRun = false)
{
$args = array_merge(['clone', $url], $args);
if ($destination) {
$args[] = $destination;
}
return (bool) $this->execute($args, false, $mustRun, false);
} | [
"public",
"function",
"cloneRepo",
"(",
"$",
"url",
",",
"$",
"destination",
"=",
"null",
",",
"array",
"$",
"args",
"=",
"[",
"]",
",",
"$",
"mustRun",
"=",
"false",
")",
"{",
"$",
"args",
"=",
"array_merge",
"(",
"[",
"'clone'",
",",
"$",
"url",
... | Clone a repository.
A ProcessFailedException will be thrown if the command fails.
@param string $url
The Git repository URL.
@param string $destination
A directory name to clone into.
@param array $args
Extra arguments for the Git command.
@param bool $mustRun
Enable exceptions if the Git command fails.
@return bool | [
"Clone",
"a",
"repository",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L401-L409 |
platformsh/platformsh-cli | src/Service/Git.php | Git.updateSubmodules | public function updateSubmodules($recursive = false, $dir = null, $mustRun = false)
{
$args = ['submodule', 'update', '--init'];
if ($recursive) {
$args[] = '--recursive';
}
return (bool) $this->execute($args, $dir, $mustRun, false);
} | php | public function updateSubmodules($recursive = false, $dir = null, $mustRun = false)
{
$args = ['submodule', 'update', '--init'];
if ($recursive) {
$args[] = '--recursive';
}
return (bool) $this->execute($args, $dir, $mustRun, false);
} | [
"public",
"function",
"updateSubmodules",
"(",
"$",
"recursive",
"=",
"false",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
")",
"{",
"$",
"args",
"=",
"[",
"'submodule'",
",",
"'update'",
",",
"'--init'",
"]",
";",
"if",
"(",
"$"... | Update and/or initialize submodules.
@param bool $recursive
Whether to recurse into nested submodules.
@param string|null $dir
The path to a Git repository.
@param bool $mustRun
Enable exceptions if the Git command fails.
@return bool | [
"Update",
"and",
"/",
"or",
"initialize",
"submodules",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L449-L457 |
platformsh/platformsh-cli | src/Service/Git.php | Git.getConfig | public function getConfig($key, $dir = null, $mustRun = false)
{
$args = ['config', '--get', $key];
return $this->execute($args, $dir, $mustRun);
} | php | public function getConfig($key, $dir = null, $mustRun = false)
{
$args = ['config', '--get', $key];
return $this->execute($args, $dir, $mustRun);
} | [
"public",
"function",
"getConfig",
"(",
"$",
"key",
",",
"$",
"dir",
"=",
"null",
",",
"$",
"mustRun",
"=",
"false",
")",
"{",
"$",
"args",
"=",
"[",
"'config'",
",",
"'--get'",
",",
"$",
"key",
"]",
";",
"return",
"$",
"this",
"->",
"execute",
"... | Read a configuration item.
@param string $key
A Git configuration key.
@param string|null $dir
The path to a Git repository.
@param bool $mustRun
Enable exceptions if the Git command fails.
@return string|false | [
"Read",
"a",
"configuration",
"item",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L471-L476 |
platformsh/platformsh-cli | src/Service/Git.php | Git.setSshCommand | public function setSshCommand($sshCommand)
{
if (empty($sshCommand) || $sshCommand === 'ssh') {
unset($this->env['GIT_SSH_COMMAND'], $this->env['GIT_SSH']);
} elseif (!$this->supportsGitSshCommand()) {
$this->env['GIT_SSH'] = $this->writeSshFile($sshCommand . " \$*\n");
} else {
$this->env['GIT_SSH_COMMAND'] = $sshCommand;
}
} | php | public function setSshCommand($sshCommand)
{
if (empty($sshCommand) || $sshCommand === 'ssh') {
unset($this->env['GIT_SSH_COMMAND'], $this->env['GIT_SSH']);
} elseif (!$this->supportsGitSshCommand()) {
$this->env['GIT_SSH'] = $this->writeSshFile($sshCommand . " \$*\n");
} else {
$this->env['GIT_SSH_COMMAND'] = $sshCommand;
}
} | [
"public",
"function",
"setSshCommand",
"(",
"$",
"sshCommand",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"sshCommand",
")",
"||",
"$",
"sshCommand",
"===",
"'ssh'",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"env",
"[",
"'GIT_SSH_COMMAND'",
"]",
",",
"$"... | Set the SSH command for Git to use.
This will use GIT_SSH_COMMAND if supported, or GIT_SSH (and a temporary
file) otherwise.
@param string|null $sshCommand
The complete SSH command. An empty string or null will use Git's
default. | [
"Set",
"the",
"SSH",
"command",
"for",
"Git",
"to",
"use",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L488-L497 |
platformsh/platformsh-cli | src/Service/Git.php | Git.writeSshFile | public function writeSshFile($sshCommand)
{
$tempDir = sys_get_temp_dir();
$tempFile = tempnam($tempDir, 'cli-git-ssh');
if (!$tempFile) {
throw new \RuntimeException('Failed to create temporary file in: ' . $tempDir);
}
if (!file_put_contents($tempFile, trim($sshCommand) . "\n")) {
throw new \RuntimeException('Failed to write temporary file: ' . $tempFile);
}
if (!chmod($tempFile, 0750)) {
throw new \RuntimeException('Failed to make temporary SSH command file executable: ' . $tempFile);
}
$this->sshCommandFile = $tempFile;
return $tempFile;
} | php | public function writeSshFile($sshCommand)
{
$tempDir = sys_get_temp_dir();
$tempFile = tempnam($tempDir, 'cli-git-ssh');
if (!$tempFile) {
throw new \RuntimeException('Failed to create temporary file in: ' . $tempDir);
}
if (!file_put_contents($tempFile, trim($sshCommand) . "\n")) {
throw new \RuntimeException('Failed to write temporary file: ' . $tempFile);
}
if (!chmod($tempFile, 0750)) {
throw new \RuntimeException('Failed to make temporary SSH command file executable: ' . $tempFile);
}
$this->sshCommandFile = $tempFile;
return $tempFile;
} | [
"public",
"function",
"writeSshFile",
"(",
"$",
"sshCommand",
")",
"{",
"$",
"tempDir",
"=",
"sys_get_temp_dir",
"(",
")",
";",
"$",
"tempFile",
"=",
"tempnam",
"(",
"$",
"tempDir",
",",
"'cli-git-ssh'",
")",
";",
"if",
"(",
"!",
"$",
"tempFile",
")",
... | Write an SSH command to a temporary file to be used with GIT_SSH.
@param string $sshCommand
@return string | [
"Write",
"an",
"SSH",
"command",
"to",
"a",
"temporary",
"file",
"to",
"be",
"used",
"with",
"GIT_SSH",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Git.php#L506-L523 |
platformsh/platformsh-cli | src/Command/Auth/PasswordLoginCommand.php | PasswordLoginCommand.validateUsernameOrEmail | public function validateUsernameOrEmail($username)
{
$username = trim($username);
if (!strlen($username) || (!filter_var($username, FILTER_VALIDATE_EMAIL) && !$this->validateUsername($username))) {
throw new \RuntimeException(
'Please enter a valid email address or username.'
);
}
return $username;
} | php | public function validateUsernameOrEmail($username)
{
$username = trim($username);
if (!strlen($username) || (!filter_var($username, FILTER_VALIDATE_EMAIL) && !$this->validateUsername($username))) {
throw new \RuntimeException(
'Please enter a valid email address or username.'
);
}
return $username;
} | [
"public",
"function",
"validateUsernameOrEmail",
"(",
"$",
"username",
")",
"{",
"$",
"username",
"=",
"trim",
"(",
"$",
"username",
")",
";",
"if",
"(",
"!",
"strlen",
"(",
"$",
"username",
")",
"||",
"(",
"!",
"filter_var",
"(",
"$",
"username",
",",... | Validation callback for the username or email address.
@param string $username
@return string | [
"Validation",
"callback",
"for",
"the",
"username",
"or",
"email",
"address",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Auth/PasswordLoginCommand.php#L158-L168 |
platformsh/platformsh-cli | src/Command/Tunnel/TunnelSingleCommand.php | TunnelSingleCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$project = $this->getSelectedProject();
$environment = $this->getSelectedEnvironment();
$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;
}
$service = $relationshipsService->chooseService($sshUrl, $input, $output);
if (!$service) {
return 1;
}
if ($environment->id === 'master') {
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$confirmText = sprintf(
'Are you sure you want to open an SSH tunnel to'
. ' the relationship <comment>%s</comment> on the'
. ' <comment>%s</comment> (production) environment?',
$service['_relationship_name'],
$environment->id
);
if (!$questionHelper->confirm($confirmText, false)) {
return 1;
}
$this->stdErr->writeln('');
}
/** @var \Platformsh\Cli\Service\Ssh $ssh */
$ssh = $this->getService('ssh');
$sshArgs = $ssh->getSshArgs();
$remoteHost = $service['host'];
$remotePort = $service['port'];
if ($localPort = $input->getOption('port')) {
if (!PortUtil::validatePort($localPort)) {
$this->stdErr->writeln(sprintf('Invalid port: <error>%s</error>', $localPort));
return 1;
}
if (PortUtil::isPortInUse($localPort)) {
$this->stdErr->writeln(sprintf('Port already in use: <error>%s</error>', $localPort));
return 1;
}
} else {
$localPort = $this->getPort();
}
$tunnel = [
'projectId' => $project->id,
'environmentId' => $environment->id,
'appName' => $appName,
'relationship' => $service['_relationship_name'],
'serviceKey' => $service['_relationship_key'],
'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 for the relationship <info>%s</info> (on port %s)',
$relationshipString,
$openTunnelInfo['localPort']
));
return 1;
}
$pidFile = $this->getPidFile($tunnel);
$processManager = new ProcessManager();
$process = $this->createTunnelProcess($sshUrl, $remoteHost, $remotePort, $localPort, $sshArgs);
$pid = $processManager->startProcess($process, $pidFile, $this->stdErr);
// 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);
return 1;
}
$tunnel['pid'] = $pid;
$this->tunnelInfo[] = $tunnel;
$this->saveTunnelInfo();
$this->stdErr->writeln('');
$this->stdErr->writeln(sprintf(
'SSH tunnel opened on port %s to relationship: <info>%s</info>',
$tunnel['localPort'],
$relationshipString
));
$localService = array_merge($service, array_intersect_key([
'host' => self::LOCAL_IP,
'port' => $tunnel['localPort'],
], $service));
$info = [
'username' => 'Username',
'password' => 'Password',
'scheme' => 'Scheme',
'host' => 'Host',
'port' => 'Port',
'path' => 'Path',
];
foreach ($info as $key => $category) {
if (isset($localService[$key])) {
$this->stdErr->writeln(sprintf(' <info>%s</info>: %s', $category, $localService[$key]));
}
}
$this->stdErr->writeln('');
if (isset($localService['scheme']) && in_array($localService['scheme'], ['http', 'https'], true)) {
$this->stdErr->writeln(sprintf('URL: <info>%s</info>', $this->getServiceUrl($localService)));
$this->stdErr->writeln('');
}
$this->stdErr->writeln('Quitting this command (with Ctrl+C or equivalent) will close the tunnel.');
$this->stdErr->writeln('');
$processManager->monitor($this->stdErr);
return $process->isSuccessful() ? 0 : 1;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$project = $this->getSelectedProject();
$environment = $this->getSelectedEnvironment();
$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;
}
$service = $relationshipsService->chooseService($sshUrl, $input, $output);
if (!$service) {
return 1;
}
if ($environment->id === 'master') {
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$confirmText = sprintf(
'Are you sure you want to open an SSH tunnel to'
. ' the relationship <comment>%s</comment> on the'
. ' <comment>%s</comment> (production) environment?',
$service['_relationship_name'],
$environment->id
);
if (!$questionHelper->confirm($confirmText, false)) {
return 1;
}
$this->stdErr->writeln('');
}
/** @var \Platformsh\Cli\Service\Ssh $ssh */
$ssh = $this->getService('ssh');
$sshArgs = $ssh->getSshArgs();
$remoteHost = $service['host'];
$remotePort = $service['port'];
if ($localPort = $input->getOption('port')) {
if (!PortUtil::validatePort($localPort)) {
$this->stdErr->writeln(sprintf('Invalid port: <error>%s</error>', $localPort));
return 1;
}
if (PortUtil::isPortInUse($localPort)) {
$this->stdErr->writeln(sprintf('Port already in use: <error>%s</error>', $localPort));
return 1;
}
} else {
$localPort = $this->getPort();
}
$tunnel = [
'projectId' => $project->id,
'environmentId' => $environment->id,
'appName' => $appName,
'relationship' => $service['_relationship_name'],
'serviceKey' => $service['_relationship_key'],
'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 for the relationship <info>%s</info> (on port %s)',
$relationshipString,
$openTunnelInfo['localPort']
));
return 1;
}
$pidFile = $this->getPidFile($tunnel);
$processManager = new ProcessManager();
$process = $this->createTunnelProcess($sshUrl, $remoteHost, $remotePort, $localPort, $sshArgs);
$pid = $processManager->startProcess($process, $pidFile, $this->stdErr);
// 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);
return 1;
}
$tunnel['pid'] = $pid;
$this->tunnelInfo[] = $tunnel;
$this->saveTunnelInfo();
$this->stdErr->writeln('');
$this->stdErr->writeln(sprintf(
'SSH tunnel opened on port %s to relationship: <info>%s</info>',
$tunnel['localPort'],
$relationshipString
));
$localService = array_merge($service, array_intersect_key([
'host' => self::LOCAL_IP,
'port' => $tunnel['localPort'],
], $service));
$info = [
'username' => 'Username',
'password' => 'Password',
'scheme' => 'Scheme',
'host' => 'Host',
'port' => 'Port',
'path' => 'Path',
];
foreach ($info as $key => $category) {
if (isset($localService[$key])) {
$this->stdErr->writeln(sprintf(' <info>%s</info>: %s', $category, $localService[$key]));
}
}
$this->stdErr->writeln('');
if (isset($localService['scheme']) && in_array($localService['scheme'], ['http', 'https'], true)) {
$this->stdErr->writeln(sprintf('URL: <info>%s</info>', $this->getServiceUrl($localService)));
$this->stdErr->writeln('');
}
$this->stdErr->writeln('Quitting this command (with Ctrl+C or equivalent) will close the tunnel.');
$this->stdErr->writeln('');
$processManager->monitor($this->stdErr);
return $process->isSuccessful() ? 0 : 1;
} | [
"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/Tunnel/TunnelSingleCommand.php#L34-L182 |
platformsh/platformsh-cli | src/Command/Tunnel/TunnelSingleCommand.php | TunnelSingleCommand.getServiceUrl | private function getServiceUrl(array $service)
{
$map = ['username' => 'user', 'password' => 'pass'];
$urlParts = [];
foreach ($service as $key => $value) {
$newKey = isset($map[$key]) ? $map[$key] : $key;
$urlParts[$newKey] = $value;
}
return Url::buildUrl($urlParts);
} | php | private function getServiceUrl(array $service)
{
$map = ['username' => 'user', 'password' => 'pass'];
$urlParts = [];
foreach ($service as $key => $value) {
$newKey = isset($map[$key]) ? $map[$key] : $key;
$urlParts[$newKey] = $value;
}
return Url::buildUrl($urlParts);
} | [
"private",
"function",
"getServiceUrl",
"(",
"array",
"$",
"service",
")",
"{",
"$",
"map",
"=",
"[",
"'username'",
"=>",
"'user'",
",",
"'password'",
"=>",
"'pass'",
"]",
";",
"$",
"urlParts",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"service",
"as",
... | Build a URL to a service.
@param array $service
@return string | [
"Build",
"a",
"URL",
"to",
"a",
"service",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Tunnel/TunnelSingleCommand.php#L191-L201 |
platformsh/platformsh-cli | src/Command/App/AppListCommand.php | AppListCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
// Find a list of deployed web apps.
$deployment = $this->api()
->getCurrentDeployment($this->getSelectedEnvironment(), $input->getOption('refresh'));
$apps = $deployment->webapps;
if (!count($apps)) {
$this->stdErr->writeln('No applications found.');
if ($deployment->services) {
$this->stdErr->writeln('');
$this->stdErr->writeln(sprintf(
'To list services, run: <info>%s services</info>',
$this->config()->get('application.executable')
));
}
return 0;
}
// Determine whether to show the "Local path" of the app. This will be
// found via matching the remote, deployed app with one in the local
// project.
// @todo The "Local path" column is mainly here for legacy reasons, and can be removed in a future version.
$showLocalPath = false;
$localApps = [];
if (($projectRoot = $this->getProjectRoot()) && $this->selectedProjectIsCurrent()) {
$localApps = LocalApplication::getApplications($projectRoot, $this->config());
$showLocalPath = true;
}
// Get the local path for a given application.
$getLocalPath = function ($appName) use ($localApps) {
foreach ($localApps as $localApp) {
if ($localApp->getName() === $appName) {
return $localApp->getRoot();
break;
}
}
return '';
};
$headers = ['Name', 'Type', 'disk' => 'Disk (MiB)', 'Size'];
$defaultColumns = ['name', 'type'];
if ($showLocalPath) {
$headers['path'] = 'Path';
$defaultColumns[] = 'Path';
}
$rows = [];
foreach ($apps as $app) {
$row = [$app->name, $app->type, 'disk' => $app->disk, $app->size];
if ($showLocalPath) {
$row['path'] = $getLocalPath($app->name);
}
$rows[] = $row;
}
/** @var \Platformsh\Cli\Service\Table $table */
$table = $this->getService('table');
if (!$table->formatIsMachineReadable()) {
$this->stdErr->writeln(sprintf(
'Applications on the project <info>%s</info>, environment <info>%s</info>:',
$this->api()->getProjectLabel($this->getSelectedProject()),
$this->api()->getEnvironmentLabel($this->getSelectedEnvironment())
));
}
$table->render($rows, $headers, $defaultColumns);
if (!$table->formatIsMachineReadable() && $deployment->services) {
$this->stdErr->writeln('');
$this->stdErr->writeln(sprintf(
'To list services, run: <info>%s services</info>',
$this->config()->get('application.executable')
));
}
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
// Find a list of deployed web apps.
$deployment = $this->api()
->getCurrentDeployment($this->getSelectedEnvironment(), $input->getOption('refresh'));
$apps = $deployment->webapps;
if (!count($apps)) {
$this->stdErr->writeln('No applications found.');
if ($deployment->services) {
$this->stdErr->writeln('');
$this->stdErr->writeln(sprintf(
'To list services, run: <info>%s services</info>',
$this->config()->get('application.executable')
));
}
return 0;
}
// Determine whether to show the "Local path" of the app. This will be
// found via matching the remote, deployed app with one in the local
// project.
// @todo The "Local path" column is mainly here for legacy reasons, and can be removed in a future version.
$showLocalPath = false;
$localApps = [];
if (($projectRoot = $this->getProjectRoot()) && $this->selectedProjectIsCurrent()) {
$localApps = LocalApplication::getApplications($projectRoot, $this->config());
$showLocalPath = true;
}
// Get the local path for a given application.
$getLocalPath = function ($appName) use ($localApps) {
foreach ($localApps as $localApp) {
if ($localApp->getName() === $appName) {
return $localApp->getRoot();
break;
}
}
return '';
};
$headers = ['Name', 'Type', 'disk' => 'Disk (MiB)', 'Size'];
$defaultColumns = ['name', 'type'];
if ($showLocalPath) {
$headers['path'] = 'Path';
$defaultColumns[] = 'Path';
}
$rows = [];
foreach ($apps as $app) {
$row = [$app->name, $app->type, 'disk' => $app->disk, $app->size];
if ($showLocalPath) {
$row['path'] = $getLocalPath($app->name);
}
$rows[] = $row;
}
/** @var \Platformsh\Cli\Service\Table $table */
$table = $this->getService('table');
if (!$table->formatIsMachineReadable()) {
$this->stdErr->writeln(sprintf(
'Applications on the project <info>%s</info>, environment <info>%s</info>:',
$this->api()->getProjectLabel($this->getSelectedProject()),
$this->api()->getEnvironmentLabel($this->getSelectedEnvironment())
));
}
$table->render($rows, $headers, $defaultColumns);
if (!$table->formatIsMachineReadable() && $deployment->services) {
$this->stdErr->writeln('');
$this->stdErr->writeln(sprintf(
'To list services, run: <info>%s services</info>',
$this->config()->get('application.executable')
));
}
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"validateInput",
"(",
"$",
"input",
")",
";",
"// Find a list of deployed web apps.",
"$",
"deployment",
"=",
"$",
"this"... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/App/AppListCommand.php#L31-L113 |
platformsh/platformsh-cli | src/Local/DependencyManager/Pip.php | Pip.install | public function install($path, array $dependencies, $global = false)
{
file_put_contents($path . '/requirements.txt', $this->formatRequirementsTxt($dependencies));
$command = 'pip install --requirement=requirements.txt';
if (!$global) {
$command .= ' --prefix=.';
}
$this->runCommand($command, $path);
} | php | public function install($path, array $dependencies, $global = false)
{
file_put_contents($path . '/requirements.txt', $this->formatRequirementsTxt($dependencies));
$command = 'pip install --requirement=requirements.txt';
if (!$global) {
$command .= ' --prefix=.';
}
$this->runCommand($command, $path);
} | [
"public",
"function",
"install",
"(",
"$",
"path",
",",
"array",
"$",
"dependencies",
",",
"$",
"global",
"=",
"false",
")",
"{",
"file_put_contents",
"(",
"$",
"path",
".",
"'/requirements.txt'",
",",
"$",
"this",
"->",
"formatRequirementsTxt",
"(",
"$",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyManager/Pip.php#L28-L36 |
platformsh/platformsh-cli | src/Local/DependencyManager/Pip.php | Pip.getEnvVars | public function getEnvVars($path)
{
$envVars = [];
// The PYTHONPATH needs to be set as something like
// "lib/python2.7/site-packages". So here we are scanning "lib" to find
// the correct subdirectory.
if (file_exists($path . '/lib')) {
$subdirectories = scandir($path . '/lib') ?: [];
foreach ($subdirectories as $subdirectory) {
if (strpos($subdirectory, '.') !== 0) {
$envVars['PYTHONPATH'] = $path . '/lib/' . $subdirectory . '/site-packages';
break;
}
}
}
return $envVars;
} | php | public function getEnvVars($path)
{
$envVars = [];
// The PYTHONPATH needs to be set as something like
// "lib/python2.7/site-packages". So here we are scanning "lib" to find
// the correct subdirectory.
if (file_exists($path . '/lib')) {
$subdirectories = scandir($path . '/lib') ?: [];
foreach ($subdirectories as $subdirectory) {
if (strpos($subdirectory, '.') !== 0) {
$envVars['PYTHONPATH'] = $path . '/lib/' . $subdirectory . '/site-packages';
break;
}
}
}
return $envVars;
} | [
"public",
"function",
"getEnvVars",
"(",
"$",
"path",
")",
"{",
"$",
"envVars",
"=",
"[",
"]",
";",
"// The PYTHONPATH needs to be set as something like",
"// \"lib/python2.7/site-packages\". So here we are scanning \"lib\" to find",
"// the correct subdirectory.",
"if",
"(",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyManager/Pip.php#L41-L59 |
platformsh/platformsh-cli | src/Local/DependencyManager/Pip.php | Pip.formatRequirementsTxt | private function formatRequirementsTxt(array $dependencies)
{
$lines = [];
foreach ($dependencies as $package => $version) {
if (in_array($version[0], ['<', '!', '>', '='])) {
$lines[] = sprintf('%s%s', $package, $version);
} elseif ($version === '*') {
$lines[] = $package;
} else {
$lines[] = sprintf('%s==%s', $package, $version);
}
}
return implode("\n", $lines);
} | php | private function formatRequirementsTxt(array $dependencies)
{
$lines = [];
foreach ($dependencies as $package => $version) {
if (in_array($version[0], ['<', '!', '>', '='])) {
$lines[] = sprintf('%s%s', $package, $version);
} elseif ($version === '*') {
$lines[] = $package;
} else {
$lines[] = sprintf('%s==%s', $package, $version);
}
}
return implode("\n", $lines);
} | [
"private",
"function",
"formatRequirementsTxt",
"(",
"array",
"$",
"dependencies",
")",
"{",
"$",
"lines",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"dependencies",
"as",
"$",
"package",
"=>",
"$",
"version",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"... | @param array $dependencies
@return string | [
"@param",
"array",
"$dependencies"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyManager/Pip.php#L66-L80 |
platformsh/platformsh-cli | src/Command/Integration/IntegrationUpdateCommand.php | IntegrationUpdateCommand.configure | protected function configure()
{
$this
->setName('integration:update')
->addArgument('id', InputArgument::REQUIRED, 'The ID of the integration to update')
->setDescription('Update an integration');
$this->getForm()->configureInputDefinition($this->getDefinition());
$this->addProjectOption()->addWaitOptions();
$this->addExample(
'Switch on the "fetch branches" option for a specific integration',
'ZXhhbXBsZSB --fetch-branches 1'
);
} | php | protected function configure()
{
$this
->setName('integration:update')
->addArgument('id', InputArgument::REQUIRED, 'The ID of the integration to update')
->setDescription('Update an integration');
$this->getForm()->configureInputDefinition($this->getDefinition());
$this->addProjectOption()->addWaitOptions();
$this->addExample(
'Switch on the "fetch branches" option for a specific integration',
'ZXhhbXBsZSB --fetch-branches 1'
);
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'integration:update'",
")",
"->",
"addArgument",
"(",
"'id'",
",",
"InputArgument",
"::",
"REQUIRED",
",",
"'The ID of the integration to update'",
")",
"->",
"setDescription",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Integration/IntegrationUpdateCommand.php#L15-L27 |
platformsh/platformsh-cli | src/Command/Integration/IntegrationUpdateCommand.php | IntegrationUpdateCommand.valuesAreEqual | private function valuesAreEqual($a, $b)
{
if (is_array($a) && is_array($b)) {
ksort($a);
ksort($b);
}
return $a === $b;
} | php | private function valuesAreEqual($a, $b)
{
if (is_array($a) && is_array($b)) {
ksort($a);
ksort($b);
}
return $a === $b;
} | [
"private",
"function",
"valuesAreEqual",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"a",
")",
"&&",
"is_array",
"(",
"$",
"b",
")",
")",
"{",
"ksort",
"(",
"$",
"a",
")",
";",
"ksort",
"(",
"$",
"b",
")",
";",
... | Compare new and old integration values.
@param mixed $a
@param mixed $b
@return bool
True if the values are considered the same, false otherwise. | [
"Compare",
"new",
"and",
"old",
"integration",
"values",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Integration/IntegrationUpdateCommand.php#L127-L135 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.setRelativeLinks | public function setRelativeLinks($relative = true)
{
// This is not possible on Windows.
if (OsUtil::isWindows()) {
$relative = false;
}
$this->relative = $relative;
} | php | public function setRelativeLinks($relative = true)
{
// This is not possible on Windows.
if (OsUtil::isWindows()) {
$relative = false;
}
$this->relative = $relative;
} | [
"public",
"function",
"setRelativeLinks",
"(",
"$",
"relative",
"=",
"true",
")",
"{",
"// This is not possible on Windows.",
"if",
"(",
"OsUtil",
"::",
"isWindows",
"(",
")",
")",
"{",
"$",
"relative",
"=",
"false",
";",
"}",
"$",
"this",
"->",
"relative",
... | Set whether to use relative links.
@param bool $relative | [
"Set",
"whether",
"to",
"use",
"relative",
"links",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L47-L54 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.remove | public function remove($files, $retryWithChmod = false)
{
try {
$this->fs->remove($files);
} catch (IOException $e) {
if ($retryWithChmod && $this->unprotect($files, true)) {
return $this->remove($files, false);
}
trigger_error($e->getMessage(), E_USER_WARNING);
return false;
}
return true;
} | php | public function remove($files, $retryWithChmod = false)
{
try {
$this->fs->remove($files);
} catch (IOException $e) {
if ($retryWithChmod && $this->unprotect($files, true)) {
return $this->remove($files, false);
}
trigger_error($e->getMessage(), E_USER_WARNING);
return false;
}
return true;
} | [
"public",
"function",
"remove",
"(",
"$",
"files",
",",
"$",
"retryWithChmod",
"=",
"false",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"fs",
"->",
"remove",
"(",
"$",
"files",
")",
";",
"}",
"catch",
"(",
"IOException",
"$",
"e",
")",
"{",
"if",
"... | Delete a file or directory.
@param string|array|\Traversable $files
A filename, an array of files, or a \Traversable instance to delete.
@param bool $retryWithChmod
Whether to retry deleting on error, after recursively changing file
modes to add read/write/exec permissions. A bit like 'rm -rf'.
@return bool | [
"Delete",
"a",
"file",
"or",
"directory",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L67-L81 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.unprotect | protected function unprotect($files, $recursive = false)
{
if (!$files instanceof \Traversable) {
$files = new \ArrayObject(is_array($files) ? $files : array($files));
}
foreach ($files as $file) {
if (is_link($file)) {
continue;
} elseif (is_dir($file)) {
if ((!is_executable($file) || !is_writable($file))
&& true !== @chmod($file, 0700)) {
return false;
}
if ($recursive && !$this->unprotect(new \FilesystemIterator($file), true)) {
return false;
}
} elseif (!is_writable($file) && true !== @chmod($file, 0600)) {
return false;
}
}
return true;
} | php | protected function unprotect($files, $recursive = false)
{
if (!$files instanceof \Traversable) {
$files = new \ArrayObject(is_array($files) ? $files : array($files));
}
foreach ($files as $file) {
if (is_link($file)) {
continue;
} elseif (is_dir($file)) {
if ((!is_executable($file) || !is_writable($file))
&& true !== @chmod($file, 0700)) {
return false;
}
if ($recursive && !$this->unprotect(new \FilesystemIterator($file), true)) {
return false;
}
} elseif (!is_writable($file) && true !== @chmod($file, 0600)) {
return false;
}
}
return true;
} | [
"protected",
"function",
"unprotect",
"(",
"$",
"files",
",",
"$",
"recursive",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"files",
"instanceof",
"\\",
"Traversable",
")",
"{",
"$",
"files",
"=",
"new",
"\\",
"ArrayObject",
"(",
"is_array",
"(",
"$",... | Make files writable by the current user.
@param string|array|\Traversable $files
A filename, an array of files, or a \Traversable instance.
@param bool $recursive
Whether to change the mode recursively or not.
@return bool
True on success, false on failure. | [
"Make",
"files",
"writable",
"by",
"the",
"current",
"user",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L94-L117 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.copy | public function copy($source, $destination, $override = false)
{
if (is_dir($destination) && !is_dir($source)) {
$destination = rtrim($destination, '/') . '/' . basename($source);
}
$this->fs->copy($source, $destination, $override);
} | php | public function copy($source, $destination, $override = false)
{
if (is_dir($destination) && !is_dir($source)) {
$destination = rtrim($destination, '/') . '/' . basename($source);
}
$this->fs->copy($source, $destination, $override);
} | [
"public",
"function",
"copy",
"(",
"$",
"source",
",",
"$",
"destination",
",",
"$",
"override",
"=",
"false",
")",
"{",
"if",
"(",
"is_dir",
"(",
"$",
"destination",
")",
"&&",
"!",
"is_dir",
"(",
"$",
"source",
")",
")",
"{",
"$",
"destination",
... | Copy a file, if it is newer than the destination.
@param string $source
@param string $destination
@param bool $override | [
"Copy",
"a",
"file",
"if",
"it",
"is",
"newer",
"than",
"the",
"destination",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L155-L161 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.copyAll | public function copyAll($source, $destination, array $skip = ['.git', '.DS_Store'], $override = false)
{
if (is_dir($source) && !is_dir($destination)) {
if (!mkdir($destination, 0755, true)) {
throw new \RuntimeException("Failed to create directory: " . $destination);
}
}
if (is_dir($source)) {
// Prevent infinite recursion when the destination is inside the
// source.
if (strpos($destination, $source) === 0) {
$relative = str_replace($source, '', $destination);
$parts = explode('/', ltrim($relative, '/'), 2);
$skip[] = $parts[0];
}
$sourceDirectory = opendir($source);
while ($file = readdir($sourceDirectory)) {
// Skip symlinks, '.' and '..', and files in $skip.
if ($file === '.'
|| $file === '..'
|| $this->inBlacklist($file, $skip)
|| is_link($source . '/' . $file)) {
continue;
}
// Recurse into directories.
if (is_dir($source . '/' . $file)) {
$this->copyAll($source . '/' . $file, $destination . '/' . $file, $skip, $override);
continue;
}
// Perform the copy.
if (is_file($source . '/' . $file)) {
$this->fs->copy($source . '/' . $file, $destination . '/' . $file, $override);
}
}
closedir($sourceDirectory);
} else {
$this->fs->copy($source, $destination, $override);
}
} | php | public function copyAll($source, $destination, array $skip = ['.git', '.DS_Store'], $override = false)
{
if (is_dir($source) && !is_dir($destination)) {
if (!mkdir($destination, 0755, true)) {
throw new \RuntimeException("Failed to create directory: " . $destination);
}
}
if (is_dir($source)) {
// Prevent infinite recursion when the destination is inside the
// source.
if (strpos($destination, $source) === 0) {
$relative = str_replace($source, '', $destination);
$parts = explode('/', ltrim($relative, '/'), 2);
$skip[] = $parts[0];
}
$sourceDirectory = opendir($source);
while ($file = readdir($sourceDirectory)) {
// Skip symlinks, '.' and '..', and files in $skip.
if ($file === '.'
|| $file === '..'
|| $this->inBlacklist($file, $skip)
|| is_link($source . '/' . $file)) {
continue;
}
// Recurse into directories.
if (is_dir($source . '/' . $file)) {
$this->copyAll($source . '/' . $file, $destination . '/' . $file, $skip, $override);
continue;
}
// Perform the copy.
if (is_file($source . '/' . $file)) {
$this->fs->copy($source . '/' . $file, $destination . '/' . $file, $override);
}
}
closedir($sourceDirectory);
} else {
$this->fs->copy($source, $destination, $override);
}
} | [
"public",
"function",
"copyAll",
"(",
"$",
"source",
",",
"$",
"destination",
",",
"array",
"$",
"skip",
"=",
"[",
"'.git'",
",",
"'.DS_Store'",
"]",
",",
"$",
"override",
"=",
"false",
")",
"{",
"if",
"(",
"is_dir",
"(",
"$",
"source",
")",
"&&",
... | Copy all files and folders between directories.
@param string $source
@param string $destination
@param array $skip
@param bool $override | [
"Copy",
"all",
"files",
"and",
"folders",
"between",
"directories",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L171-L213 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.symlink | public function symlink($target, $link)
{
if (!file_exists($target)) {
throw new \InvalidArgumentException('Target not found: ' . $target);
}
if ($this->relative) {
$target = $this->makePathRelative($target, dirname($link));
}
$this->fs->symlink($target, $link, $this->copyOnWindows);
} | php | public function symlink($target, $link)
{
if (!file_exists($target)) {
throw new \InvalidArgumentException('Target not found: ' . $target);
}
if ($this->relative) {
$target = $this->makePathRelative($target, dirname($link));
}
$this->fs->symlink($target, $link, $this->copyOnWindows);
} | [
"public",
"function",
"symlink",
"(",
"$",
"target",
",",
"$",
"link",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"target",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Target not found: '",
".",
"$",
"target",
")",
";"... | Create a symbolic link to a file or directory.
@param string $target The target to link to (must already exist).
@param string $link The name of the symbolic link. | [
"Create",
"a",
"symbolic",
"link",
"to",
"a",
"file",
"or",
"directory",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L221-L230 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.makePathRelative | public function makePathRelative($path, $reference)
{
$path = realpath($path) ?: $path;
$reference = realpath($reference) ?: $reference;
return rtrim($this->fs->makePathRelative($path, $reference), DIRECTORY_SEPARATOR);
} | php | public function makePathRelative($path, $reference)
{
$path = realpath($path) ?: $path;
$reference = realpath($reference) ?: $reference;
return rtrim($this->fs->makePathRelative($path, $reference), DIRECTORY_SEPARATOR);
} | [
"public",
"function",
"makePathRelative",
"(",
"$",
"path",
",",
"$",
"reference",
")",
"{",
"$",
"path",
"=",
"realpath",
"(",
"$",
"path",
")",
"?",
":",
"$",
"path",
";",
"$",
"reference",
"=",
"realpath",
"(",
"$",
"reference",
")",
"?",
":",
"... | Wraps Symfony Filesystem's makePathRelative() with enhancements.
This ensures both parts of the path are realpaths, if possible, before
calculating the relative path. It also trims trailing slashes.
@param string $path An absolute path.
@param string $reference The path to which it will be made relative.
@see SymfonyFilesystem::makePathRelative()
@return string
The $path, relative to the $reference. | [
"Wraps",
"Symfony",
"Filesystem",
"s",
"makePathRelative",
"()",
"with",
"enhancements",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L246-L252 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.formatPathForDisplay | public function formatPathForDisplay($path)
{
$relative = $this->makePathRelative($path, getcwd());
if (strpos($relative, '../..') === false && strlen($relative) < strlen($path)) {
return $relative;
}
return rtrim(trim($path), '/');
} | php | public function formatPathForDisplay($path)
{
$relative = $this->makePathRelative($path, getcwd());
if (strpos($relative, '../..') === false && strlen($relative) < strlen($path)) {
return $relative;
}
return rtrim(trim($path), '/');
} | [
"public",
"function",
"formatPathForDisplay",
"(",
"$",
"path",
")",
"{",
"$",
"relative",
"=",
"$",
"this",
"->",
"makePathRelative",
"(",
"$",
"path",
",",
"getcwd",
"(",
")",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"relative",
",",
"'../..'",
")",
... | Format a path for display (use the relative path if it's simpler).
@param string $path
@return string | [
"Format",
"a",
"path",
"for",
"display",
"(",
"use",
"the",
"relative",
"path",
"if",
"it",
"s",
"simpler",
")",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L261-L269 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.inBlacklist | protected function inBlacklist($filename, array $blacklist)
{
foreach ($blacklist as $pattern) {
if (fnmatch($pattern, $filename, FNM_PATHNAME | FNM_CASEFOLD)) {
return true;
}
}
return false;
} | php | protected function inBlacklist($filename, array $blacklist)
{
foreach ($blacklist as $pattern) {
if (fnmatch($pattern, $filename, FNM_PATHNAME | FNM_CASEFOLD)) {
return true;
}
}
return false;
} | [
"protected",
"function",
"inBlacklist",
"(",
"$",
"filename",
",",
"array",
"$",
"blacklist",
")",
"{",
"foreach",
"(",
"$",
"blacklist",
"as",
"$",
"pattern",
")",
"{",
"if",
"(",
"fnmatch",
"(",
"$",
"pattern",
",",
"$",
"filename",
",",
"FNM_PATHNAME"... | Check if a filename is in the blacklist.
@param string $filename
@param string[] $blacklist
@return bool | [
"Check",
"if",
"a",
"filename",
"is",
"in",
"the",
"blacklist",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L279-L288 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.symlinkAll | public function symlinkAll(
$source,
$destination,
$skipExisting = true,
$recursive = false,
$blacklist = [],
$copy = false
) {
if (!is_dir($destination)) {
mkdir($destination);
}
// The symlink won't work if $source is a relative path.
$source = realpath($source);
// Files to always skip.
$skip = ['.git', '.DS_Store'];
$skip = array_merge($skip, $blacklist);
$sourceDirectory = opendir($source);
while ($file = readdir($sourceDirectory)) {
// Skip symlinks, '.' and '..', and files in $skip.
if ($file === '.' || $file === '..' || $this->inBlacklist($file, $skip) || is_link($source . '/' . $file)) {
continue;
}
$sourceFile = $source . '/' . $file;
$linkFile = $destination . '/' . $file;
if ($recursive && !is_link($linkFile) && is_dir($linkFile) && is_dir($sourceFile)) {
$this->symlinkAll($sourceFile, $linkFile, $skipExisting, $recursive, $blacklist, $copy);
continue;
} elseif (file_exists($linkFile)) {
if ($skipExisting) {
continue;
} else {
throw new \Exception('File exists: ' . $linkFile);
}
} elseif (is_link($linkFile)) {
// This is a broken link. Remove it.
$this->remove($linkFile);
}
if ($copy) {
$this->copyAll($sourceFile, $linkFile, $blacklist);
} else {
$this->symlink($sourceFile, $linkFile);
}
}
closedir($sourceDirectory);
} | php | public function symlinkAll(
$source,
$destination,
$skipExisting = true,
$recursive = false,
$blacklist = [],
$copy = false
) {
if (!is_dir($destination)) {
mkdir($destination);
}
// The symlink won't work if $source is a relative path.
$source = realpath($source);
// Files to always skip.
$skip = ['.git', '.DS_Store'];
$skip = array_merge($skip, $blacklist);
$sourceDirectory = opendir($source);
while ($file = readdir($sourceDirectory)) {
// Skip symlinks, '.' and '..', and files in $skip.
if ($file === '.' || $file === '..' || $this->inBlacklist($file, $skip) || is_link($source . '/' . $file)) {
continue;
}
$sourceFile = $source . '/' . $file;
$linkFile = $destination . '/' . $file;
if ($recursive && !is_link($linkFile) && is_dir($linkFile) && is_dir($sourceFile)) {
$this->symlinkAll($sourceFile, $linkFile, $skipExisting, $recursive, $blacklist, $copy);
continue;
} elseif (file_exists($linkFile)) {
if ($skipExisting) {
continue;
} else {
throw new \Exception('File exists: ' . $linkFile);
}
} elseif (is_link($linkFile)) {
// This is a broken link. Remove it.
$this->remove($linkFile);
}
if ($copy) {
$this->copyAll($sourceFile, $linkFile, $blacklist);
} else {
$this->symlink($sourceFile, $linkFile);
}
}
closedir($sourceDirectory);
} | [
"public",
"function",
"symlinkAll",
"(",
"$",
"source",
",",
"$",
"destination",
",",
"$",
"skipExisting",
"=",
"true",
",",
"$",
"recursive",
"=",
"false",
",",
"$",
"blacklist",
"=",
"[",
"]",
",",
"$",
"copy",
"=",
"false",
")",
"{",
"if",
"(",
... | Symlink or copy all files and folders between two directories.
@param string $source
@param string $destination
@param bool $skipExisting
@param bool $recursive
@param string[] $blacklist
@param bool $copy
@throws \Exception When a conflict is discovered. | [
"Symlink",
"or",
"copy",
"all",
"files",
"and",
"folders",
"between",
"two",
"directories",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L302-L351 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.makePathAbsolute | public function makePathAbsolute($relativePath)
{
if (file_exists($relativePath) && !is_link($relativePath) && ($realPath = realpath($relativePath))) {
$absolute = $realPath;
} else {
$parent = dirname($relativePath);
if (!is_dir($parent) || !($parentRealPath = realpath($parent))) {
throw new \InvalidArgumentException('Directory not found: ' . $parent);
}
$basename = basename($relativePath);
$absolute = $basename == '..'
? dirname($parentRealPath)
: rtrim($parentRealPath . '/' . $basename, './');
}
return $absolute;
} | php | public function makePathAbsolute($relativePath)
{
if (file_exists($relativePath) && !is_link($relativePath) && ($realPath = realpath($relativePath))) {
$absolute = $realPath;
} else {
$parent = dirname($relativePath);
if (!is_dir($parent) || !($parentRealPath = realpath($parent))) {
throw new \InvalidArgumentException('Directory not found: ' . $parent);
}
$basename = basename($relativePath);
$absolute = $basename == '..'
? dirname($parentRealPath)
: rtrim($parentRealPath . '/' . $basename, './');
}
return $absolute;
} | [
"public",
"function",
"makePathAbsolute",
"(",
"$",
"relativePath",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"relativePath",
")",
"&&",
"!",
"is_link",
"(",
"$",
"relativePath",
")",
"&&",
"(",
"$",
"realPath",
"=",
"realpath",
"(",
"$",
"relativePath... | Make a relative path into an absolute one.
The realpath() function will only work for existing files, and not for
symlinks. This is a more flexible solution.
@param string $relativePath
@throws \InvalidArgumentException If the parent directory is not found.
@return string | [
"Make",
"a",
"relative",
"path",
"into",
"an",
"absolute",
"one",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L365-L381 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.writeFile | public function writeFile($filename, $contents, $backup = true)
{
$fs = new SymfonyFilesystem();
if (file_exists($filename) && $backup && $contents !== file_get_contents($filename)) {
$backupName = dirname($filename) . '/' . basename($filename) . '.bak';
$fs->rename($filename, $backupName, true);
}
$fs->dumpFile($filename, $contents);
} | php | public function writeFile($filename, $contents, $backup = true)
{
$fs = new SymfonyFilesystem();
if (file_exists($filename) && $backup && $contents !== file_get_contents($filename)) {
$backupName = dirname($filename) . '/' . basename($filename) . '.bak';
$fs->rename($filename, $backupName, true);
}
$fs->dumpFile($filename, $contents);
} | [
"public",
"function",
"writeFile",
"(",
"$",
"filename",
",",
"$",
"contents",
",",
"$",
"backup",
"=",
"true",
")",
"{",
"$",
"fs",
"=",
"new",
"SymfonyFilesystem",
"(",
")",
";",
"if",
"(",
"file_exists",
"(",
"$",
"filename",
")",
"&&",
"$",
"back... | Write a file and create a backup if the contents have changed.
@param string $filename
@param string $contents
@param bool $backup | [
"Write",
"a",
"file",
"and",
"create",
"a",
"backup",
"if",
"the",
"contents",
"have",
"changed",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L414-L422 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.archiveDir | public function archiveDir($dir, $destination)
{
$tar = $this->getTarExecutable();
$dir = $this->fixTarPath($dir);
$destination = $this->fixTarPath($destination);
$this->shell->execute([$tar, '-czp', '-C' . $dir, '-f' . $destination, '.'], null, true);
} | php | public function archiveDir($dir, $destination)
{
$tar = $this->getTarExecutable();
$dir = $this->fixTarPath($dir);
$destination = $this->fixTarPath($destination);
$this->shell->execute([$tar, '-czp', '-C' . $dir, '-f' . $destination, '.'], null, true);
} | [
"public",
"function",
"archiveDir",
"(",
"$",
"dir",
",",
"$",
"destination",
")",
"{",
"$",
"tar",
"=",
"$",
"this",
"->",
"getTarExecutable",
"(",
")",
";",
"$",
"dir",
"=",
"$",
"this",
"->",
"fixTarPath",
"(",
"$",
"dir",
")",
";",
"$",
"destin... | Create a gzipped tar archive of a directory's contents.
@param string $dir
@param string $destination | [
"Create",
"a",
"gzipped",
"tar",
"archive",
"of",
"a",
"directory",
"s",
"contents",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L430-L436 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.extractArchive | public function extractArchive($archive, $destination)
{
if (!file_exists($archive)) {
throw new \InvalidArgumentException("Archive not found: $archive");
}
if (!file_exists($destination) && !mkdir($destination, 0755, true)) {
throw new \InvalidArgumentException("Could not create destination directory: $destination");
}
$tar = $this->getTarExecutable();
$destination = $this->fixTarPath($destination);
$archive = $this->fixTarPath($archive);
$this->shell->execute([$tar, '-xzp', '-C' . $destination, '-f' . $archive], null, true);
} | php | public function extractArchive($archive, $destination)
{
if (!file_exists($archive)) {
throw new \InvalidArgumentException("Archive not found: $archive");
}
if (!file_exists($destination) && !mkdir($destination, 0755, true)) {
throw new \InvalidArgumentException("Could not create destination directory: $destination");
}
$tar = $this->getTarExecutable();
$destination = $this->fixTarPath($destination);
$archive = $this->fixTarPath($archive);
$this->shell->execute([$tar, '-xzp', '-C' . $destination, '-f' . $archive], null, true);
} | [
"public",
"function",
"extractArchive",
"(",
"$",
"archive",
",",
"$",
"destination",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"archive",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Archive not found: $archive\"",
")",
";... | Extract a gzipped tar archive into the specified destination directory.
@param string $archive
@param string $destination | [
"Extract",
"a",
"gzipped",
"tar",
"archive",
"into",
"the",
"specified",
"destination",
"directory",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L444-L456 |
platformsh/platformsh-cli | src/Service/Filesystem.php | Filesystem.fixTarPath | protected function fixTarPath($path)
{
if (OsUtil::isWindows()) {
$path = preg_replace_callback(
'#^([A-Z]):/#i',
function (array $matches) {
return '/' . strtolower($matches[1]) . '/';
},
str_replace('\\', '/', $path)
);
}
return $path;
} | php | protected function fixTarPath($path)
{
if (OsUtil::isWindows()) {
$path = preg_replace_callback(
'#^([A-Z]):/#i',
function (array $matches) {
return '/' . strtolower($matches[1]) . '/';
},
str_replace('\\', '/', $path)
);
}
return $path;
} | [
"protected",
"function",
"fixTarPath",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"OsUtil",
"::",
"isWindows",
"(",
")",
")",
"{",
"$",
"path",
"=",
"preg_replace_callback",
"(",
"'#^([A-Z]):/#i'",
",",
"function",
"(",
"array",
"$",
"matches",
")",
"{",
"re... | Fix a path so that it can be used with tar on Windows.
@see http://betterlogic.com/roger/2009/01/tar-woes-with-windows/
@param string $path
@return string | [
"Fix",
"a",
"path",
"so",
"that",
"it",
"can",
"be",
"used",
"with",
"tar",
"on",
"Windows",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Filesystem.php#L467-L480 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.