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/Command/Self/SelfReleaseCommand.php
SelfReleaseCommand.hasGitDifferences
private function hasGitDifferences($since) { /** @var \Platformsh\Cli\Service\Git $git */ $git = $this->getService('git'); $stat = $git->execute(['diff', '--numstat', $since . '...HEAD'], CLI_ROOT, true); if (!is_string($stat)) { return false; } foreach (explode("\n", trim($stat)) as $line) { // Exclude config.yaml and dist/manifest.json from the check. if (strpos($line, ' config.yaml') === false && strpos($line, ' dist/manifest.json') === false) { return true; } } return false; }
php
private function hasGitDifferences($since) { /** @var \Platformsh\Cli\Service\Git $git */ $git = $this->getService('git'); $stat = $git->execute(['diff', '--numstat', $since . '...HEAD'], CLI_ROOT, true); if (!is_string($stat)) { return false; } foreach (explode("\n", trim($stat)) as $line) { // Exclude config.yaml and dist/manifest.json from the check. if (strpos($line, ' config.yaml') === false && strpos($line, ' dist/manifest.json') === false) { return true; } } return false; }
[ "private", "function", "hasGitDifferences", "(", "$", "since", ")", "{", "/** @var \\Platformsh\\Cli\\Service\\Git $git */", "$", "git", "=", "$", "this", "->", "getService", "(", "'git'", ")", ";", "$", "stat", "=", "$", "git", "->", "execute", "(", "[", "'...
Checks if there are relevant Git differences since the last version. @param string $since @return bool
[ "Checks", "if", "there", "are", "relevant", "Git", "differences", "since", "the", "last", "version", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Self/SelfReleaseCommand.php#L434-L451
platformsh/platformsh-cli
src/Command/Self/SelfReleaseCommand.php
SelfReleaseCommand.getGitChangelog
private function getGitChangelog($since) { /** @var \Platformsh\Cli\Service\Git $git */ $git = $this->getService('git'); $changelog = $git->execute([ 'log', '--pretty=tformat:* %s%n%b', '--no-merges', '--invert-grep', '--grep=(Release v|\[skip changelog\])', '--perl-regexp', '--regexp-ignore-case', $since . '...HEAD' ], CLI_ROOT); if (!is_string($changelog)) { return ''; } $changelog = preg_replace('/^[^\*\n]/m', ' $0', $changelog); $changelog = preg_replace('/\n+\*/', "\n*", $changelog); $changelog = trim($changelog); return $changelog; }
php
private function getGitChangelog($since) { /** @var \Platformsh\Cli\Service\Git $git */ $git = $this->getService('git'); $changelog = $git->execute([ 'log', '--pretty=tformat:* %s%n%b', '--no-merges', '--invert-grep', '--grep=(Release v|\[skip changelog\])', '--perl-regexp', '--regexp-ignore-case', $since . '...HEAD' ], CLI_ROOT); if (!is_string($changelog)) { return ''; } $changelog = preg_replace('/^[^\*\n]/m', ' $0', $changelog); $changelog = preg_replace('/\n+\*/', "\n*", $changelog); $changelog = trim($changelog); return $changelog; }
[ "private", "function", "getGitChangelog", "(", "$", "since", ")", "{", "/** @var \\Platformsh\\Cli\\Service\\Git $git */", "$", "git", "=", "$", "this", "->", "getService", "(", "'git'", ")", ";", "$", "changelog", "=", "$", "git", "->", "execute", "(", "[", ...
@param string $since @return string
[ "@param", "string", "$since" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Self/SelfReleaseCommand.php#L458-L481
platformsh/platformsh-cli
src/Command/Variable/VariableUpdateCommand.php
VariableUpdateCommand.configure
protected function configure() { $this ->setName('variable:update') ->setDescription('Update a variable') ->addArgument('name', InputArgument::REQUIRED, 'The variable name'); $this->addLevelOption(); $fields = $this->getFields(); unset($fields['name'], $fields['prefix'], $fields['environment'], $fields['level']); $this->form = Form::fromArray($fields); $this->form->configureInputDefinition($this->getDefinition()); $this->addProjectOption() ->addEnvironmentOption() ->addWaitOptions(); }
php
protected function configure() { $this ->setName('variable:update') ->setDescription('Update a variable') ->addArgument('name', InputArgument::REQUIRED, 'The variable name'); $this->addLevelOption(); $fields = $this->getFields(); unset($fields['name'], $fields['prefix'], $fields['environment'], $fields['level']); $this->form = Form::fromArray($fields); $this->form->configureInputDefinition($this->getDefinition()); $this->addProjectOption() ->addEnvironmentOption() ->addWaitOptions(); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'variable:update'", ")", "->", "setDescription", "(", "'Update a variable'", ")", "->", "addArgument", "(", "'name'", ",", "InputArgument", "::", "REQUIRED", ",", "'The vari...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Variable/VariableUpdateCommand.php#L18-L32
platformsh/platformsh-cli
src/Local/LocalProject.php
LocalProject.readProjectConfigFile
public function readProjectConfigFile($dir, $configFile) { $result = null; $filename = $dir . '/' . $this->config->get('service.project_config_dir') . '/' . $configFile; if (file_exists($filename)) { $parser = new Parser(); $result = $parser->parse(file_get_contents($filename)); } return $result; }
php
public function readProjectConfigFile($dir, $configFile) { $result = null; $filename = $dir . '/' . $this->config->get('service.project_config_dir') . '/' . $configFile; if (file_exists($filename)) { $parser = new Parser(); $result = $parser->parse(file_get_contents($filename)); } return $result; }
[ "public", "function", "readProjectConfigFile", "(", "$", "dir", ",", "$", "configFile", ")", "{", "$", "result", "=", "null", ";", "$", "filename", "=", "$", "dir", ".", "'/'", ".", "$", "this", "->", "config", "->", "get", "(", "'service.project_config_...
Read a config file for a project. @param string $dir The project root. @param string $configFile A config file such as 'services.yaml'. @return array|null
[ "Read", "a", "config", "file", "for", "a", "project", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalProject.php#L35-L45
platformsh/platformsh-cli
src/Local/LocalProject.php
LocalProject.parseGitUrl
protected function parseGitUrl($gitUrl) { $gitDomain = $this->config->get('detection.git_domain'); $pattern = '/^([a-z0-9]{12,})@git\.(([a-z0-9\-]+\.)?' . preg_quote($gitDomain) . '):\1\.git$/'; if (!preg_match($pattern, $gitUrl, $matches)) { return false; } return ['id' => $matches[1], 'host' => $matches[2]]; }
php
protected function parseGitUrl($gitUrl) { $gitDomain = $this->config->get('detection.git_domain'); $pattern = '/^([a-z0-9]{12,})@git\.(([a-z0-9\-]+\.)?' . preg_quote($gitDomain) . '):\1\.git$/'; if (!preg_match($pattern, $gitUrl, $matches)) { return false; } return ['id' => $matches[1], 'host' => $matches[2]]; }
[ "protected", "function", "parseGitUrl", "(", "$", "gitUrl", ")", "{", "$", "gitDomain", "=", "$", "this", "->", "config", "->", "get", "(", "'detection.git_domain'", ")", ";", "$", "pattern", "=", "'/^([a-z0-9]{12,})@git\\.(([a-z0-9\\-]+\\.)?'", ".", "preg_quote",...
@param string $gitUrl @return array|false An array containing 'id' and 'host', or false on failure.
[ "@param", "string", "$gitUrl" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalProject.php#L53-L62
platformsh/platformsh-cli
src/Local/LocalProject.php
LocalProject.getGitRemoteUrl
protected function getGitRemoteUrl($dir) { $this->git->ensureInstalled(); foreach ([$this->config->get('detection.git_remote_name'), 'origin'] as $remote) { if ($url = $this->git->getConfig("remote.$remote.url", $dir)) { return $url; } } return false; }
php
protected function getGitRemoteUrl($dir) { $this->git->ensureInstalled(); foreach ([$this->config->get('detection.git_remote_name'), 'origin'] as $remote) { if ($url = $this->git->getConfig("remote.$remote.url", $dir)) { return $url; } } return false; }
[ "protected", "function", "getGitRemoteUrl", "(", "$", "dir", ")", "{", "$", "this", "->", "git", "->", "ensureInstalled", "(", ")", ";", "foreach", "(", "[", "$", "this", "->", "config", "->", "get", "(", "'detection.git_remote_name'", ")", ",", "'origin'"...
@param string $dir @throws \RuntimeException If no remote can be found. @return string|false The Git remote URL.
[ "@param", "string", "$dir" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalProject.php#L73-L83
platformsh/platformsh-cli
src/Local/LocalProject.php
LocalProject.ensureGitRemote
public function ensureGitRemote($dir, $url) { if (!file_exists($dir . '/.git')) { throw new \InvalidArgumentException('The directory is not a Git repository'); } $this->git->ensureInstalled(); $currentUrl = $this->git->getConfig( sprintf('remote.%s.url', $this->config->get('detection.git_remote_name')), $dir ); if (!$currentUrl) { $this->git->execute( ['remote', 'add', $this->config->get('detection.git_remote_name'), $url], $dir, true ); } elseif ($currentUrl !== $url) { $this->git->execute([ 'remote', 'set-url', $this->config->get('detection.git_remote_name'), $url ], $dir, true); } }
php
public function ensureGitRemote($dir, $url) { if (!file_exists($dir . '/.git')) { throw new \InvalidArgumentException('The directory is not a Git repository'); } $this->git->ensureInstalled(); $currentUrl = $this->git->getConfig( sprintf('remote.%s.url', $this->config->get('detection.git_remote_name')), $dir ); if (!$currentUrl) { $this->git->execute( ['remote', 'add', $this->config->get('detection.git_remote_name'), $url], $dir, true ); } elseif ($currentUrl !== $url) { $this->git->execute([ 'remote', 'set-url', $this->config->get('detection.git_remote_name'), $url ], $dir, true); } }
[ "public", "function", "ensureGitRemote", "(", "$", "dir", ",", "$", "url", ")", "{", "if", "(", "!", "file_exists", "(", "$", "dir", ".", "'/.git'", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The directory is not a Git repository'"...
Ensure there is an appropriate Git remote in the repository. @param string $dir The repository directory. @param string $url The Git URL.
[ "Ensure", "there", "is", "an", "appropriate", "Git", "remote", "in", "the", "repository", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalProject.php#L93-L117
platformsh/platformsh-cli
src/Local/LocalProject.php
LocalProject.findTopDirectoryContaining
protected static function findTopDirectoryContaining($file, callable $callback = null) { static $roots = []; $cwd = getcwd(); if ($cwd === false) { return false; } if (isset($roots[$cwd][$file])) { return $roots[$cwd][$file]; } $roots[$cwd][$file] = false; $root = &$roots[$cwd][$file]; $currentDir = $cwd; while (!$root) { if (file_exists($currentDir . '/' . $file)) { if ($callback === null || $callback($currentDir)) { $root = $currentDir; break; } } // The file was not found, go one directory up. $levelUp = dirname($currentDir); if ($levelUp === $currentDir || $levelUp === '.') { break; } $currentDir = $levelUp; } return $root; }
php
protected static function findTopDirectoryContaining($file, callable $callback = null) { static $roots = []; $cwd = getcwd(); if ($cwd === false) { return false; } if (isset($roots[$cwd][$file])) { return $roots[$cwd][$file]; } $roots[$cwd][$file] = false; $root = &$roots[$cwd][$file]; $currentDir = $cwd; while (!$root) { if (file_exists($currentDir . '/' . $file)) { if ($callback === null || $callback($currentDir)) { $root = $currentDir; break; } } // The file was not found, go one directory up. $levelUp = dirname($currentDir); if ($levelUp === $currentDir || $levelUp === '.') { break; } $currentDir = $levelUp; } return $root; }
[ "protected", "static", "function", "findTopDirectoryContaining", "(", "$", "file", ",", "callable", "$", "callback", "=", "null", ")", "{", "static", "$", "roots", "=", "[", "]", ";", "$", "cwd", "=", "getcwd", "(", ")", ";", "if", "(", "$", "cwd", "...
Find the highest level directory that contains a file. @param string $file The filename to look for. @param callable $callback A callback to validate the directory when found. Accepts one argument (the directory path). Return true to use the directory, or false to continue traversing upwards. @return string|false The path to the directory, or false if the file is not found.
[ "Find", "the", "highest", "level", "directory", "that", "contains", "a", "file", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalProject.php#L132-L164
platformsh/platformsh-cli
src/Local/LocalProject.php
LocalProject.mapDirectory
public function mapDirectory($directory, Project $project) { if (!file_exists($directory . '/.git')) { throw new \InvalidArgumentException('Not a Git repository: ' . $directory); } $projectConfig = [ 'id' => $project->id, ]; if ($host = parse_url($project->getUri(), PHP_URL_HOST)) { $projectConfig['host'] = $host; } $this->writeCurrentProjectConfig($projectConfig, $directory, true); $this->ensureGitRemote($directory, $project->getGitUrl()); }
php
public function mapDirectory($directory, Project $project) { if (!file_exists($directory . '/.git')) { throw new \InvalidArgumentException('Not a Git repository: ' . $directory); } $projectConfig = [ 'id' => $project->id, ]; if ($host = parse_url($project->getUri(), PHP_URL_HOST)) { $projectConfig['host'] = $host; } $this->writeCurrentProjectConfig($projectConfig, $directory, true); $this->ensureGitRemote($directory, $project->getGitUrl()); }
[ "public", "function", "mapDirectory", "(", "$", "directory", ",", "Project", "$", "project", ")", "{", "if", "(", "!", "file_exists", "(", "$", "directory", ".", "'/.git'", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Not a Git rep...
Initialize a directory as a project root. @param string $directory The Git repository that should be initialized. @param Project $project The project.
[ "Initialize", "a", "directory", "as", "a", "project", "root", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalProject.php#L174-L187
platformsh/platformsh-cli
src/Local/LocalProject.php
LocalProject.getProjectRoot
public function getProjectRoot() { // Backwards compatibility - if in an old-style project root, change // directory to the repository. if (is_dir('repository') && file_exists($this->config->get('local.project_config_legacy'))) { $cwd = getcwd(); chdir('repository'); } // The project root is a Git repository, which contains a project // configuration file, and/or contains a Git remote with the appropriate // domain. $dir = $this->findTopDirectoryContaining('.git', function ($dir) { $config = $this->getProjectConfig($dir); return !empty($config); }); if (isset($cwd)) { chdir($cwd); } return $dir; }
php
public function getProjectRoot() { // Backwards compatibility - if in an old-style project root, change // directory to the repository. if (is_dir('repository') && file_exists($this->config->get('local.project_config_legacy'))) { $cwd = getcwd(); chdir('repository'); } // The project root is a Git repository, which contains a project // configuration file, and/or contains a Git remote with the appropriate // domain. $dir = $this->findTopDirectoryContaining('.git', function ($dir) { $config = $this->getProjectConfig($dir); return !empty($config); }); if (isset($cwd)) { chdir($cwd); } return $dir; }
[ "public", "function", "getProjectRoot", "(", ")", "{", "// Backwards compatibility - if in an old-style project root, change", "// directory to the repository.", "if", "(", "is_dir", "(", "'repository'", ")", "&&", "file_exists", "(", "$", "this", "->", "config", "->", "g...
Find the root of the current project. @return string|false
[ "Find", "the", "root", "of", "the", "current", "project", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalProject.php#L204-L227
platformsh/platformsh-cli
src/Local/LocalProject.php
LocalProject.getProjectConfig
public function getProjectConfig($projectRoot = null) { $projectRoot = $projectRoot ?: $this->getProjectRoot(); if (isset(self::$projectConfigs[$projectRoot])) { return self::$projectConfigs[$projectRoot]; } $projectConfig = null; $configFilename = $this->config->get('local.project_config'); if ($projectRoot && file_exists($projectRoot . '/' . $configFilename)) { $yaml = new Parser(); $projectConfig = $yaml->parse(file_get_contents($projectRoot . '/' . $configFilename)); self::$projectConfigs[$projectRoot] = $projectConfig; } elseif ($projectRoot && is_dir($projectRoot . '/.git')) { $gitUrl = $this->getGitRemoteUrl($projectRoot); if ($gitUrl && ($projectConfig = $this->parseGitUrl($gitUrl))) { $this->writeCurrentProjectConfig($projectConfig, $projectRoot); } } return $projectConfig; }
php
public function getProjectConfig($projectRoot = null) { $projectRoot = $projectRoot ?: $this->getProjectRoot(); if (isset(self::$projectConfigs[$projectRoot])) { return self::$projectConfigs[$projectRoot]; } $projectConfig = null; $configFilename = $this->config->get('local.project_config'); if ($projectRoot && file_exists($projectRoot . '/' . $configFilename)) { $yaml = new Parser(); $projectConfig = $yaml->parse(file_get_contents($projectRoot . '/' . $configFilename)); self::$projectConfigs[$projectRoot] = $projectConfig; } elseif ($projectRoot && is_dir($projectRoot . '/.git')) { $gitUrl = $this->getGitRemoteUrl($projectRoot); if ($gitUrl && ($projectConfig = $this->parseGitUrl($gitUrl))) { $this->writeCurrentProjectConfig($projectConfig, $projectRoot); } } return $projectConfig; }
[ "public", "function", "getProjectConfig", "(", "$", "projectRoot", "=", "null", ")", "{", "$", "projectRoot", "=", "$", "projectRoot", "?", ":", "$", "this", "->", "getProjectRoot", "(", ")", ";", "if", "(", "isset", "(", "self", "::", "$", "projectConfi...
Get the configuration for the current project. @param string|null $projectRoot @return array|null The current project's configuration.
[ "Get", "the", "configuration", "for", "the", "current", "project", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalProject.php#L237-L257
platformsh/platformsh-cli
src/Local/LocalProject.php
LocalProject.writeCurrentProjectConfig
public function writeCurrentProjectConfig(array $config, $projectRoot = null, $merge = false) { $projectRoot = $projectRoot ?: $this->getProjectRoot(); if (!$projectRoot) { throw new \Exception('Project root not found'); } $this->ensureLocalDir($projectRoot); $file = $projectRoot . '/' . $this->config->get('local.project_config'); if ($merge) { $projectConfig = $this->getProjectConfig($projectRoot) ?: []; $config = array_merge($projectConfig, $config); } $yaml = (new Dumper())->dump($config, 10); $this->fs->dumpFile($file, $yaml); self::$projectConfigs[$projectRoot] = $config; return $config; }
php
public function writeCurrentProjectConfig(array $config, $projectRoot = null, $merge = false) { $projectRoot = $projectRoot ?: $this->getProjectRoot(); if (!$projectRoot) { throw new \Exception('Project root not found'); } $this->ensureLocalDir($projectRoot); $file = $projectRoot . '/' . $this->config->get('local.project_config'); if ($merge) { $projectConfig = $this->getProjectConfig($projectRoot) ?: []; $config = array_merge($projectConfig, $config); } $yaml = (new Dumper())->dump($config, 10); $this->fs->dumpFile($file, $yaml); self::$projectConfigs[$projectRoot] = $config; return $config; }
[ "public", "function", "writeCurrentProjectConfig", "(", "array", "$", "config", ",", "$", "projectRoot", "=", "null", ",", "$", "merge", "=", "false", ")", "{", "$", "projectRoot", "=", "$", "projectRoot", "?", ":", "$", "this", "->", "getProjectRoot", "("...
Write configuration for a project. Configuration is stored as YAML, in the location configured by 'local.project_config'. @param array $config The configuration. @param string $projectRoot The project root. @param bool $merge Whether to merge with existing configuration. @throws \Exception On failure @return array The updated project configuration.
[ "Write", "configuration", "for", "a", "project", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalProject.php#L277-L295
platformsh/platformsh-cli
src/Local/LocalProject.php
LocalProject.writeGitExclude
public function writeGitExclude($dir) { $filesToExclude = ['/' . $this->config->get('local.local_dir'), '/' . $this->config->get('local.web_root')]; $excludeFilename = $dir . '/.git/info/exclude'; $existing = ''; // Skip writing anything if the contents already include the // application.name. if (file_exists($excludeFilename)) { $existing = file_get_contents($excludeFilename); if (strpos($existing, $this->config->get('application.name')) !== false) { // Backwards compatibility between versions 3.0.0 and 3.0.2. $newRoot = "\n" . '/' . $this->config->get('application.name') . "\n"; $oldRoot = "\n" . '/.www' . "\n"; if (strpos($existing, $oldRoot) !== false && strpos($existing, $newRoot) === false) { $this->fs->dumpFile($excludeFilename, str_replace($oldRoot, $newRoot, $existing)); } if (is_link($dir . '/.www')) { unlink($dir . '/.www'); } // End backwards compatibility block. return; } } $content = "# Automatically added by the " . $this->config->get('application.name') . "\n" . implode("\n", $filesToExclude) . "\n"; if (!empty($existing)) { $content = $existing . "\n" . $content; } $this->fs->dumpFile($excludeFilename, $content); }
php
public function writeGitExclude($dir) { $filesToExclude = ['/' . $this->config->get('local.local_dir'), '/' . $this->config->get('local.web_root')]; $excludeFilename = $dir . '/.git/info/exclude'; $existing = ''; // Skip writing anything if the contents already include the // application.name. if (file_exists($excludeFilename)) { $existing = file_get_contents($excludeFilename); if (strpos($existing, $this->config->get('application.name')) !== false) { // Backwards compatibility between versions 3.0.0 and 3.0.2. $newRoot = "\n" . '/' . $this->config->get('application.name') . "\n"; $oldRoot = "\n" . '/.www' . "\n"; if (strpos($existing, $oldRoot) !== false && strpos($existing, $newRoot) === false) { $this->fs->dumpFile($excludeFilename, str_replace($oldRoot, $newRoot, $existing)); } if (is_link($dir . '/.www')) { unlink($dir . '/.www'); } // End backwards compatibility block. return; } } $content = "# Automatically added by the " . $this->config->get('application.name') . "\n" . implode("\n", $filesToExclude) . "\n"; if (!empty($existing)) { $content = $existing . "\n" . $content; } $this->fs->dumpFile($excludeFilename, $content); }
[ "public", "function", "writeGitExclude", "(", "$", "dir", ")", "{", "$", "filesToExclude", "=", "[", "'/'", ".", "$", "this", "->", "config", "->", "get", "(", "'local.local_dir'", ")", ",", "'/'", ".", "$", "this", "->", "config", "->", "get", "(", ...
Write to the Git exclude file. @param string $dir
[ "Write", "to", "the", "Git", "exclude", "file", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/LocalProject.php#L333-L366
platformsh/platformsh-cli
src/Service/Ssh.php
Ssh.getSshArgs
public function getSshArgs(array $extraOptions = []) { $options = array_merge($this->getSshOptions(), $extraOptions); $args = []; foreach ($options as $name => $value) { $args[] = '-o'; $args[] = $name . ' ' . $value; } return $args; }
php
public function getSshArgs(array $extraOptions = []) { $options = array_merge($this->getSshOptions(), $extraOptions); $args = []; foreach ($options as $name => $value) { $args[] = '-o'; $args[] = $name . ' ' . $value; } return $args; }
[ "public", "function", "getSshArgs", "(", "array", "$", "extraOptions", "=", "[", "]", ")", "{", "$", "options", "=", "array_merge", "(", "$", "this", "->", "getSshOptions", "(", ")", ",", "$", "extraOptions", ")", ";", "$", "args", "=", "[", "]", ";"...
@param array $extraOptions @return array
[ "@param", "array", "$extraOptions" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Ssh.php#L36-L47
platformsh/platformsh-cli
src/Service/Ssh.php
Ssh.getSshOptions
protected function getSshOptions() { $options = []; $options['SendEnv'] = 'TERM'; if ($this->input->hasOption('identity-file') && $this->input->getOption('identity-file')) { $file = $this->input->getOption('identity-file'); if (!file_exists($file)) { throw new \InvalidArgumentException('Identity file not found: ' . $file); } $options['IdentitiesOnly'] = 'yes'; $options['IdentityFile'] = $file; } if ($this->output->isDebug()) { $options['LogLevel'] = 'DEBUG'; } elseif ($this->output->isVeryVerbose()) { $options['LogLevel'] = 'VERBOSE'; } elseif ($this->output->isQuiet()) { $options['LogLevel'] = 'QUIET'; } return $options; }
php
protected function getSshOptions() { $options = []; $options['SendEnv'] = 'TERM'; if ($this->input->hasOption('identity-file') && $this->input->getOption('identity-file')) { $file = $this->input->getOption('identity-file'); if (!file_exists($file)) { throw new \InvalidArgumentException('Identity file not found: ' . $file); } $options['IdentitiesOnly'] = 'yes'; $options['IdentityFile'] = $file; } if ($this->output->isDebug()) { $options['LogLevel'] = 'DEBUG'; } elseif ($this->output->isVeryVerbose()) { $options['LogLevel'] = 'VERBOSE'; } elseif ($this->output->isQuiet()) { $options['LogLevel'] = 'QUIET'; } return $options; }
[ "protected", "function", "getSshOptions", "(", ")", "{", "$", "options", "=", "[", "]", ";", "$", "options", "[", "'SendEnv'", "]", "=", "'TERM'", ";", "if", "(", "$", "this", "->", "input", "->", "hasOption", "(", "'identity-file'", ")", "&&", "$", ...
Returns an array of SSH options, based on the input options. @return string[] An array of SSH options.
[ "Returns", "an", "array", "of", "SSH", "options", "based", "on", "the", "input", "options", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Ssh.php#L54-L78
platformsh/platformsh-cli
src/Service/Ssh.php
Ssh.getSshCommand
public function getSshCommand(array $extraOptions = []) { $command = 'ssh'; $args = $this->getSshArgs($extraOptions); if (!empty($args)) { $command .= ' ' . implode(' ', array_map('escapeshellarg', $args)); } return $command; }
php
public function getSshCommand(array $extraOptions = []) { $command = 'ssh'; $args = $this->getSshArgs($extraOptions); if (!empty($args)) { $command .= ' ' . implode(' ', array_map('escapeshellarg', $args)); } return $command; }
[ "public", "function", "getSshCommand", "(", "array", "$", "extraOptions", "=", "[", "]", ")", "{", "$", "command", "=", "'ssh'", ";", "$", "args", "=", "$", "this", "->", "getSshArgs", "(", "$", "extraOptions", ")", ";", "if", "(", "!", "empty", "(",...
Returns an SSH command line. @param array $extraOptions @return string
[ "Returns", "an", "SSH", "command", "line", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Ssh.php#L87-L96
platformsh/platformsh-cli
src/Command/Integration/IntegrationCommandBase.php
IntegrationCommandBase.hookNeedsUpdate
private function hookNeedsUpdate(Integration $integration, array $hook, array $payload) { if ($integration->type === 'bitbucket') { foreach ($payload as $item => $value) { if (!isset($hook[$item])) { return true; } if ($item === 'events') { sort($value); sort($hook[$item]); if ($value !== $hook[$item]) { return true; } } if ($hook[$item] !== $value) { return true; } } return false; } return $this->arraysDiffer($hook, $payload); }
php
private function hookNeedsUpdate(Integration $integration, array $hook, array $payload) { if ($integration->type === 'bitbucket') { foreach ($payload as $item => $value) { if (!isset($hook[$item])) { return true; } if ($item === 'events') { sort($value); sort($hook[$item]); if ($value !== $hook[$item]) { return true; } } if ($hook[$item] !== $value) { return true; } } return false; } return $this->arraysDiffer($hook, $payload); }
[ "private", "function", "hookNeedsUpdate", "(", "Integration", "$", "integration", ",", "array", "$", "hook", ",", "array", "$", "payload", ")", "{", "if", "(", "$", "integration", "->", "type", "===", "'bitbucket'", ")", "{", "foreach", "(", "$", "payload"...
Check if a hook needs updating. @param \Platformsh\Client\Model\Integration $integration @param array $hook @param array $payload @return bool
[ "Check", "if", "a", "hook", "needs", "updating", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Integration/IntegrationCommandBase.php#L414-L437
platformsh/platformsh-cli
src/Command/Integration/IntegrationCommandBase.php
IntegrationCommandBase.arraysDiffer
private function arraysDiffer(array $array1, array $array2) { foreach ($array2 as $property => $value) { if (!array_key_exists($property, $array1)) { return true; } if (is_array($value)) { if (!is_array($array1[$property])) { return true; } if ($array1[$property] != $value && $this->arraysDiffer($array1[$property], $value)) { return true; } continue; } if ($array1[$property] != $value) { return true; } } return false; }
php
private function arraysDiffer(array $array1, array $array2) { foreach ($array2 as $property => $value) { if (!array_key_exists($property, $array1)) { return true; } if (is_array($value)) { if (!is_array($array1[$property])) { return true; } if ($array1[$property] != $value && $this->arraysDiffer($array1[$property], $value)) { return true; } continue; } if ($array1[$property] != $value) { return true; } } return false; }
[ "private", "function", "arraysDiffer", "(", "array", "$", "array1", ",", "array", "$", "array2", ")", "{", "foreach", "(", "$", "array2", "as", "$", "property", "=>", "$", "value", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "property", ","...
Checks if $array2 has any values missing or different from $array1. Runs recursively for multidimensional arrays. @param array $array1 @param array $array2 @return bool
[ "Checks", "if", "$array2", "has", "any", "values", "missing", "or", "different", "from", "$array1", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Integration/IntegrationCommandBase.php#L449-L470
platformsh/platformsh-cli
src/Command/Integration/IntegrationCommandBase.php
IntegrationCommandBase.findWebHook
private function findWebHook(Integration $integration, array $jsonResult) { $type = $integration->type; $hookUrl = $integration->getLink('#hook'); if ($integration->type === 'bitbucket') { $hooks = $jsonResult['values']; } else { $hooks = $jsonResult; } foreach ($hooks as $hook) { if ($type === 'github' && $hook['config']['url'] === $hookUrl) { return $hook; } if ($type === 'gitlab' && $hook['url'] === $hookUrl) { return $hook; } if ($type === 'bitbucket' && $hook['url'] === $hookUrl) { return $hook; } } return false; }
php
private function findWebHook(Integration $integration, array $jsonResult) { $type = $integration->type; $hookUrl = $integration->getLink('#hook'); if ($integration->type === 'bitbucket') { $hooks = $jsonResult['values']; } else { $hooks = $jsonResult; } foreach ($hooks as $hook) { if ($type === 'github' && $hook['config']['url'] === $hookUrl) { return $hook; } if ($type === 'gitlab' && $hook['url'] === $hookUrl) { return $hook; } if ($type === 'bitbucket' && $hook['url'] === $hookUrl) { return $hook; } } return false; }
[ "private", "function", "findWebHook", "(", "Integration", "$", "integration", ",", "array", "$", "jsonResult", ")", "{", "$", "type", "=", "$", "integration", "->", "type", ";", "$", "hookUrl", "=", "$", "integration", "->", "getLink", "(", "'#hook'", ")",...
Find if a valid webhook exists in a service's hooks list. @param \Platformsh\Client\Model\Integration $integration @param array $jsonResult @return array|false
[ "Find", "if", "a", "valid", "webhook", "exists", "in", "a", "service", "s", "hooks", "list", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Integration/IntegrationCommandBase.php#L480-L502
platformsh/platformsh-cli
src/Command/Integration/IntegrationCommandBase.php
IntegrationCommandBase.getBitbucketAccessToken
protected function getBitbucketAccessToken(array $credentials) { if (isset($this->bitbucketAccessTokens[$credentials['key']])) { return $this->bitbucketAccessTokens[$credentials['key']]; } $result = $this->api() ->getHttpClient() ->post('https://bitbucket.org/site/oauth2/access_token', [ 'auth' => [$credentials['key'], $credentials['secret']], 'body' => [ 'grant_type' => 'client_credentials', ], ]); $data = $result->json(); if (!isset($data['access_token'])) { throw new \RuntimeException('Access token not found in Bitbucket response'); } $this->bitbucketAccessTokens[$credentials['key']] = $data['access_token']; return $data['access_token']; }
php
protected function getBitbucketAccessToken(array $credentials) { if (isset($this->bitbucketAccessTokens[$credentials['key']])) { return $this->bitbucketAccessTokens[$credentials['key']]; } $result = $this->api() ->getHttpClient() ->post('https://bitbucket.org/site/oauth2/access_token', [ 'auth' => [$credentials['key'], $credentials['secret']], 'body' => [ 'grant_type' => 'client_credentials', ], ]); $data = $result->json(); if (!isset($data['access_token'])) { throw new \RuntimeException('Access token not found in Bitbucket response'); } $this->bitbucketAccessTokens[$credentials['key']] = $data['access_token']; return $data['access_token']; }
[ "protected", "function", "getBitbucketAccessToken", "(", "array", "$", "credentials", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "bitbucketAccessTokens", "[", "$", "credentials", "[", "'key'", "]", "]", ")", ")", "{", "return", "$", "this", "->"...
Obtain an OAuth2 token for Bitbucket from the given app credentials. @param array $credentials @return string
[ "Obtain", "an", "OAuth2", "token", "for", "Bitbucket", "from", "the", "given", "app", "credentials", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Integration/IntegrationCommandBase.php#L532-L554
platformsh/platformsh-cli
src/Command/Integration/IntegrationCommandBase.php
IntegrationCommandBase.validateBitbucketCredentials
protected function validateBitbucketCredentials(array $credentials) { try { $this->getBitbucketAccessToken($credentials); } catch (\Exception $e) { $message = '<error>Invalid Bitbucket credentials</error>'; if ($e instanceof BadResponseException && $e->getResponse() && $e->getResponse()->getStatusCode() === 400) { $message .= "\n" . 'Ensure that the OAuth consumer key and secret are valid.' . "\n" . 'Additionally, ensure that the OAuth consumer has a callback URL set (even just to <comment>http://localhost</comment>).'; } return $message; } return TRUE; }
php
protected function validateBitbucketCredentials(array $credentials) { try { $this->getBitbucketAccessToken($credentials); } catch (\Exception $e) { $message = '<error>Invalid Bitbucket credentials</error>'; if ($e instanceof BadResponseException && $e->getResponse() && $e->getResponse()->getStatusCode() === 400) { $message .= "\n" . 'Ensure that the OAuth consumer key and secret are valid.' . "\n" . 'Additionally, ensure that the OAuth consumer has a callback URL set (even just to <comment>http://localhost</comment>).'; } return $message; } return TRUE; }
[ "protected", "function", "validateBitbucketCredentials", "(", "array", "$", "credentials", ")", "{", "try", "{", "$", "this", "->", "getBitbucketAccessToken", "(", "$", "credentials", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", ...
Validate Bitbucket credentials. @param array $credentials @return string|TRUE
[ "Validate", "Bitbucket", "credentials", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Integration/IntegrationCommandBase.php#L563-L578
platformsh/platformsh-cli
src/Command/Integration/IntegrationCommandBase.php
IntegrationCommandBase.listValidationErrors
protected function listValidationErrors(array $errors, OutputInterface $output) { if (count($errors) === 1) { $this->stdErr->writeln('The following error was found:'); } else { $this->stdErr->writeln(sprintf( 'The following %d errors were found:', count($errors) )); } foreach ($errors as $key => $error) { if (is_string($key) && strlen($key)) { $output->writeln("$key: $error"); } else { $output->writeln($error); } } }
php
protected function listValidationErrors(array $errors, OutputInterface $output) { if (count($errors) === 1) { $this->stdErr->writeln('The following error was found:'); } else { $this->stdErr->writeln(sprintf( 'The following %d errors were found:', count($errors) )); } foreach ($errors as $key => $error) { if (is_string($key) && strlen($key)) { $output->writeln("$key: $error"); } else { $output->writeln($error); } } }
[ "protected", "function", "listValidationErrors", "(", "array", "$", "errors", ",", "OutputInterface", "$", "output", ")", "{", "if", "(", "count", "(", "$", "errors", ")", "===", "1", ")", "{", "$", "this", "->", "stdErr", "->", "writeln", "(", "'The fol...
Lists validation errors found in an integration. @param array $errors @param \Symfony\Component\Console\Output\OutputInterface $output
[ "Lists", "validation", "errors", "found", "in", "an", "integration", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Integration/IntegrationCommandBase.php#L586-L604
platformsh/platformsh-cli
src/Service/ActivityLoader.php
ActivityLoader.load
public function load(Resource $apiResource, $limit, $type, $startsAt) { /** @var \Platformsh\Client\Model\Environment|\Platformsh\Client\Model\Project $apiResource */ $activities = $apiResource->getActivities($limit, $type, $startsAt); $progress = new ProgressBar($this->getProgressOutput()); $progress->setMessage($type === 'environment.backup' ? 'Loading snapshots...' : 'Loading activities...'); $progress->setFormat('%message% %current% (max: %max%)'); $progress->start($limit); while (count($activities) < $limit) { if ($activity = end($activities)) { $startsAt = strtotime($activity->created_at); } $nextActivities = $apiResource->getActivities($limit - count($activities), $type, $startsAt); if (!count($nextActivities)) { break; } foreach ($nextActivities as $activity) { $activities[$activity->id] = $activity; } $progress->setProgress(count($activities)); } $progress->clear(); return $activities; }
php
public function load(Resource $apiResource, $limit, $type, $startsAt) { /** @var \Platformsh\Client\Model\Environment|\Platformsh\Client\Model\Project $apiResource */ $activities = $apiResource->getActivities($limit, $type, $startsAt); $progress = new ProgressBar($this->getProgressOutput()); $progress->setMessage($type === 'environment.backup' ? 'Loading snapshots...' : 'Loading activities...'); $progress->setFormat('%message% %current% (max: %max%)'); $progress->start($limit); while (count($activities) < $limit) { if ($activity = end($activities)) { $startsAt = strtotime($activity->created_at); } $nextActivities = $apiResource->getActivities($limit - count($activities), $type, $startsAt); if (!count($nextActivities)) { break; } foreach ($nextActivities as $activity) { $activities[$activity->id] = $activity; } $progress->setProgress(count($activities)); } $progress->clear(); return $activities; }
[ "public", "function", "load", "(", "Resource", "$", "apiResource", ",", "$", "limit", ",", "$", "type", ",", "$", "startsAt", ")", "{", "/** @var \\Platformsh\\Client\\Model\\Environment|\\Platformsh\\Client\\Model\\Project $apiResource */", "$", "activities", "=", "$", ...
Load activities. @param Resource $apiResource @param int $limit @param string|null $type @param int|null $startsAt @return \Platformsh\Client\Model\Activity[]
[ "Load", "activities", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/ActivityLoader.php#L49-L73
platformsh/platformsh-cli
src/Command/Mount/MountListCommand.php
MountListCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $appConfig = $this->getAppConfig($this->selectApp($input), (bool) $input->getOption('refresh')); if (empty($appConfig['mounts'])) { $this->stdErr->writeln(sprintf('The app "%s" doesn\'t define any mounts.', $appConfig['name'])); return 1; } /** @var \Platformsh\Cli\Service\Mount $mountService */ $mountService = $this->getService('mount'); $mounts = $mountService->normalizeMounts($appConfig['mounts']); if ($input->getOption('paths')) { $output->writeln(array_keys($mounts)); return 0; } $header = ['path' => 'Mount path', 'definition' => 'Definition']; $rows = []; /** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */ $formatter = $this->getService('property_formatter'); foreach ($mounts as $path => $definition) { $rows[] = ['path' => $path, 'definition' => $formatter->format($definition)]; } /** @var \Platformsh\Cli\Service\Table $table */ $table = $this->getService('table'); $this->stdErr->writeln(sprintf('Mounts in the app <info>%s</info> (environment <info>%s</info>):', $appConfig['name'], $this->getSelectedEnvironment()->id)); $table->render($rows, $header); return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $appConfig = $this->getAppConfig($this->selectApp($input), (bool) $input->getOption('refresh')); if (empty($appConfig['mounts'])) { $this->stdErr->writeln(sprintf('The app "%s" doesn\'t define any mounts.', $appConfig['name'])); return 1; } /** @var \Platformsh\Cli\Service\Mount $mountService */ $mountService = $this->getService('mount'); $mounts = $mountService->normalizeMounts($appConfig['mounts']); if ($input->getOption('paths')) { $output->writeln(array_keys($mounts)); return 0; } $header = ['path' => 'Mount path', 'definition' => 'Definition']; $rows = []; /** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */ $formatter = $this->getService('property_formatter'); foreach ($mounts as $path => $definition) { $rows[] = ['path' => $path, 'definition' => $formatter->format($definition)]; } /** @var \Platformsh\Cli\Service\Table $table */ $table = $this->getService('table'); $this->stdErr->writeln(sprintf('Mounts in the app <info>%s</info> (environment <info>%s</info>):', $appConfig['name'], $this->getSelectedEnvironment()->id)); $table->render($rows, $header); return 0; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "validateInput", "(", "$", "input", ")", ";", "$", "appConfig", "=", "$", "this", "->", "getAppConfig", "(", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Mount/MountListCommand.php#L33-L68
platformsh/platformsh-cli
src/Service/QuestionHelper.php
QuestionHelper.confirm
public function confirm($questionText, $default = true) { $questionText .= ' <question>' . ($default ? '[Y/n]' : '[y/N]') . '</question> '; $yes = $this->input->hasOption('yes') && $this->input->getOption('yes'); $no = $this->input->hasOption('no') && $this->input->getOption('no'); if ($yes && !$no) { $this->output->writeln($questionText . 'y'); return true; } elseif ($no && !$yes) { $this->output->writeln($questionText . 'n'); return false; } elseif (!$this->input->isInteractive()) { $this->output->writeln($questionText . ($default ? 'y' : 'n')); return $default; } $question = new ConfirmationQuestion($questionText, $default); return $this->ask($this->input, $this->output, $question); }
php
public function confirm($questionText, $default = true) { $questionText .= ' <question>' . ($default ? '[Y/n]' : '[y/N]') . '</question> '; $yes = $this->input->hasOption('yes') && $this->input->getOption('yes'); $no = $this->input->hasOption('no') && $this->input->getOption('no'); if ($yes && !$no) { $this->output->writeln($questionText . 'y'); return true; } elseif ($no && !$yes) { $this->output->writeln($questionText . 'n'); return false; } elseif (!$this->input->isInteractive()) { $this->output->writeln($questionText . ($default ? 'y' : 'n')); return $default; } $question = new ConfirmationQuestion($questionText, $default); return $this->ask($this->input, $this->output, $question); }
[ "public", "function", "confirm", "(", "$", "questionText", ",", "$", "default", "=", "true", ")", "{", "$", "questionText", ".=", "' <question>'", ".", "(", "$", "default", "?", "'[Y/n]'", ":", "'[y/N]'", ")", ".", "'</question> '", ";", "$", "yes", "=",...
Ask the user to confirm an action. @param string $questionText @param bool $default @return bool
[ "Ask", "the", "user", "to", "confirm", "an", "action", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/QuestionHelper.php#L47-L66
platformsh/platformsh-cli
src/Service/QuestionHelper.php
QuestionHelper.choose
public function choose(array $items, $text = 'Enter a number to choose an item:', $default = null, $skipOnOne = true) { if (count($items) === 1 && $skipOnOne) { return key($items); } $itemList = array_values($items); $defaultKey = $default !== null ? array_search($default, $itemList, true) : null; $question = new ChoiceQuestion($text, $itemList, $defaultKey); $question->setMaxAttempts(5); if (!$this->input->isInteractive()) { if (!isset($defaultKey)) { return null; } $choice = $itemList[$defaultKey]; $choiceKey = array_search($choice, $items, true); if ($choiceKey === false) { throw new \RuntimeException('Invalid default'); } return $choiceKey; } $choice = $this->ask($this->input, $this->output, $question); $choiceKey = array_search($choice, $items, true); if ($choiceKey === false) { throw new \RuntimeException("Invalid value: $choice"); } $this->output->writeln(''); return $choiceKey; }
php
public function choose(array $items, $text = 'Enter a number to choose an item:', $default = null, $skipOnOne = true) { if (count($items) === 1 && $skipOnOne) { return key($items); } $itemList = array_values($items); $defaultKey = $default !== null ? array_search($default, $itemList, true) : null; $question = new ChoiceQuestion($text, $itemList, $defaultKey); $question->setMaxAttempts(5); if (!$this->input->isInteractive()) { if (!isset($defaultKey)) { return null; } $choice = $itemList[$defaultKey]; $choiceKey = array_search($choice, $items, true); if ($choiceKey === false) { throw new \RuntimeException('Invalid default'); } return $choiceKey; } $choice = $this->ask($this->input, $this->output, $question); $choiceKey = array_search($choice, $items, true); if ($choiceKey === false) { throw new \RuntimeException("Invalid value: $choice"); } $this->output->writeln(''); return $choiceKey; }
[ "public", "function", "choose", "(", "array", "$", "items", ",", "$", "text", "=", "'Enter a number to choose an item:'", ",", "$", "default", "=", "null", ",", "$", "skipOnOne", "=", "true", ")", "{", "if", "(", "count", "(", "$", "items", ")", "===", ...
Provides an interactive choice question. @param array $items An associative array of choices. @param string $text Some text to precede the choices. @param mixed $default A default (as a key in $items). @param bool $skipOnOne Whether to skip the choice if there is only one item. @throws \RuntimeException on failure @return mixed The chosen item (as a key in $items).
[ "Provides", "an", "interactive", "choice", "question", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/QuestionHelper.php#L82-L114
platformsh/platformsh-cli
src/Service/QuestionHelper.php
QuestionHelper.askInput
public function askInput($questionText, $default = null, array $autoCompleterValues = [], callable $validator = null) { if ($default !== null) { $questionText .= ' <question>[' . $default . ']</question>'; } $questionText .= ': '; $question = new Question($questionText, $default); if (!empty($autoCompleterValues)) { $question->setAutocompleterValues($autoCompleterValues); } if ($validator !== null) { $question->setValidator($validator); $question->setMaxAttempts(5); } return $this->ask($this->input, $this->output, $question); }
php
public function askInput($questionText, $default = null, array $autoCompleterValues = [], callable $validator = null) { if ($default !== null) { $questionText .= ' <question>[' . $default . ']</question>'; } $questionText .= ': '; $question = new Question($questionText, $default); if (!empty($autoCompleterValues)) { $question->setAutocompleterValues($autoCompleterValues); } if ($validator !== null) { $question->setValidator($validator); $question->setMaxAttempts(5); } return $this->ask($this->input, $this->output, $question); }
[ "public", "function", "askInput", "(", "$", "questionText", ",", "$", "default", "=", "null", ",", "array", "$", "autoCompleterValues", "=", "[", "]", ",", "callable", "$", "validator", "=", "null", ")", "{", "if", "(", "$", "default", "!==", "null", "...
Ask a simple question which requires input. @param string $questionText @param mixed $default @param array $autoCompleterValues @param callable $validator @return string The user's answer.
[ "Ask", "a", "simple", "question", "which", "requires", "input", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/QuestionHelper.php#L127-L143
platformsh/platformsh-cli
src/Command/CompletionCommand.php
CompletionCommand.getEnvironmentsForCheckout
public function getEnvironmentsForCheckout() { $project = $this->getWelcomeCommand()->getCurrentProject(); if (!$project) { return []; } try { $currentEnvironment = $this->getWelcomeCommand()->getCurrentEnvironment($project, false); } catch (\Exception $e) { $currentEnvironment = false; } $environments = $this->api->getEnvironments($project, false, false); if ($currentEnvironment) { $environments = array_filter( $environments, function ($environment) use ($currentEnvironment) { return $environment->id !== $currentEnvironment->id; } ); } return array_keys($environments); }
php
public function getEnvironmentsForCheckout() { $project = $this->getWelcomeCommand()->getCurrentProject(); if (!$project) { return []; } try { $currentEnvironment = $this->getWelcomeCommand()->getCurrentEnvironment($project, false); } catch (\Exception $e) { $currentEnvironment = false; } $environments = $this->api->getEnvironments($project, false, false); if ($currentEnvironment) { $environments = array_filter( $environments, function ($environment) use ($currentEnvironment) { return $environment->id !== $currentEnvironment->id; } ); } return array_keys($environments); }
[ "public", "function", "getEnvironmentsForCheckout", "(", ")", "{", "$", "project", "=", "$", "this", "->", "getWelcomeCommand", "(", ")", "->", "getCurrentProject", "(", ")", ";", "if", "(", "!", "$", "project", ")", "{", "return", "[", "]", ";", "}", ...
Get a list of environments IDs that can be checked out. @return string[]
[ "Get", "a", "list", "of", "environments", "IDs", "that", "can", "be", "checked", "out", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CompletionCommand.php#L199-L221
platformsh/platformsh-cli
src/Command/CompletionCommand.php
CompletionCommand.getAppNames
public function getAppNames() { $apps = []; if ($projectRoot = $this->getWelcomeCommand()->getProjectRoot()) { foreach (LocalApplication::getApplications($projectRoot) as $app) { $name = $app->getName(); if ($name !== null) { $apps[] = $name; } } } elseif ($project = $this->getProject()) { if ($environment = $this->api->getEnvironment('master', $project, false)) { $apps = array_keys($environment->getSshUrls()); } } return $apps; }
php
public function getAppNames() { $apps = []; if ($projectRoot = $this->getWelcomeCommand()->getProjectRoot()) { foreach (LocalApplication::getApplications($projectRoot) as $app) { $name = $app->getName(); if ($name !== null) { $apps[] = $name; } } } elseif ($project = $this->getProject()) { if ($environment = $this->api->getEnvironment('master', $project, false)) { $apps = array_keys($environment->getSshUrls()); } } return $apps; }
[ "public", "function", "getAppNames", "(", ")", "{", "$", "apps", "=", "[", "]", ";", "if", "(", "$", "projectRoot", "=", "$", "this", "->", "getWelcomeCommand", "(", ")", "->", "getProjectRoot", "(", ")", ")", "{", "foreach", "(", "LocalApplication", "...
Get a list of application names in the local project. @return string[]
[ "Get", "a", "list", "of", "application", "names", "in", "the", "local", "project", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CompletionCommand.php#L228-L245
platformsh/platformsh-cli
src/Command/CompletionCommand.php
CompletionCommand.getProject
protected function getProject() { if (!$this->projects) { return false; } $commandLine = $this->handler->getContext() ->getCommandLine(); $currentProjectId = $this->getProjectIdFromCommandLine($commandLine); if (!$currentProjectId && ($currentProject = $this->getWelcomeCommand()->getCurrentProject())) { return $currentProject; } elseif (isset($this->projects[$currentProjectId])) { return $this->projects[$currentProjectId]; } return false; }
php
protected function getProject() { if (!$this->projects) { return false; } $commandLine = $this->handler->getContext() ->getCommandLine(); $currentProjectId = $this->getProjectIdFromCommandLine($commandLine); if (!$currentProjectId && ($currentProject = $this->getWelcomeCommand()->getCurrentProject())) { return $currentProject; } elseif (isset($this->projects[$currentProjectId])) { return $this->projects[$currentProjectId]; } return false; }
[ "protected", "function", "getProject", "(", ")", "{", "if", "(", "!", "$", "this", "->", "projects", ")", "{", "return", "false", ";", "}", "$", "commandLine", "=", "$", "this", "->", "handler", "->", "getContext", "(", ")", "->", "getCommandLine", "("...
Get the preferred project for autocompletion. The project is either defined by an ID that the user has specified in the command (via the 'project' argument or '--project' option), or it is determined from the current path. @return \Platformsh\Client\Model\Project|false
[ "Get", "the", "preferred", "project", "for", "autocompletion", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CompletionCommand.php#L256-L272
platformsh/platformsh-cli
src/Command/CompletionCommand.php
CompletionCommand.getEnvironments
public function getEnvironments() { $project = $this->getProject(); if (!$project) { return []; } return array_keys($this->api->getEnvironments($project, false, false)); }
php
public function getEnvironments() { $project = $this->getProject(); if (!$project) { return []; } return array_keys($this->api->getEnvironments($project, false, false)); }
[ "public", "function", "getEnvironments", "(", ")", "{", "$", "project", "=", "$", "this", "->", "getProject", "(", ")", ";", "if", "(", "!", "$", "project", ")", "{", "return", "[", "]", ";", "}", "return", "array_keys", "(", "$", "this", "->", "ap...
Get a list of environment IDs. @return string[]
[ "Get", "a", "list", "of", "environment", "IDs", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CompletionCommand.php#L279-L287
platformsh/platformsh-cli
src/Command/CompletionCommand.php
CompletionCommand.getUserEmails
public function getUserEmails() { $project = $this->getProject(); if (!$project) { return []; } $emails = []; foreach ($this->api->getProjectAccesses($project) as $projectAccess) { $account = $this->api->getAccount($projectAccess); $emails[] = $account['email']; } return $emails; }
php
public function getUserEmails() { $project = $this->getProject(); if (!$project) { return []; } $emails = []; foreach ($this->api->getProjectAccesses($project) as $projectAccess) { $account = $this->api->getAccount($projectAccess); $emails[] = $account['email']; } return $emails; }
[ "public", "function", "getUserEmails", "(", ")", "{", "$", "project", "=", "$", "this", "->", "getProject", "(", ")", ";", "if", "(", "!", "$", "project", ")", "{", "return", "[", "]", ";", "}", "$", "emails", "=", "[", "]", ";", "foreach", "(", ...
Get a list of user email addresses. @return string[]
[ "Get", "a", "list", "of", "user", "email", "addresses", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CompletionCommand.php#L294-L308
platformsh/platformsh-cli
src/Service/Url.php
Url.openUrl
public function openUrl($url, $print = true) { $browserOption = $this->input->hasOption('browser') ? $this->input->getOption('browser') : null; $open = true; $success = false; // If the user wants to pipe the output to another command, stop here. if ($this->input->hasOption('pipe') && $this->input->getOption('pipe')) { $open = false; $print = true; } // Check if the user has requested not to use a browser. elseif ($browserOption === '0') { $open = false; } // Check for a display (if not on Windows or OS X). elseif (!$this->hasDisplay()) { $open = false; $this->stdErr->writeln('Not opening URL (no display found)', OutputInterface::VERBOSITY_VERBOSE); } // Open the URL. if ($open && ($browser = $this->getBrowser($browserOption))) { $success = $this->shell->executeSimple($browser . ' ' . escapeshellarg($url)) === 0; } // Print the URL. if ($print) { $this->output->writeln($url); } return $success; }
php
public function openUrl($url, $print = true) { $browserOption = $this->input->hasOption('browser') ? $this->input->getOption('browser') : null; $open = true; $success = false; // If the user wants to pipe the output to another command, stop here. if ($this->input->hasOption('pipe') && $this->input->getOption('pipe')) { $open = false; $print = true; } // Check if the user has requested not to use a browser. elseif ($browserOption === '0') { $open = false; } // Check for a display (if not on Windows or OS X). elseif (!$this->hasDisplay()) { $open = false; $this->stdErr->writeln('Not opening URL (no display found)', OutputInterface::VERBOSITY_VERBOSE); } // Open the URL. if ($open && ($browser = $this->getBrowser($browserOption))) { $success = $this->shell->executeSimple($browser . ' ' . escapeshellarg($url)) === 0; } // Print the URL. if ($print) { $this->output->writeln($url); } return $success; }
[ "public", "function", "openUrl", "(", "$", "url", ",", "$", "print", "=", "true", ")", "{", "$", "browserOption", "=", "$", "this", "->", "input", "->", "hasOption", "(", "'browser'", ")", "?", "$", "this", "->", "input", "->", "getOption", "(", "'br...
Open a URL in the browser, or print it. @param string $url @param bool $print @return bool True if a browser was used, false otherwise.
[ "Open", "a", "URL", "in", "the", "browser", "or", "print", "it", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Url.php#L67-L99
platformsh/platformsh-cli
src/Service/Url.php
Url.getBrowser
private function getBrowser($browserOption = null) { if (!empty($browserOption)) { list($command, ) = explode(' ', $browserOption, 2); if (!$this->shell->commandExists($command)) { $this->stdErr->writeln(sprintf('Command not found: <error>%s</error>', $command)); return false; } return $browserOption; } return $this->getDefaultBrowser(); }
php
private function getBrowser($browserOption = null) { if (!empty($browserOption)) { list($command, ) = explode(' ', $browserOption, 2); if (!$this->shell->commandExists($command)) { $this->stdErr->writeln(sprintf('Command not found: <error>%s</error>', $command)); return false; } return $browserOption; } return $this->getDefaultBrowser(); }
[ "private", "function", "getBrowser", "(", "$", "browserOption", "=", "null", ")", "{", "if", "(", "!", "empty", "(", "$", "browserOption", ")", ")", "{", "list", "(", "$", "command", ",", ")", "=", "explode", "(", "' '", ",", "$", "browserOption", ",...
Finds the browser to use. @param string|null $browserOption @return string|false A browser command, or false if no browser can or should be used.
[ "Finds", "the", "browser", "to", "use", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Url.php#L119-L132
platformsh/platformsh-cli
src/Service/Url.php
Url.getDefaultBrowser
private function getDefaultBrowser() { $browsers = ['xdg-open', 'gnome-open', 'start']; if (OsUtil::isOsX()) { $browsers = ['open']; } foreach ($browsers as $browser) { if ($this->shell->commandExists($browser)) { return $browser; } } return false; }
php
private function getDefaultBrowser() { $browsers = ['xdg-open', 'gnome-open', 'start']; if (OsUtil::isOsX()) { $browsers = ['open']; } foreach ($browsers as $browser) { if ($this->shell->commandExists($browser)) { return $browser; } } return false; }
[ "private", "function", "getDefaultBrowser", "(", ")", "{", "$", "browsers", "=", "[", "'xdg-open'", ",", "'gnome-open'", ",", "'start'", "]", ";", "if", "(", "OsUtil", "::", "isOsX", "(", ")", ")", "{", "$", "browsers", "=", "[", "'open'", "]", ";", ...
Find a default browser to use. @return string|false
[ "Find", "a", "default", "browser", "to", "use", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Url.php#L139-L153
platformsh/platformsh-cli
src/Command/Repo/LsCommand.php
LsCommand.configure
protected function configure() { $this ->setName('repo:ls') ->setDescription('List files in the project repository') ->addArgument('path', InputArgument::OPTIONAL, 'The path to a subdirectory') ->addOption('directories', 'd', InputOption::VALUE_NONE, 'Show directories only') ->addOption('files', 'f', InputOption::VALUE_NONE, 'Show files only') ->addOption('git-style', null, InputOption::VALUE_NONE, 'Style output similar to "git ls-tree"') ->addOption('commit', 'c', InputOption::VALUE_REQUIRED, 'The commit SHA. ' . GitDataApi::COMMIT_SYNTAX_HELP); $this->addProjectOption(); $this->addEnvironmentOption(); }
php
protected function configure() { $this ->setName('repo:ls') ->setDescription('List files in the project repository') ->addArgument('path', InputArgument::OPTIONAL, 'The path to a subdirectory') ->addOption('directories', 'd', InputOption::VALUE_NONE, 'Show directories only') ->addOption('files', 'f', InputOption::VALUE_NONE, 'Show files only') ->addOption('git-style', null, InputOption::VALUE_NONE, 'Style output similar to "git ls-tree"') ->addOption('commit', 'c', InputOption::VALUE_REQUIRED, 'The commit SHA. ' . GitDataApi::COMMIT_SYNTAX_HELP); $this->addProjectOption(); $this->addEnvironmentOption(); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'repo:ls'", ")", "->", "setDescription", "(", "'List files in the project repository'", ")", "->", "addArgument", "(", "'path'", ",", "InputArgument", "::", "OPTIONAL", ",", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Repo/LsCommand.php#L19-L31
platformsh/platformsh-cli
src/Command/Repo/LsCommand.php
LsCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input, false, true); $environment = $this->getSelectedEnvironment(); try { /** @var \Platformsh\Cli\Service\GitDataApi $gitData */ $gitData = $this->getService('git_data_api'); $tree = $gitData->getTree($environment, $input->getArgument('path'), $input->getOption('commit')); } catch (GitObjectTypeException $e) { $this->stdErr->writeln(sprintf( '%s: <error>%s</error>', $e->getMessage(), $e->getPath() )); $this->stdErr->writeln(sprintf('To read a file, run: <comment>%s repo:cat [path]</comment>', $this->config()->get('application.executable'))); return 3; } if ($tree == false) { $this->stdErr->writeln(sprintf('Directory not found: <error>%s</error>', $input->getArgument('path'))); return 2; } $treeObjects = $tree->tree; if ($input->getOption('files') && $input->getOption('directories')) { // No filters required. } elseif ($input->getOption('files')) { $treeObjects = array_filter($treeObjects, function (array $treeObject) { return $treeObject['type'] === 'blob'; }); } elseif ($input->getOption('directories')) { $treeObjects = array_filter($treeObjects, function (array $treeObject) { return $treeObject['type'] === 'tree'; }); } $gitStyle = $input->getOption('git-style'); foreach ($treeObjects as $object) { if ($gitStyle) { $detailsFormat = "%s %s %s\t%s"; $output->writeln(sprintf( $detailsFormat, $object['mode'], $object['type'], $object['sha'], $object['path'] )); } else { $format = '%s'; if ($object['type'] === 'tree') { $format = '<fg=cyan>%s/</>'; } $output->writeln(sprintf($format, $object['path'])); } } return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input, false, true); $environment = $this->getSelectedEnvironment(); try { /** @var \Platformsh\Cli\Service\GitDataApi $gitData */ $gitData = $this->getService('git_data_api'); $tree = $gitData->getTree($environment, $input->getArgument('path'), $input->getOption('commit')); } catch (GitObjectTypeException $e) { $this->stdErr->writeln(sprintf( '%s: <error>%s</error>', $e->getMessage(), $e->getPath() )); $this->stdErr->writeln(sprintf('To read a file, run: <comment>%s repo:cat [path]</comment>', $this->config()->get('application.executable'))); return 3; } if ($tree == false) { $this->stdErr->writeln(sprintf('Directory not found: <error>%s</error>', $input->getArgument('path'))); return 2; } $treeObjects = $tree->tree; if ($input->getOption('files') && $input->getOption('directories')) { // No filters required. } elseif ($input->getOption('files')) { $treeObjects = array_filter($treeObjects, function (array $treeObject) { return $treeObject['type'] === 'blob'; }); } elseif ($input->getOption('directories')) { $treeObjects = array_filter($treeObjects, function (array $treeObject) { return $treeObject['type'] === 'tree'; }); } $gitStyle = $input->getOption('git-style'); foreach ($treeObjects as $object) { if ($gitStyle) { $detailsFormat = "%s %s %s\t%s"; $output->writeln(sprintf( $detailsFormat, $object['mode'], $object['type'], $object['sha'], $object['path'] )); } else { $format = '%s'; if ($object['type'] === 'tree') { $format = '<fg=cyan>%s/</>'; } $output->writeln(sprintf($format, $object['path'])); } } 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/Repo/LsCommand.php#L36-L95
platformsh/platformsh-cli
src/Service/Relationships.php
Relationships.chooseDatabase
public function chooseDatabase($sshUrl, InputInterface $input, OutputInterface $output) { return $this->chooseService($sshUrl, $input, $output, ['mysql', 'pgsql']); }
php
public function chooseDatabase($sshUrl, InputInterface $input, OutputInterface $output) { return $this->chooseService($sshUrl, $input, $output, ['mysql', 'pgsql']); }
[ "public", "function", "chooseDatabase", "(", "$", "sshUrl", ",", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "return", "$", "this", "->", "chooseService", "(", "$", "sshUrl", ",", "$", "input", ",", "$", "output", ",", ...
Choose a database for the user. @param string $sshUrl @param InputInterface $input @param OutputInterface $output @return array|false
[ "Choose", "a", "database", "for", "the", "user", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Relationships.php#L44-L47
platformsh/platformsh-cli
src/Service/Relationships.php
Relationships.chooseService
public function chooseService($sshUrl, InputInterface $input, OutputInterface $output, $schemes = []) { $stdErr = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output; $relationships = $this->getRelationships($sshUrl); // Filter to find services matching the schemes. if (!empty($schemes)) { $relationships = array_filter($relationships, function (array $relationship) use ($schemes) { foreach ($relationship as $key => $service) { if (isset($service['scheme']) && in_array($service['scheme'], $schemes, true)) { return true; } } return false; }); } if (empty($relationships)) { if (!empty($schemes)) { $stdErr->writeln(sprintf('No relationships found matching scheme(s): <error>%s</error>.', implode(', ', $schemes))); } else { $stdErr->writeln(sprintf('No relationships found')); } return false; } // Collapse relationships and services into a flat list. $choices = []; foreach ($relationships as $name => $relationship) { $serviceCount = count($relationship); foreach ($relationship as $key => $info) { $identifier = $name . ($serviceCount > 1 ? '.' . $key : ''); if (isset($info['username']) && (!isset($info['host']) || $info['host'] === '127.0.0.1')) { $choices[$identifier] = sprintf('%s (%s)', $identifier, $info['username']); } elseif (isset($info['username'], $info['host'])) { $choices[$identifier] = sprintf('%s (%s@%s)', $identifier, $info['username'], $info['host']); } else { $choices[$identifier] = $identifier; } } } // Use the --relationship option, if specified. $identifier = false; if ($input->hasOption('relationship') && ($relationshipName = $input->getOption('relationship'))) { // Normalise the relationship name to remove a trailing ".0". if (substr($relationshipName, -2) === '.0' && isset($relationships[$relationshipName]) && count($relationships[$relationshipName]) ===1) { $relationshipName = substr($relationshipName, 0, strlen($relationshipName) - 2); } if (!isset($choices[$relationshipName])) { $stdErr->writeln('Relationship not found: <error>' . $relationshipName . '</error>'); return false; } $identifier = $relationshipName; } if (!$identifier && count($choices) === 1) { $identifier = key($choices); } if (!$identifier && !$input->isInteractive()) { $stdErr->writeln('More than one relationship found.'); if ($input->hasOption('relationship')) { $stdErr->writeln('Use the <error>--relationship</error> (-r) option to specify a relationship. Options:'); foreach (array_keys($choices) as $identifier) { $stdErr->writeln(' ' . $identifier); } } return false; } if (!$identifier) { $questionHelper = new QuestionHelper($input, $output); $identifier = $questionHelper->choose($choices, 'Enter a number to choose a relationship:'); } if (strpos($identifier, '.') !== false) { list($name, $key) = explode('.', $identifier, 2); } else { $name = $identifier; $key = 0; } $relationship = $relationships[$name][$key]; // Ensure the service name is included in the relationship info. // This is for backwards compatibility with projects that do not have // this information. if (!isset($relationship['service'])) { $appConfig = $this->envVarService->getArrayEnvVar('APPLICATION', $sshUrl); if (!empty($appConfig['relationships'][$name]) && is_string($appConfig['relationships'][$name])) { list($serviceName, ) = explode(':', $appConfig['relationships'][$name], 2); $relationship['service'] = $serviceName; } } // Add metadata about the service. $relationship['_relationship_name'] = $name; $relationship['_relationship_key'] = $key; return $relationship; }
php
public function chooseService($sshUrl, InputInterface $input, OutputInterface $output, $schemes = []) { $stdErr = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output; $relationships = $this->getRelationships($sshUrl); // Filter to find services matching the schemes. if (!empty($schemes)) { $relationships = array_filter($relationships, function (array $relationship) use ($schemes) { foreach ($relationship as $key => $service) { if (isset($service['scheme']) && in_array($service['scheme'], $schemes, true)) { return true; } } return false; }); } if (empty($relationships)) { if (!empty($schemes)) { $stdErr->writeln(sprintf('No relationships found matching scheme(s): <error>%s</error>.', implode(', ', $schemes))); } else { $stdErr->writeln(sprintf('No relationships found')); } return false; } // Collapse relationships and services into a flat list. $choices = []; foreach ($relationships as $name => $relationship) { $serviceCount = count($relationship); foreach ($relationship as $key => $info) { $identifier = $name . ($serviceCount > 1 ? '.' . $key : ''); if (isset($info['username']) && (!isset($info['host']) || $info['host'] === '127.0.0.1')) { $choices[$identifier] = sprintf('%s (%s)', $identifier, $info['username']); } elseif (isset($info['username'], $info['host'])) { $choices[$identifier] = sprintf('%s (%s@%s)', $identifier, $info['username'], $info['host']); } else { $choices[$identifier] = $identifier; } } } // Use the --relationship option, if specified. $identifier = false; if ($input->hasOption('relationship') && ($relationshipName = $input->getOption('relationship'))) { // Normalise the relationship name to remove a trailing ".0". if (substr($relationshipName, -2) === '.0' && isset($relationships[$relationshipName]) && count($relationships[$relationshipName]) ===1) { $relationshipName = substr($relationshipName, 0, strlen($relationshipName) - 2); } if (!isset($choices[$relationshipName])) { $stdErr->writeln('Relationship not found: <error>' . $relationshipName . '</error>'); return false; } $identifier = $relationshipName; } if (!$identifier && count($choices) === 1) { $identifier = key($choices); } if (!$identifier && !$input->isInteractive()) { $stdErr->writeln('More than one relationship found.'); if ($input->hasOption('relationship')) { $stdErr->writeln('Use the <error>--relationship</error> (-r) option to specify a relationship. Options:'); foreach (array_keys($choices) as $identifier) { $stdErr->writeln(' ' . $identifier); } } return false; } if (!$identifier) { $questionHelper = new QuestionHelper($input, $output); $identifier = $questionHelper->choose($choices, 'Enter a number to choose a relationship:'); } if (strpos($identifier, '.') !== false) { list($name, $key) = explode('.', $identifier, 2); } else { $name = $identifier; $key = 0; } $relationship = $relationships[$name][$key]; // Ensure the service name is included in the relationship info. // This is for backwards compatibility with projects that do not have // this information. if (!isset($relationship['service'])) { $appConfig = $this->envVarService->getArrayEnvVar('APPLICATION', $sshUrl); if (!empty($appConfig['relationships'][$name]) && is_string($appConfig['relationships'][$name])) { list($serviceName, ) = explode(':', $appConfig['relationships'][$name], 2); $relationship['service'] = $serviceName; } } // Add metadata about the service. $relationship['_relationship_name'] = $name; $relationship['_relationship_key'] = $key; return $relationship; }
[ "public", "function", "chooseService", "(", "$", "sshUrl", ",", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ",", "$", "schemes", "=", "[", "]", ")", "{", "$", "stdErr", "=", "$", "output", "instanceof", "ConsoleOutputInterface", "?...
Choose a service for the user. @param string $sshUrl @param InputInterface $input @param OutputInterface $output @param string[] $schemes Filter by scheme. @return array|false
[ "Choose", "a", "service", "for", "the", "user", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Relationships.php#L59-L162
platformsh/platformsh-cli
src/Service/Relationships.php
Relationships.getDbCommandArgs
public function getDbCommandArgs($command, array $database, $schema = null) { if ($schema === null) { $schema = $database['path']; } switch ($command) { case 'psql': case 'pg_dump': $url = sprintf( 'postgresql://%s:%s@%s:%d', $database['username'], $database['password'], $database['host'], $database['port'] ); if ($schema !== '') { $url .= '/' . rawurlencode($schema); } return OsUtil::escapePosixShellArg($url); case 'mysql': case 'mysqldump': $args = sprintf( '--user=%s --password=%s --host=%s --port=%d', OsUtil::escapePosixShellArg($database['username']), OsUtil::escapePosixShellArg($database['password']), OsUtil::escapePosixShellArg($database['host']), $database['port'] ); if ($schema !== '') { $args .= ' ' . OsUtil::escapePosixShellArg($schema); } return $args; case 'mongo': case 'mongodump': case 'mongoexport': case 'mongorestore': $args = sprintf( '--username %s --password %s --host %s --port %d', OsUtil::escapePosixShellArg($database['username']), OsUtil::escapePosixShellArg($database['password']), OsUtil::escapePosixShellArg($database['host']), $database['port'] ); if ($schema !== '') { $args .= ' --authenticationDatabase ' . OsUtil::escapePosixShellArg($schema); if ($command === 'mongo') { $args .= ' ' . OsUtil::escapePosixShellArg($schema); } else { $args .= ' --db ' . OsUtil::escapePosixShellArg($schema); } } return $args; } throw new \InvalidArgumentException('Unrecognised command: ' . $command); }
php
public function getDbCommandArgs($command, array $database, $schema = null) { if ($schema === null) { $schema = $database['path']; } switch ($command) { case 'psql': case 'pg_dump': $url = sprintf( 'postgresql://%s:%s@%s:%d', $database['username'], $database['password'], $database['host'], $database['port'] ); if ($schema !== '') { $url .= '/' . rawurlencode($schema); } return OsUtil::escapePosixShellArg($url); case 'mysql': case 'mysqldump': $args = sprintf( '--user=%s --password=%s --host=%s --port=%d', OsUtil::escapePosixShellArg($database['username']), OsUtil::escapePosixShellArg($database['password']), OsUtil::escapePosixShellArg($database['host']), $database['port'] ); if ($schema !== '') { $args .= ' ' . OsUtil::escapePosixShellArg($schema); } return $args; case 'mongo': case 'mongodump': case 'mongoexport': case 'mongorestore': $args = sprintf( '--username %s --password %s --host %s --port %d', OsUtil::escapePosixShellArg($database['username']), OsUtil::escapePosixShellArg($database['password']), OsUtil::escapePosixShellArg($database['host']), $database['port'] ); if ($schema !== '') { $args .= ' --authenticationDatabase ' . OsUtil::escapePosixShellArg($schema); if ($command === 'mongo') { $args .= ' ' . OsUtil::escapePosixShellArg($schema); } else { $args .= ' --db ' . OsUtil::escapePosixShellArg($schema); } } return $args; } throw new \InvalidArgumentException('Unrecognised command: ' . $command); }
[ "public", "function", "getDbCommandArgs", "(", "$", "command", ",", "array", "$", "database", ",", "$", "schema", "=", "null", ")", "{", "if", "(", "$", "schema", "===", "null", ")", "{", "$", "schema", "=", "$", "database", "[", "'path'", "]", ";", ...
Returns command-line arguments to connect to a database. @param string $command The command that will need arguments (one of 'psql', 'pg_dump', 'mysql', or 'mysqldump'). @param array $database The database definition from the relationship. @param string|null $schema The name of a database schema, or null to use the default schema, or an empty string to not select a schema. @return string The command line arguments (excluding the $command).
[ "Returns", "command", "-", "line", "arguments", "to", "connect", "to", "a", "database", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Relationships.php#L193-L254
platformsh/platformsh-cli
src/Util/NestedArrayUtil.php
NestedArrayUtil.&
public static function &getNestedArrayValue(array &$array, array $parents, &$keyExists = false) { $ref = &$array; foreach ($parents as $parent) { if (is_array($ref) && array_key_exists($parent, $ref)) { $ref = &$ref[$parent]; } else { $keyExists = false; $null = null; return $null; } } $keyExists = true; return $ref; }
php
public static function &getNestedArrayValue(array &$array, array $parents, &$keyExists = false) { $ref = &$array; foreach ($parents as $parent) { if (is_array($ref) && array_key_exists($parent, $ref)) { $ref = &$ref[$parent]; } else { $keyExists = false; $null = null; return $null; } } $keyExists = true; return $ref; }
[ "public", "static", "function", "&", "getNestedArrayValue", "(", "array", "&", "$", "array", ",", "array", "$", "parents", ",", "&", "$", "keyExists", "=", "false", ")", "{", "$", "ref", "=", "&", "$", "array", ";", "foreach", "(", "$", "parents", "a...
Get a nested value in an array. @see Copied from \Drupal\Component\Utility\NestedArray::getValue() @param array $array @param array $parents @param bool $keyExists @return mixed
[ "Get", "a", "nested", "value", "in", "an", "array", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/NestedArrayUtil.php#L18-L33
platformsh/platformsh-cli
src/Util/NestedArrayUtil.php
NestedArrayUtil.setNestedArrayValue
public static function setNestedArrayValue(array &$array, array $parents, $value, $force = false) { $ref = &$array; foreach ($parents as $parent) { // PHP auto-creates container arrays and NULL entries without error if $ref // is NULL, but throws an error if $ref is set, but not an array. if ($force && isset($ref) && !is_array($ref)) { $ref = []; } $ref = &$ref[$parent]; } $ref = $value; }
php
public static function setNestedArrayValue(array &$array, array $parents, $value, $force = false) { $ref = &$array; foreach ($parents as $parent) { // PHP auto-creates container arrays and NULL entries without error if $ref // is NULL, but throws an error if $ref is set, but not an array. if ($force && isset($ref) && !is_array($ref)) { $ref = []; } $ref = &$ref[$parent]; } $ref = $value; }
[ "public", "static", "function", "setNestedArrayValue", "(", "array", "&", "$", "array", ",", "array", "$", "parents", ",", "$", "value", ",", "$", "force", "=", "false", ")", "{", "$", "ref", "=", "&", "$", "array", ";", "foreach", "(", "$", "parents...
Set a nested value in an array. @see Copied from \Drupal\Component\Utility\NestedArray::setValue() @param array &$array @param array $parents @param mixed $value @param bool $force
[ "Set", "a", "nested", "value", "in", "an", "array", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/NestedArrayUtil.php#L45-L57
platformsh/platformsh-cli
src/Command/SshKey/SshKeyAddCommand.php
SshKeyAddCommand.keyExistsByFingerprint
protected function keyExistsByFingerprint($fingerprint) { foreach ($this->api()->getClient()->getSshKeys() as $existingKey) { if ($existingKey->fingerprint === $fingerprint) { return true; } } return false; }
php
protected function keyExistsByFingerprint($fingerprint) { foreach ($this->api()->getClient()->getSshKeys() as $existingKey) { if ($existingKey->fingerprint === $fingerprint) { return true; } } return false; }
[ "protected", "function", "keyExistsByFingerprint", "(", "$", "fingerprint", ")", "{", "foreach", "(", "$", "this", "->", "api", "(", ")", "->", "getClient", "(", ")", "->", "getSshKeys", "(", ")", "as", "$", "existingKey", ")", "{", "if", "(", "$", "ex...
Check whether the SSH key already exists in the user's account. @param string $fingerprint The public key fingerprint (as an MD5 hash). @return bool
[ "Check", "whether", "the", "SSH", "key", "already", "exists", "in", "the", "user", "s", "account", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/SshKey/SshKeyAddCommand.php#L145-L154
platformsh/platformsh-cli
src/Command/SshKey/SshKeyAddCommand.php
SshKeyAddCommand.getNewKeyPath
protected function getNewKeyPath($number = 1) { $basename = self::DEFAULT_BASENAME; if ($number > 1) { $basename = strpos($basename, '.key') ? str_replace('.key', '.' . $number . 'key', $basename) : $basename . '.' . $number; } /** @var \Platformsh\Cli\Service\Filesystem $fs */ $fs = $this->getService('fs'); $filename = $fs->getHomeDirectory() . '/.ssh/' . $basename; if (file_exists($filename)) { return $this->getNewKeyPath(++$number); } return $filename; }
php
protected function getNewKeyPath($number = 1) { $basename = self::DEFAULT_BASENAME; if ($number > 1) { $basename = strpos($basename, '.key') ? str_replace('.key', '.' . $number . 'key', $basename) : $basename . '.' . $number; } /** @var \Platformsh\Cli\Service\Filesystem $fs */ $fs = $this->getService('fs'); $filename = $fs->getHomeDirectory() . '/.ssh/' . $basename; if (file_exists($filename)) { return $this->getNewKeyPath(++$number); } return $filename; }
[ "protected", "function", "getNewKeyPath", "(", "$", "number", "=", "1", ")", "{", "$", "basename", "=", "self", "::", "DEFAULT_BASENAME", ";", "if", "(", "$", "number", ">", "1", ")", "{", "$", "basename", "=", "strpos", "(", "$", "basename", ",", "'...
Find the path for a new SSH key. If the file already exists, this will recurse to find a new filename. The first will be "id_rsa", the second "id_rsa2", the third "id_rsa3", and so on. @param int $number @return string
[ "Find", "the", "path", "for", "a", "new", "SSH", "key", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/SshKey/SshKeyAddCommand.php#L167-L183
platformsh/platformsh-cli
src/Command/Environment/EnvironmentInitCommand.php
EnvironmentInitCommand.configure
protected function configure() { $this ->setName('environment:init') ->setDescription('Initialize an environment from a public Git repository') ->addArgument('url', InputArgument::REQUIRED, 'A URL to a Git repository') ->addOption('profile', null, InputOption::VALUE_REQUIRED, 'The name of the profile'); if ($this->config()->get('service.name') === 'Platform.sh') { $this->addExample('Initialize using the Platform.sh Go template', 'https://github.com/platformsh/template-golang'); } $this->addProjectOption() ->addEnvironmentOption() ->addWaitOptions(); }
php
protected function configure() { $this ->setName('environment:init') ->setDescription('Initialize an environment from a public Git repository') ->addArgument('url', InputArgument::REQUIRED, 'A URL to a Git repository') ->addOption('profile', null, InputOption::VALUE_REQUIRED, 'The name of the profile'); if ($this->config()->get('service.name') === 'Platform.sh') { $this->addExample('Initialize using the Platform.sh Go template', 'https://github.com/platformsh/template-golang'); } $this->addProjectOption() ->addEnvironmentOption() ->addWaitOptions(); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'environment:init'", ")", "->", "setDescription", "(", "'Initialize an environment from a public Git repository'", ")", "->", "addArgument", "(", "'url'", ",", "InputArgument", ":...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentInitCommand.php#L15-L30
platformsh/platformsh-cli
src/Command/Environment/EnvironmentInitCommand.php
EnvironmentInitCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input, true); if (!$this->hasSelectedEnvironment()) { $this->selectEnvironment('master'); } $environment = $this->getSelectedEnvironment(); $url = $input->getArgument('url'); $profile = $input->getOption('profile') ?: basename($url); if (parse_url($url) === false) { $this->stdErr->writeln(sprintf('Invalid repository URL: <error>%s</error>', $url)); return 1; } if (!$environment->operationAvailable('initialize', true)) { $this->stdErr->writeln(sprintf( "Operation not available: The environment <error>%s</error> can't be initialized.", $environment->id )); if ($environment->has_code) { $this->stdErr->writeln('The environment already contains code.'); } return 1; } // Summarize this action with a message. $message = 'Initializing project '; $message .= $this->api()->getProjectLabel($this->getSelectedProject()); if ($environment->id !== 'master') { $message .= ', environment ' . $this->api()->getEnvironmentLabel($environment); } if ($input->getOption('profile')) { $message .= ' with profile <info>' . $profile . '</info> (' . $url . ')'; } else { $message .= ' with repository <info>' . $url . '</info>.'; } $this->stdErr->writeln($message); $activity = $environment->initialize($profile, $url); $this->api()->clearEnvironmentsCache($environment->project); if ($this->shouldWait($input)) { /** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */ $activityMonitor = $this->getService('activity_monitor'); $activityMonitor->waitAndLog($activity); } return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input, true); if (!$this->hasSelectedEnvironment()) { $this->selectEnvironment('master'); } $environment = $this->getSelectedEnvironment(); $url = $input->getArgument('url'); $profile = $input->getOption('profile') ?: basename($url); if (parse_url($url) === false) { $this->stdErr->writeln(sprintf('Invalid repository URL: <error>%s</error>', $url)); return 1; } if (!$environment->operationAvailable('initialize', true)) { $this->stdErr->writeln(sprintf( "Operation not available: The environment <error>%s</error> can't be initialized.", $environment->id )); if ($environment->has_code) { $this->stdErr->writeln('The environment already contains code.'); } return 1; } // Summarize this action with a message. $message = 'Initializing project '; $message .= $this->api()->getProjectLabel($this->getSelectedProject()); if ($environment->id !== 'master') { $message .= ', environment ' . $this->api()->getEnvironmentLabel($environment); } if ($input->getOption('profile')) { $message .= ' with profile <info>' . $profile . '</info> (' . $url . ')'; } else { $message .= ' with repository <info>' . $url . '</info>.'; } $this->stdErr->writeln($message); $activity = $environment->initialize($profile, $url); $this->api()->clearEnvironmentsCache($environment->project); if ($this->shouldWait($input)) { /** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */ $activityMonitor = $this->getService('activity_monitor'); $activityMonitor->waitAndLog($activity); } return 0; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "validateInput", "(", "$", "input", ",", "true", ")", ";", "if", "(", "!", "$", "this", "->", "hasSelectedEnvironme...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentInitCommand.php#L35-L90
platformsh/platformsh-cli
src/Service/PropertyFormatter.php
PropertyFormatter.format
public function format($value, $property = null) { switch ($property) { case 'http_access': return $this->formatHttpAccess($value); case 'token': return '******'; case 'addon_credentials': if (is_array($value) && isset($value['shared_secret'])) { $value['shared_secret'] = '******'; } break; case 'app_credentials': if (is_array($value) && isset($value['secret'])) { $value['secret'] = '******'; } break; case 'author.date': case 'committer.date': case 'created_at': case 'updated_at': case 'expires_at': case 'started_at': case 'completed_at': case 'ssl.expires_on': $value = $this->formatDate($value); break; case 'ssl': if ($property === 'ssl' && is_array($value) && isset($value['expires_on'])) { $value['expires_on'] = $this->formatDate($value['expires_on']); } } if (!is_string($value)) { $value = rtrim(Yaml::dump($value, 2)); } return $value; }
php
public function format($value, $property = null) { switch ($property) { case 'http_access': return $this->formatHttpAccess($value); case 'token': return '******'; case 'addon_credentials': if (is_array($value) && isset($value['shared_secret'])) { $value['shared_secret'] = '******'; } break; case 'app_credentials': if (is_array($value) && isset($value['secret'])) { $value['secret'] = '******'; } break; case 'author.date': case 'committer.date': case 'created_at': case 'updated_at': case 'expires_at': case 'started_at': case 'completed_at': case 'ssl.expires_on': $value = $this->formatDate($value); break; case 'ssl': if ($property === 'ssl' && is_array($value) && isset($value['expires_on'])) { $value['expires_on'] = $this->formatDate($value['expires_on']); } } if (!is_string($value)) { $value = rtrim(Yaml::dump($value, 2)); } return $value; }
[ "public", "function", "format", "(", "$", "value", ",", "$", "property", "=", "null", ")", "{", "switch", "(", "$", "property", ")", "{", "case", "'http_access'", ":", "return", "$", "this", "->", "formatHttpAccess", "(", "$", "value", ")", ";", "case"...
@param mixed $value @param string $property @return string
[ "@param", "mixed", "$value", "@param", "string", "$property" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/PropertyFormatter.php#L32-L75
platformsh/platformsh-cli
src/Service/PropertyFormatter.php
PropertyFormatter.configureInput
public static function configureInput(InputDefinition $definition) { $definition->addOption(new InputOption( 'date-fmt', null, InputOption::VALUE_REQUIRED, 'The date format (as a PHP date format string)', // @todo refactor so this can be non-static and use injected config (new Config())->getWithDefault('application.date_format', 'c') )); }
php
public static function configureInput(InputDefinition $definition) { $definition->addOption(new InputOption( 'date-fmt', null, InputOption::VALUE_REQUIRED, 'The date format (as a PHP date format string)', // @todo refactor so this can be non-static and use injected config (new Config())->getWithDefault('application.date_format', 'c') )); }
[ "public", "static", "function", "configureInput", "(", "InputDefinition", "$", "definition", ")", "{", "$", "definition", "->", "addOption", "(", "new", "InputOption", "(", "'date-fmt'", ",", "null", ",", "InputOption", "::", "VALUE_REQUIRED", ",", "'The date form...
Add options to a command's input definition. @param InputDefinition $definition
[ "Add", "options", "to", "a", "command", "s", "input", "definition", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/PropertyFormatter.php#L82-L92
platformsh/platformsh-cli
src/Service/PropertyFormatter.php
PropertyFormatter.formatDate
protected function formatDate($value) { $format = null; if (isset($this->input) && $this->input->hasOption('date-fmt')) { $format = $this->input->getOption('date-fmt'); } if ($format === null) { $format = $this->config->getWithDefault('application.date_format', 'c'); } // Workaround for the ssl.expires_on date, which is currently a // timestamp in milliseconds. if (substr($value, -3) === '000' && strlen($value) === 13) { $value = substr($value, 0, 10); } $timestamp = is_numeric($value) ? $value : strtotime($value); return $timestamp === false ? null : date($format, $timestamp); }
php
protected function formatDate($value) { $format = null; if (isset($this->input) && $this->input->hasOption('date-fmt')) { $format = $this->input->getOption('date-fmt'); } if ($format === null) { $format = $this->config->getWithDefault('application.date_format', 'c'); } // Workaround for the ssl.expires_on date, which is currently a // timestamp in milliseconds. if (substr($value, -3) === '000' && strlen($value) === 13) { $value = substr($value, 0, 10); } $timestamp = is_numeric($value) ? $value : strtotime($value); return $timestamp === false ? null : date($format, $timestamp); }
[ "protected", "function", "formatDate", "(", "$", "value", ")", "{", "$", "format", "=", "null", ";", "if", "(", "isset", "(", "$", "this", "->", "input", ")", "&&", "$", "this", "->", "input", "->", "hasOption", "(", "'date-fmt'", ")", ")", "{", "$...
@param string $value @return string|null
[ "@param", "string", "$value" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/PropertyFormatter.php#L99-L118
platformsh/platformsh-cli
src/Service/PropertyFormatter.php
PropertyFormatter.formatHttpAccess
protected function formatHttpAccess($httpAccess) { $info = (array) $httpAccess; $info += [ 'addresses' => [], 'basic_auth' => [], 'is_enabled' => true, ]; // Hide passwords. $info['basic_auth'] = array_map(function () { return '******'; }, $info['basic_auth']); return $this->format($info); }
php
protected function formatHttpAccess($httpAccess) { $info = (array) $httpAccess; $info += [ 'addresses' => [], 'basic_auth' => [], 'is_enabled' => true, ]; // Hide passwords. $info['basic_auth'] = array_map(function () { return '******'; }, $info['basic_auth']); return $this->format($info); }
[ "protected", "function", "formatHttpAccess", "(", "$", "httpAccess", ")", "{", "$", "info", "=", "(", "array", ")", "$", "httpAccess", ";", "$", "info", "+=", "[", "'addresses'", "=>", "[", "]", ",", "'basic_auth'", "=>", "[", "]", ",", "'is_enabled'", ...
@param array|string|null $httpAccess @return string
[ "@param", "array|string|null", "$httpAccess" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/PropertyFormatter.php#L125-L139
platformsh/platformsh-cli
src/Service/PropertyFormatter.php
PropertyFormatter.displayData
public function displayData(OutputInterface $output, array $data, $property = null) { $key = null; if ($property) { $parents = explode('.', $property); $key = end($parents); $data = NestedArrayUtil::getNestedArrayValue($data, $parents, $keyExists); if (!$keyExists) { throw new \InvalidArgumentException('Property not found: ' . $property); } } if (!is_string($data)) { $output->write(Yaml::dump($data, 5, 4, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK)); } else { $output->writeln($this->format($data, $key)); } }
php
public function displayData(OutputInterface $output, array $data, $property = null) { $key = null; if ($property) { $parents = explode('.', $property); $key = end($parents); $data = NestedArrayUtil::getNestedArrayValue($data, $parents, $keyExists); if (!$keyExists) { throw new \InvalidArgumentException('Property not found: ' . $property); } } if (!is_string($data)) { $output->write(Yaml::dump($data, 5, 4, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK)); } else { $output->writeln($this->format($data, $key)); } }
[ "public", "function", "displayData", "(", "OutputInterface", "$", "output", ",", "array", "$", "data", ",", "$", "property", "=", "null", ")", "{", "$", "key", "=", "null", ";", "if", "(", "$", "property", ")", "{", "$", "parents", "=", "explode", "(...
Display a complex data structure. @param OutputInterface $output An output object. @param array $data The data to display. @param string|null $property The property of the data to display (a dot-separated string).
[ "Display", "a", "complex", "data", "structure", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/PropertyFormatter.php#L149-L167
platformsh/platformsh-cli
src/Command/Tunnel/TunnelCommandBase.php
TunnelCommandBase.isTunnelOpen
protected function isTunnelOpen(array $tunnel) { foreach ($this->getTunnelInfo() as $info) { if ($this->tunnelsAreEqual($tunnel, $info)) { /** @noinspection PhpComposerExtensionStubsInspection */ if (isset($info['pid']) && function_exists('posix_kill') && !posix_kill($info['pid'], 0)) { $this->debug(sprintf( 'The tunnel at port %d is no longer open, removing from list', $info['localPort'] )); $this->closeTunnel($info); continue; } return $info; } } return false; }
php
protected function isTunnelOpen(array $tunnel) { foreach ($this->getTunnelInfo() as $info) { if ($this->tunnelsAreEqual($tunnel, $info)) { /** @noinspection PhpComposerExtensionStubsInspection */ if (isset($info['pid']) && function_exists('posix_kill') && !posix_kill($info['pid'], 0)) { $this->debug(sprintf( 'The tunnel at port %d is no longer open, removing from list', $info['localPort'] )); $this->closeTunnel($info); continue; } return $info; } } return false; }
[ "protected", "function", "isTunnelOpen", "(", "array", "$", "tunnel", ")", "{", "foreach", "(", "$", "this", "->", "getTunnelInfo", "(", ")", "as", "$", "info", ")", "{", "if", "(", "$", "this", "->", "tunnelsAreEqual", "(", "$", "tunnel", ",", "$", ...
Check whether a tunnel is already open. @param array $tunnel @return bool|array
[ "Check", "whether", "a", "tunnel", "is", "already", "open", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Tunnel/TunnelCommandBase.php#L25-L44
platformsh/platformsh-cli
src/Command/Tunnel/TunnelCommandBase.php
TunnelCommandBase.getTunnelInfo
protected function getTunnelInfo($open = true) { if (!isset($this->tunnelInfo)) { $this->tunnelInfo = []; // @todo move this to State service (in a new major version) $filename = $this->config()->getWritableUserDir() . '/tunnel-info.json'; if (file_exists($filename)) { $this->debug(sprintf('Loading tunnel info from %s', $filename)); $this->tunnelInfo = (array) json_decode(file_get_contents($filename), true); } } if ($open) { $needsSave = false; foreach ($this->tunnelInfo as $key => $tunnel) { /** @noinspection PhpComposerExtensionStubsInspection */ if (isset($tunnel['pid']) && function_exists('posix_kill') && !posix_kill($tunnel['pid'], 0)) { $this->debug(sprintf( 'The tunnel at port %d is no longer open, removing from list', $tunnel['localPort'] )); unset($this->tunnelInfo[$key]); $needsSave = true; } } if ($needsSave) { $this->saveTunnelInfo(); } } return $this->tunnelInfo; }
php
protected function getTunnelInfo($open = true) { if (!isset($this->tunnelInfo)) { $this->tunnelInfo = []; // @todo move this to State service (in a new major version) $filename = $this->config()->getWritableUserDir() . '/tunnel-info.json'; if (file_exists($filename)) { $this->debug(sprintf('Loading tunnel info from %s', $filename)); $this->tunnelInfo = (array) json_decode(file_get_contents($filename), true); } } if ($open) { $needsSave = false; foreach ($this->tunnelInfo as $key => $tunnel) { /** @noinspection PhpComposerExtensionStubsInspection */ if (isset($tunnel['pid']) && function_exists('posix_kill') && !posix_kill($tunnel['pid'], 0)) { $this->debug(sprintf( 'The tunnel at port %d is no longer open, removing from list', $tunnel['localPort'] )); unset($this->tunnelInfo[$key]); $needsSave = true; } } if ($needsSave) { $this->saveTunnelInfo(); } } return $this->tunnelInfo; }
[ "protected", "function", "getTunnelInfo", "(", "$", "open", "=", "true", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "tunnelInfo", ")", ")", "{", "$", "this", "->", "tunnelInfo", "=", "[", "]", ";", "// @todo move this to State service (in a...
Get info on currently open tunnels. @param bool $open @return array
[ "Get", "info", "on", "currently", "open", "tunnels", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Tunnel/TunnelCommandBase.php#L53-L84
platformsh/platformsh-cli
src/Command/Tunnel/TunnelCommandBase.php
TunnelCommandBase.closeTunnel
protected function closeTunnel(array $tunnel) { $success = true; if (isset($tunnel['pid']) && function_exists('posix_kill')) { /** @noinspection PhpComposerExtensionStubsInspection */ $success = posix_kill($tunnel['pid'], SIGTERM); if (!$success) { /** @noinspection PhpComposerExtensionStubsInspection */ $this->stdErr->writeln(sprintf( 'Failed to kill process <error>%d</error> (POSIX error %s)', $tunnel['pid'], posix_get_last_error() )); } } $pidFile = $this->getPidFile($tunnel); if (file_exists($pidFile)) { $success = unlink($pidFile) && $success; } $this->tunnelInfo = array_filter($this->tunnelInfo, function ($info) use ($tunnel) { return !$this->tunnelsAreEqual($info, $tunnel); }); $this->saveTunnelInfo(); return $success; }
php
protected function closeTunnel(array $tunnel) { $success = true; if (isset($tunnel['pid']) && function_exists('posix_kill')) { /** @noinspection PhpComposerExtensionStubsInspection */ $success = posix_kill($tunnel['pid'], SIGTERM); if (!$success) { /** @noinspection PhpComposerExtensionStubsInspection */ $this->stdErr->writeln(sprintf( 'Failed to kill process <error>%d</error> (POSIX error %s)', $tunnel['pid'], posix_get_last_error() )); } } $pidFile = $this->getPidFile($tunnel); if (file_exists($pidFile)) { $success = unlink($pidFile) && $success; } $this->tunnelInfo = array_filter($this->tunnelInfo, function ($info) use ($tunnel) { return !$this->tunnelsAreEqual($info, $tunnel); }); $this->saveTunnelInfo(); return $success; }
[ "protected", "function", "closeTunnel", "(", "array", "$", "tunnel", ")", "{", "$", "success", "=", "true", ";", "if", "(", "isset", "(", "$", "tunnel", "[", "'pid'", "]", ")", "&&", "function_exists", "(", "'posix_kill'", ")", ")", "{", "/** @noinspecti...
Close an open tunnel. @param array $tunnel @return bool True on success, false on failure.
[ "Close", "an", "open", "tunnel", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Tunnel/TunnelCommandBase.php#L107-L132
platformsh/platformsh-cli
src/Command/Tunnel/TunnelCommandBase.php
TunnelCommandBase.getPort
protected function getPort($default = 30000) { $ports = []; foreach ($this->getTunnelInfo() as $tunnel) { $ports[] = $tunnel['localPort']; } return PortUtil::getPort($ports ? max($ports) + 1 : $default); }
php
protected function getPort($default = 30000) { $ports = []; foreach ($this->getTunnelInfo() as $tunnel) { $ports[] = $tunnel['localPort']; } return PortUtil::getPort($ports ? max($ports) + 1 : $default); }
[ "protected", "function", "getPort", "(", "$", "default", "=", "30000", ")", "{", "$", "ports", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getTunnelInfo", "(", ")", "as", "$", "tunnel", ")", "{", "$", "ports", "[", "]", "=", "$", "tun...
Automatically determine the best port for a new tunnel. @param int $default @return int
[ "Automatically", "determine", "the", "best", "port", "for", "a", "new", "tunnel", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Tunnel/TunnelCommandBase.php#L141-L149
platformsh/platformsh-cli
src/Command/Tunnel/TunnelCommandBase.php
TunnelCommandBase.getPidFile
protected function getPidFile(array $tunnel) { $key = $this->getTunnelKey($tunnel); $dir = $this->config()->getWritableUserDir() . '/.tunnels'; if (!is_dir($dir) && !mkdir($dir, 0700, true)) { throw new \RuntimeException('Failed to create directory: ' . $dir); } return $dir . '/' . preg_replace('/[^0-9a-z\.]+/', '-', $key) . '.pid'; }
php
protected function getPidFile(array $tunnel) { $key = $this->getTunnelKey($tunnel); $dir = $this->config()->getWritableUserDir() . '/.tunnels'; if (!is_dir($dir) && !mkdir($dir, 0700, true)) { throw new \RuntimeException('Failed to create directory: ' . $dir); } return $dir . '/' . preg_replace('/[^0-9a-z\.]+/', '-', $key) . '.pid'; }
[ "protected", "function", "getPidFile", "(", "array", "$", "tunnel", ")", "{", "$", "key", "=", "$", "this", "->", "getTunnelKey", "(", "$", "tunnel", ")", ";", "$", "dir", "=", "$", "this", "->", "config", "(", ")", "->", "getWritableUserDir", "(", "...
@param array $tunnel @return string
[ "@param", "array", "$tunnel" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Tunnel/TunnelCommandBase.php#L198-L207
platformsh/platformsh-cli
src/Command/Tunnel/TunnelCommandBase.php
TunnelCommandBase.createTunnelProcess
protected function createTunnelProcess($url, $remoteHost, $remotePort, $localPort, array $extraArgs = []) { $args = ['ssh', '-n', '-N', '-L', implode(':', [$localPort, $remoteHost, $remotePort]), $url]; $args = array_merge($args, $extraArgs); $process = new Process($args); $process->setTimeout(null); return $process; }
php
protected function createTunnelProcess($url, $remoteHost, $remotePort, $localPort, array $extraArgs = []) { $args = ['ssh', '-n', '-N', '-L', implode(':', [$localPort, $remoteHost, $remotePort]), $url]; $args = array_merge($args, $extraArgs); $process = new Process($args); $process->setTimeout(null); return $process; }
[ "protected", "function", "createTunnelProcess", "(", "$", "url", ",", "$", "remoteHost", ",", "$", "remotePort", ",", "$", "localPort", ",", "array", "$", "extraArgs", "=", "[", "]", ")", "{", "$", "args", "=", "[", "'ssh'", ",", "'-n'", ",", "'-N'", ...
@param string $url @param string $remoteHost @param int $remotePort @param int $localPort @param array $extraArgs @return \Symfony\Component\Process\Process
[ "@param", "string", "$url", "@param", "string", "$remoteHost", "@param", "int", "$remotePort", "@param", "int", "$localPort", "@param", "array", "$extraArgs" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Tunnel/TunnelCommandBase.php#L218-L226
platformsh/platformsh-cli
src/Command/Tunnel/TunnelCommandBase.php
TunnelCommandBase.filterTunnels
protected function filterTunnels(array $tunnels, InputInterface $input) { if (!$input->getOption('project') && !$this->getProjectRoot()) { return $tunnels; } if (!$this->hasSelectedProject()) { $this->validateInput($input, true); } $project = $this->getSelectedProject(); $environment = $this->hasSelectedEnvironment() ? $this->getSelectedEnvironment() : null; $appName = $this->hasSelectedEnvironment() ? $this->selectApp($input) : null; foreach ($tunnels as $key => $tunnel) { if ($tunnel['projectId'] !== $project->id || ($environment !== null && $tunnel['environmentId'] !== $environment->id) || ($appName !== null && $tunnel['appName'] !== $appName)) { unset($tunnels[$key]); } } return $tunnels; }
php
protected function filterTunnels(array $tunnels, InputInterface $input) { if (!$input->getOption('project') && !$this->getProjectRoot()) { return $tunnels; } if (!$this->hasSelectedProject()) { $this->validateInput($input, true); } $project = $this->getSelectedProject(); $environment = $this->hasSelectedEnvironment() ? $this->getSelectedEnvironment() : null; $appName = $this->hasSelectedEnvironment() ? $this->selectApp($input) : null; foreach ($tunnels as $key => $tunnel) { if ($tunnel['projectId'] !== $project->id || ($environment !== null && $tunnel['environmentId'] !== $environment->id) || ($appName !== null && $tunnel['appName'] !== $appName)) { unset($tunnels[$key]); } } return $tunnels; }
[ "protected", "function", "filterTunnels", "(", "array", "$", "tunnels", ",", "InputInterface", "$", "input", ")", "{", "if", "(", "!", "$", "input", "->", "getOption", "(", "'project'", ")", "&&", "!", "$", "this", "->", "getProjectRoot", "(", ")", ")", ...
Filter a list of tunnels by the currently selected project/environment. @param array $tunnels @param InputInterface $input @return array
[ "Filter", "a", "list", "of", "tunnels", "by", "the", "currently", "selected", "project", "/", "environment", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Tunnel/TunnelCommandBase.php#L236-L257
platformsh/platformsh-cli
src/Util/SslUtil.php
SslUtil.validate
public function validate($certPath, $keyPath, array $chainPaths) { // Get the contents. if (!is_readable($certPath)) { throw new \InvalidArgumentException('The certificate file could not be read: ' . $certPath); } $sslCert = trim(file_get_contents($certPath)); // Do a bit of validation. $certResource = openssl_x509_read($sslCert); if (!$certResource) { throw new \InvalidArgumentException('The certificate file is not a valid X509 certificate: ' . $certPath); } // Then the key. Does it match? if (!is_readable($keyPath)) { throw new \InvalidArgumentException('The private key file could not be read: ' . $keyPath); } $sslPrivateKey = trim(file_get_contents($keyPath)); $keyResource = openssl_pkey_get_private($sslPrivateKey); if (!$keyResource) { throw new \InvalidArgumentException('Private key not valid, or passphrase-protected: ' . $keyPath); } $keyMatch = openssl_x509_check_private_key($certResource, $keyResource); if (!$keyMatch) { throw new \InvalidArgumentException('The provided certificate does not match the provided private key.'); } // Each chain needs to contain one or more valid certificates. $chainFileContents = $this->readChainFiles($chainPaths); foreach ($chainFileContents as $filePath => $data) { $chainResource = openssl_x509_read($data); if (!$chainResource) { throw new \InvalidArgumentException('File contains an invalid X509 certificate: ' . $filePath); } openssl_x509_free($chainResource); } // Split up the chain file contents. $chain = []; $begin = '-----BEGIN CERTIFICATE-----'; foreach ($chainFileContents as $data) { if (substr_count($data, $begin) > 1) { foreach (explode($begin, $data) as $cert) { $chain[] = $begin . $cert; } } else { $chain[] = $data; } } return [ 'certificate' => $sslCert, 'key' => $sslPrivateKey, 'chain' => $chain, ]; }
php
public function validate($certPath, $keyPath, array $chainPaths) { // Get the contents. if (!is_readable($certPath)) { throw new \InvalidArgumentException('The certificate file could not be read: ' . $certPath); } $sslCert = trim(file_get_contents($certPath)); // Do a bit of validation. $certResource = openssl_x509_read($sslCert); if (!$certResource) { throw new \InvalidArgumentException('The certificate file is not a valid X509 certificate: ' . $certPath); } // Then the key. Does it match? if (!is_readable($keyPath)) { throw new \InvalidArgumentException('The private key file could not be read: ' . $keyPath); } $sslPrivateKey = trim(file_get_contents($keyPath)); $keyResource = openssl_pkey_get_private($sslPrivateKey); if (!$keyResource) { throw new \InvalidArgumentException('Private key not valid, or passphrase-protected: ' . $keyPath); } $keyMatch = openssl_x509_check_private_key($certResource, $keyResource); if (!$keyMatch) { throw new \InvalidArgumentException('The provided certificate does not match the provided private key.'); } // Each chain needs to contain one or more valid certificates. $chainFileContents = $this->readChainFiles($chainPaths); foreach ($chainFileContents as $filePath => $data) { $chainResource = openssl_x509_read($data); if (!$chainResource) { throw new \InvalidArgumentException('File contains an invalid X509 certificate: ' . $filePath); } openssl_x509_free($chainResource); } // Split up the chain file contents. $chain = []; $begin = '-----BEGIN CERTIFICATE-----'; foreach ($chainFileContents as $data) { if (substr_count($data, $begin) > 1) { foreach (explode($begin, $data) as $cert) { $chain[] = $begin . $cert; } } else { $chain[] = $data; } } return [ 'certificate' => $sslCert, 'key' => $sslPrivateKey, 'chain' => $chain, ]; }
[ "public", "function", "validate", "(", "$", "certPath", ",", "$", "keyPath", ",", "array", "$", "chainPaths", ")", "{", "// Get the contents.", "if", "(", "!", "is_readable", "(", "$", "certPath", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentExceptio...
@param string $certPath @param string $keyPath @param array $chainPaths @return array An array containing the contents of the certificate files, keyed as 'certificate' (string), 'key' (string), and 'chain' (array).
[ "@param", "string", "$certPath", "@param", "string", "$keyPath", "@param", "array", "$chainPaths" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/SslUtil.php#L16-L70
platformsh/platformsh-cli
src/Util/SslUtil.php
SslUtil.readChainFiles
protected function readChainFiles(array $chainPaths) { $chainFiles = []; foreach ($chainPaths as $chainPath) { if (!is_readable($chainPath)) { throw new \Exception("The chain file could not be read: $chainPath"); } $chainFiles[$chainPath] = trim(file_get_contents($chainPath)); } return $chainFiles; }
php
protected function readChainFiles(array $chainPaths) { $chainFiles = []; foreach ($chainPaths as $chainPath) { if (!is_readable($chainPath)) { throw new \Exception("The chain file could not be read: $chainPath"); } $chainFiles[$chainPath] = trim(file_get_contents($chainPath)); } return $chainFiles; }
[ "protected", "function", "readChainFiles", "(", "array", "$", "chainPaths", ")", "{", "$", "chainFiles", "=", "[", "]", ";", "foreach", "(", "$", "chainPaths", "as", "$", "chainPath", ")", "{", "if", "(", "!", "is_readable", "(", "$", "chainPath", ")", ...
Get the contents of multiple chain files. @param string[] $chainPaths @throws \Exception If any one of the files is not readable. @return array An array of file contents (whitespace trimmed) keyed by file name.
[ "Get", "the", "contents", "of", "multiple", "chain", "files", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/SslUtil.php#L82-L93
platformsh/platformsh-cli
src/Command/Environment/EnvironmentCheckoutCommand.php
EnvironmentCheckoutCommand.offerBranchChoice
protected function offerBranchChoice(Project $project, $projectRoot) { $environments = $this->api()->getEnvironments($project); $currentEnvironment = $this->getCurrentEnvironment($project); if ($currentEnvironment) { $this->stdErr->writeln("The current environment is " . $this->api()->getEnvironmentLabel($currentEnvironment) . "."); $this->stdErr->writeln(''); } $environmentList = []; foreach ($environments as $id => $environment) { // The $id will be an integer for numeric environment names (as // it was assigned to an array key), so it's cast back to a // string for this comparison. if ($currentEnvironment && (string) $id === $currentEnvironment->id) { continue; } $environmentList[$id] = $this->api()->getEnvironmentLabel($environment, false); } /** @var \Platformsh\Cli\Local\LocalProject $localProject */ $localProject = $this->getService('local.project'); $projectConfig = $localProject->getProjectConfig($projectRoot); if (!empty($projectConfig['mapping'])) { foreach ($projectConfig['mapping'] as $branch => $id) { if (isset($environmentList[$id]) && isset($environmentList[$branch])) { unset($environmentList[$id]); $environmentList[$branch] = sprintf('%s (%s)', $environments[$id]->title, $branch); } } } if (!count($environmentList)) { $this->stdErr->writeln(sprintf( 'Use <info>%s branch</info> to create an environment.', $this->config()->get('application.executable') )); return false; } /** @var \Platformsh\Cli\Service\QuestionHelper $helper */ $helper = $this->getService('question_helper'); // If there's more than one choice, present the user with a list. if (count($environmentList) > 1) { $chooseEnvironmentText = "Enter a number to check out another environment:"; // The environment ID will be an integer if it was numeric // (because PHP does that with array keys), so it's cast back to // a string here. return (string) $helper->choose($environmentList, $chooseEnvironmentText); } // If there's only one choice, QuestionHelper::choose() does not // interact. But we still need interactive confirmation at this point. $environmentId = key($environmentList); if ($environmentId !== false) { $label = $this->api()->getEnvironmentLabel($environments[$environmentId]); if ($helper->confirm(sprintf('Check out environment %s?', $label))) { return $environmentId; } } return false; }
php
protected function offerBranchChoice(Project $project, $projectRoot) { $environments = $this->api()->getEnvironments($project); $currentEnvironment = $this->getCurrentEnvironment($project); if ($currentEnvironment) { $this->stdErr->writeln("The current environment is " . $this->api()->getEnvironmentLabel($currentEnvironment) . "."); $this->stdErr->writeln(''); } $environmentList = []; foreach ($environments as $id => $environment) { // The $id will be an integer for numeric environment names (as // it was assigned to an array key), so it's cast back to a // string for this comparison. if ($currentEnvironment && (string) $id === $currentEnvironment->id) { continue; } $environmentList[$id] = $this->api()->getEnvironmentLabel($environment, false); } /** @var \Platformsh\Cli\Local\LocalProject $localProject */ $localProject = $this->getService('local.project'); $projectConfig = $localProject->getProjectConfig($projectRoot); if (!empty($projectConfig['mapping'])) { foreach ($projectConfig['mapping'] as $branch => $id) { if (isset($environmentList[$id]) && isset($environmentList[$branch])) { unset($environmentList[$id]); $environmentList[$branch] = sprintf('%s (%s)', $environments[$id]->title, $branch); } } } if (!count($environmentList)) { $this->stdErr->writeln(sprintf( 'Use <info>%s branch</info> to create an environment.', $this->config()->get('application.executable') )); return false; } /** @var \Platformsh\Cli\Service\QuestionHelper $helper */ $helper = $this->getService('question_helper'); // If there's more than one choice, present the user with a list. if (count($environmentList) > 1) { $chooseEnvironmentText = "Enter a number to check out another environment:"; // The environment ID will be an integer if it was numeric // (because PHP does that with array keys), so it's cast back to // a string here. return (string) $helper->choose($environmentList, $chooseEnvironmentText); } // If there's only one choice, QuestionHelper::choose() does not // interact. But we still need interactive confirmation at this point. $environmentId = key($environmentList); if ($environmentId !== false) { $label = $this->api()->getEnvironmentLabel($environments[$environmentId]); if ($helper->confirm(sprintf('Check out environment %s?', $label))) { return $environmentId; } } return false; }
[ "protected", "function", "offerBranchChoice", "(", "Project", "$", "project", ",", "$", "projectRoot", ")", "{", "$", "environments", "=", "$", "this", "->", "api", "(", ")", "->", "getEnvironments", "(", "$", "project", ")", ";", "$", "currentEnvironment", ...
Prompt the user to select a branch to checkout. @param Project $project @param string $projectRoot @return string|false The branch name, or false on failure.
[ "Prompt", "the", "user", "to", "select", "a", "branch", "to", "checkout", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentCheckoutCommand.php#L108-L170
platformsh/platformsh-cli
src/Console/Animation.php
Animation.render
public function render($placeholder = '.') { // Ensure that at least $this->interval microseconds have passed since // the last frame. if ($this->lastFrameTime !== null) { $timeSince = (microtime(true) - $this->lastFrameTime) * 1000000; if ($timeSince < $this->interval) { usleep($this->interval - $timeSince); } } if ($this->lastFrame !== null) { // If overwriting is not possible, just output the placeholder. if (!$this->output->isDecorated()) { $this->output->write($placeholder); $this->lastFrameTime = microtime(true); return; } // Move the cursor up to overwrite the previous frame. $lastFrameHeight = substr_count($this->frames[$this->lastFrame], "\n") + 1; $this->output->write(sprintf("\033[%dA", $lastFrameHeight)); } // Display the current frame. $this->output->writeln($this->frames[$this->currentFrame]); // Set up the next frame. $this->lastFrame = $this->currentFrame; $this->lastFrameTime = microtime(true); $this->currentFrame++; if (!isset($this->frames[$this->currentFrame])) { $this->currentFrame = 0; } }
php
public function render($placeholder = '.') { // Ensure that at least $this->interval microseconds have passed since // the last frame. if ($this->lastFrameTime !== null) { $timeSince = (microtime(true) - $this->lastFrameTime) * 1000000; if ($timeSince < $this->interval) { usleep($this->interval - $timeSince); } } if ($this->lastFrame !== null) { // If overwriting is not possible, just output the placeholder. if (!$this->output->isDecorated()) { $this->output->write($placeholder); $this->lastFrameTime = microtime(true); return; } // Move the cursor up to overwrite the previous frame. $lastFrameHeight = substr_count($this->frames[$this->lastFrame], "\n") + 1; $this->output->write(sprintf("\033[%dA", $lastFrameHeight)); } // Display the current frame. $this->output->writeln($this->frames[$this->currentFrame]); // Set up the next frame. $this->lastFrame = $this->currentFrame; $this->lastFrameTime = microtime(true); $this->currentFrame++; if (!isset($this->frames[$this->currentFrame])) { $this->currentFrame = 0; } }
[ "public", "function", "render", "(", "$", "placeholder", "=", "'.'", ")", "{", "// Ensure that at least $this->interval microseconds have passed since", "// the last frame.", "if", "(", "$", "this", "->", "lastFrameTime", "!==", "null", ")", "{", "$", "timeSince", "="...
Display the current frame, and advance the pointer to the next one. If the output is capable of using ANSI escape codes, this will attempt to overwrite the previous frame. But if the output is not ANSI-compatible, this will display the $placeholder instead. So, to display an endless animation only where it's safe, use: <code> $animation = new ConsoleAnimation($output, $frames); do { $animation->render(); } while ($output->isDecorated()); </code> @param string $placeholder
[ "Display", "the", "current", "frame", "and", "advance", "the", "pointer", "to", "the", "next", "one", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/Animation.php#L48-L82
platformsh/platformsh-cli
src/Command/Mount/MountSizeCommand.php
MountSizeCommand.configure
protected function configure() { $this ->setName('mount:size') ->setDescription('Check the disk usage of mounts') ->addOption('bytes', 'B', InputOption::VALUE_NONE, 'Show sizes in bytes') ->addOption('refresh', null, InputOption::VALUE_NONE, 'Refresh the cache'); Table::configureInput($this->getDefinition()); Ssh::configureInput($this->getDefinition()); $this->addProjectOption(); $this->addEnvironmentOption(); $this->addAppOption(); $appConfigFile = $this->config()->get('service.app_config_file'); $this->setHelp(<<<EOF Use this command to check the disk size and usage for an application's mounts. Mounts are directories mounted into the application from a persistent, writable filesystem. They are configured in the <info>mounts</info> key in the <info>$appConfigFile</info> file. The filesystem's total size is determined by the <info>disk</info> key in the same file. EOF ); }
php
protected function configure() { $this ->setName('mount:size') ->setDescription('Check the disk usage of mounts') ->addOption('bytes', 'B', InputOption::VALUE_NONE, 'Show sizes in bytes') ->addOption('refresh', null, InputOption::VALUE_NONE, 'Refresh the cache'); Table::configureInput($this->getDefinition()); Ssh::configureInput($this->getDefinition()); $this->addProjectOption(); $this->addEnvironmentOption(); $this->addAppOption(); $appConfigFile = $this->config()->get('service.app_config_file'); $this->setHelp(<<<EOF Use this command to check the disk size and usage for an application's mounts. Mounts are directories mounted into the application from a persistent, writable filesystem. They are configured in the <info>mounts</info> key in the <info>$appConfigFile</info> file. The filesystem's total size is determined by the <info>disk</info> key in the same file. EOF ); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'mount:size'", ")", "->", "setDescription", "(", "'Check the disk usage of mounts'", ")", "->", "addOption", "(", "'bytes'", ",", "'B'", ",", "InputOption", "::", "VALUE_NON...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Mount/MountSizeCommand.php#L18-L40
platformsh/platformsh-cli
src/Command/Mount/MountSizeCommand.php
MountSizeCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $appName = $this->selectApp($input); $appConfig = $this->getAppConfig($appName, $input->getOption('refresh')); if (empty($appConfig['mounts'])) { $this->stdErr->writeln(sprintf('The app "%s" doesn\'t define any mounts.', $appConfig['name'])); return 1; } $this->stdErr->writeln(sprintf('Checking disk usage for all mounts of the application <info>%s</info>...', $appName)); // Get a list of the mount paths (and normalize them as relative paths, // relative to the application directory). $mountPaths = []; foreach (array_keys($appConfig['mounts']) as $mountPath) { $mountPaths[] = trim(trim($mountPath), '/'); } // Build a list of multiple commands that will be run over the same SSH // connection: // 1. Get the application directory (by reading the PLATFORM_APP_DIR // environment variable). // 2. Run the 'df' command to find filesystem statistics for the // mounts. // 3. Run a 'du' command on each of the mounted paths, to find their // individual sizes. $appDirVar = $this->config()->get('service.env_prefix') . 'APP_DIR'; $commands = []; $commands[] = 'echo "$' . $appDirVar . '"'; $commands[] = 'echo'; $commands[] = 'df -P -B1 -a -x squashfs -x tmpfs -x sysfs -x proc -x devpts -x rpc_pipefs'; $commands[] = 'echo'; $commands[] = 'cd "$' . $appDirVar . '"'; foreach ($mountPaths as $mountPath) { $commands[] = 'du --block-size=1 -s ' . escapeshellarg($mountPath); } $command = 'set -e; ' . implode('; ', $commands); // Connect to the application via SSH and run the commands. $sshArgs = [ 'ssh', $this->getSelectedEnvironment()->getSshUrl($appName), ]; /** @var \Platformsh\Cli\Service\Ssh $ssh */ $ssh = $this->getService('ssh'); $sshArgs = array_merge($sshArgs, $ssh->getSshArgs()); /** @var \Platformsh\Cli\Service\Shell $shell */ $shell = $this->getService('shell'); $result = $shell->execute(array_merge($sshArgs, [$command]), null, true); // Separate the commands' output. list($appDir, $dfOutput, $duOutput) = explode("\n\n", $result, 3); // Parse the output. $volumeInfo = $this->parseDf($dfOutput, $appDir, $mountPaths); $mountSizes = $this->parseDu($duOutput, $mountPaths); // Build a table of results: one line per mount, one (multi-line) row // per filesystem. $header = ['Mount(s)', 'Size(s)', 'Disk', 'Used', 'Available', 'Capacity']; $rows = []; $showInBytes = $input->getOption('bytes'); foreach ($volumeInfo as $info) { $row = []; $row[] = implode("\n", $info['mounts']); $mountUsage = []; foreach ($info['mounts'] as $mountPath) { $mountUsage[] = $mountSizes[$mountPath]; } if ($showInBytes) { $row[] = implode("\n", $mountUsage); $row[] = $info['total']; $row[] = $info['used']; $row[] = $info['available']; } else { $row[] = implode("\n", array_map([Helper::class, 'formatMemory'], $mountUsage)); $row[] = Helper::formatMemory($info['total']); $row[] = Helper::formatMemory($info['used']); $row[] = Helper::formatMemory($info['available']); } $row[] = round($info['percent_used'], 1) . '%'; $rows[] = $row; } /** @var \Platformsh\Cli\Service\Table $table */ $table = $this->getService('table'); $table->render($rows, $header); return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $appName = $this->selectApp($input); $appConfig = $this->getAppConfig($appName, $input->getOption('refresh')); if (empty($appConfig['mounts'])) { $this->stdErr->writeln(sprintf('The app "%s" doesn\'t define any mounts.', $appConfig['name'])); return 1; } $this->stdErr->writeln(sprintf('Checking disk usage for all mounts of the application <info>%s</info>...', $appName)); // Get a list of the mount paths (and normalize them as relative paths, // relative to the application directory). $mountPaths = []; foreach (array_keys($appConfig['mounts']) as $mountPath) { $mountPaths[] = trim(trim($mountPath), '/'); } // Build a list of multiple commands that will be run over the same SSH // connection: // 1. Get the application directory (by reading the PLATFORM_APP_DIR // environment variable). // 2. Run the 'df' command to find filesystem statistics for the // mounts. // 3. Run a 'du' command on each of the mounted paths, to find their // individual sizes. $appDirVar = $this->config()->get('service.env_prefix') . 'APP_DIR'; $commands = []; $commands[] = 'echo "$' . $appDirVar . '"'; $commands[] = 'echo'; $commands[] = 'df -P -B1 -a -x squashfs -x tmpfs -x sysfs -x proc -x devpts -x rpc_pipefs'; $commands[] = 'echo'; $commands[] = 'cd "$' . $appDirVar . '"'; foreach ($mountPaths as $mountPath) { $commands[] = 'du --block-size=1 -s ' . escapeshellarg($mountPath); } $command = 'set -e; ' . implode('; ', $commands); // Connect to the application via SSH and run the commands. $sshArgs = [ 'ssh', $this->getSelectedEnvironment()->getSshUrl($appName), ]; /** @var \Platformsh\Cli\Service\Ssh $ssh */ $ssh = $this->getService('ssh'); $sshArgs = array_merge($sshArgs, $ssh->getSshArgs()); /** @var \Platformsh\Cli\Service\Shell $shell */ $shell = $this->getService('shell'); $result = $shell->execute(array_merge($sshArgs, [$command]), null, true); // Separate the commands' output. list($appDir, $dfOutput, $duOutput) = explode("\n\n", $result, 3); // Parse the output. $volumeInfo = $this->parseDf($dfOutput, $appDir, $mountPaths); $mountSizes = $this->parseDu($duOutput, $mountPaths); // Build a table of results: one line per mount, one (multi-line) row // per filesystem. $header = ['Mount(s)', 'Size(s)', 'Disk', 'Used', 'Available', 'Capacity']; $rows = []; $showInBytes = $input->getOption('bytes'); foreach ($volumeInfo as $info) { $row = []; $row[] = implode("\n", $info['mounts']); $mountUsage = []; foreach ($info['mounts'] as $mountPath) { $mountUsage[] = $mountSizes[$mountPath]; } if ($showInBytes) { $row[] = implode("\n", $mountUsage); $row[] = $info['total']; $row[] = $info['used']; $row[] = $info['available']; } else { $row[] = implode("\n", array_map([Helper::class, 'formatMemory'], $mountUsage)); $row[] = Helper::formatMemory($info['total']); $row[] = Helper::formatMemory($info['used']); $row[] = Helper::formatMemory($info['available']); } $row[] = round($info['percent_used'], 1) . '%'; $rows[] = $row; } /** @var \Platformsh\Cli\Service\Table $table */ $table = $this->getService('table'); $table->render($rows, $header); return 0; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "validateInput", "(", "$", "input", ")", ";", "$", "appName", "=", "$", "this", "->", "selectApp", "(", "$", "inp...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Mount/MountSizeCommand.php#L45-L140
platformsh/platformsh-cli
src/Command/Mount/MountSizeCommand.php
MountSizeCommand.getDfColumn
private function getDfColumn($line, $columnName) { $columnPatterns = [ 'filesystem' => '#^(.+?)(\s+[0-9])#', 'total' => '#([0-9]+)\s+[0-9]+\s+[0-9]+\s+[0-9]+%\s+#', 'used' => '#([0-9]+)\s+[0-9]+\s+[0-9]+%\s+#', 'available' => '#([0-9]+)\s+[0-9]+%\s+#', 'path' => '#%\s+(/.+)$#', ]; if (!isset($columnPatterns[$columnName])) { throw new \InvalidArgumentException("Invalid df column: $columnName"); } if (!preg_match($columnPatterns[$columnName], $line, $matches)) { throw new \RuntimeException("Failed to find column '$columnName' in df line: \n$line"); } return trim($matches[1]); }
php
private function getDfColumn($line, $columnName) { $columnPatterns = [ 'filesystem' => '#^(.+?)(\s+[0-9])#', 'total' => '#([0-9]+)\s+[0-9]+\s+[0-9]+\s+[0-9]+%\s+#', 'used' => '#([0-9]+)\s+[0-9]+\s+[0-9]+%\s+#', 'available' => '#([0-9]+)\s+[0-9]+%\s+#', 'path' => '#%\s+(/.+)$#', ]; if (!isset($columnPatterns[$columnName])) { throw new \InvalidArgumentException("Invalid df column: $columnName"); } if (!preg_match($columnPatterns[$columnName], $line, $matches)) { throw new \RuntimeException("Failed to find column '$columnName' in df line: \n$line"); } return trim($matches[1]); }
[ "private", "function", "getDfColumn", "(", "$", "line", ",", "$", "columnName", ")", "{", "$", "columnPatterns", "=", "[", "'filesystem'", "=>", "'#^(.+?)(\\s+[0-9])#'", ",", "'total'", "=>", "'#([0-9]+)\\s+[0-9]+\\s+[0-9]+\\s+[0-9]+%\\s+#'", ",", "'used'", "=>", "'...
Get a column from a line of df output. Unfortunately there doesn't seem to be a more reliable way to parse df output than by regular expression. @param string $line @param string $columnName @return string
[ "Get", "a", "column", "from", "a", "line", "of", "df", "output", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Mount/MountSizeCommand.php#L153-L170
platformsh/platformsh-cli
src/Command/Mount/MountSizeCommand.php
MountSizeCommand.parseDf
private function parseDf($dfOutput, $appDir, array $mountPaths) { $results = []; foreach (explode("\n", $dfOutput) as $i => $line) { if ($i === 0) { continue; } try { $path = $this->getDfColumn($line, 'path'); } catch (\RuntimeException $e) { $this->debug($e->getMessage()); continue; } if (strpos($path, $appDir . '/') !== 0) { continue; } $mountPath = ltrim(substr($path, strlen($appDir)), '/'); if (!in_array($mountPath, $mountPaths)) { continue; } $filesystem = $this->getDfColumn($line, 'filesystem'); if (isset($results[$filesystem])) { $results[$filesystem]['mounts'][] = $mountPath; continue; } $results[$filesystem] = [ 'total' => $this->getDfColumn($line, 'total'), 'used' => $this->getDfColumn($line, 'used'), 'available' => $this->getDfColumn($line, 'available'), 'mounts' => [$mountPath], ]; $results[$filesystem]['percent_used'] = $results[$filesystem]['used'] / $results[$filesystem]['total'] * 100; } return $results; }
php
private function parseDf($dfOutput, $appDir, array $mountPaths) { $results = []; foreach (explode("\n", $dfOutput) as $i => $line) { if ($i === 0) { continue; } try { $path = $this->getDfColumn($line, 'path'); } catch (\RuntimeException $e) { $this->debug($e->getMessage()); continue; } if (strpos($path, $appDir . '/') !== 0) { continue; } $mountPath = ltrim(substr($path, strlen($appDir)), '/'); if (!in_array($mountPath, $mountPaths)) { continue; } $filesystem = $this->getDfColumn($line, 'filesystem'); if (isset($results[$filesystem])) { $results[$filesystem]['mounts'][] = $mountPath; continue; } $results[$filesystem] = [ 'total' => $this->getDfColumn($line, 'total'), 'used' => $this->getDfColumn($line, 'used'), 'available' => $this->getDfColumn($line, 'available'), 'mounts' => [$mountPath], ]; $results[$filesystem]['percent_used'] = $results[$filesystem]['used'] / $results[$filesystem]['total'] * 100; } return $results; }
[ "private", "function", "parseDf", "(", "$", "dfOutput", ",", "$", "appDir", ",", "array", "$", "mountPaths", ")", "{", "$", "results", "=", "[", "]", ";", "foreach", "(", "explode", "(", "\"\\n\"", ",", "$", "dfOutput", ")", "as", "$", "i", "=>", "...
Parse the output of 'df', building a list of results per FS volume. @param string $dfOutput @param string $appDir @param array $mountPaths @return array
[ "Parse", "the", "output", "of", "df", "building", "a", "list", "of", "results", "per", "FS", "volume", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Mount/MountSizeCommand.php#L181-L216
platformsh/platformsh-cli
src/Command/Mount/MountSizeCommand.php
MountSizeCommand.parseDu
private function parseDu($duOutput, array $mountPaths) { $mountSizes = []; $duOutputSplit = explode("\n", $duOutput, count($mountPaths)); foreach ($mountPaths as $i => $mountPath) { if (!isset($duOutputSplit[$i])) { throw new \RuntimeException("Failed to find row $i of 'du' command output: \n" . $duOutput); } list($mountSizes[$mountPath],) = explode("\t", $duOutputSplit[$i], 2); } return $mountSizes; }
php
private function parseDu($duOutput, array $mountPaths) { $mountSizes = []; $duOutputSplit = explode("\n", $duOutput, count($mountPaths)); foreach ($mountPaths as $i => $mountPath) { if (!isset($duOutputSplit[$i])) { throw new \RuntimeException("Failed to find row $i of 'du' command output: \n" . $duOutput); } list($mountSizes[$mountPath],) = explode("\t", $duOutputSplit[$i], 2); } return $mountSizes; }
[ "private", "function", "parseDu", "(", "$", "duOutput", ",", "array", "$", "mountPaths", ")", "{", "$", "mountSizes", "=", "[", "]", ";", "$", "duOutputSplit", "=", "explode", "(", "\"\\n\"", ",", "$", "duOutput", ",", "count", "(", "$", "mountPaths", ...
Parse the 'du' output. @param string $duOutput @param array $mountPaths @return array A list of mount sizes (in bytes) keyed by mount path.
[ "Parse", "the", "du", "output", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Mount/MountSizeCommand.php#L226-L238
platformsh/platformsh-cli
src/Command/Domain/DomainUpdateCommand.php
DomainUpdateCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); if (!$this->validateDomainInput($input)) { return 1; } $project = $this->getSelectedProject(); $domain = $project->getDomain($this->domainName); if (!$domain) { $this->stdErr->writeln('Domain not found: <error>' . $this->domainName . '</error>'); return 1; } $needsUpdate = false; foreach (['key' => '', 'certificate' => '', 'chain' => []] as $option => $default) { if (empty($this->sslOptions[$option])) { $this->sslOptions[$option] = $domain->ssl[$option] ?: $default; } elseif ($this->sslOptions[$option] != $domain->ssl[$option]) { $needsUpdate = true; } } if (!$needsUpdate) { $this->stdErr->writeln('There is nothing to update.'); return 0; } $this->stdErr->writeln('Updating the domain <info>' . $this->domainName . '</info>'); $result = $domain->update(['ssl' => $this->sslOptions]); if ($this->shouldWait($input)) { /** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */ $activityMonitor = $this->getService('activity_monitor'); $activityMonitor->waitMultiple($result->getActivities(), $project); } return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); if (!$this->validateDomainInput($input)) { return 1; } $project = $this->getSelectedProject(); $domain = $project->getDomain($this->domainName); if (!$domain) { $this->stdErr->writeln('Domain not found: <error>' . $this->domainName . '</error>'); return 1; } $needsUpdate = false; foreach (['key' => '', 'certificate' => '', 'chain' => []] as $option => $default) { if (empty($this->sslOptions[$option])) { $this->sslOptions[$option] = $domain->ssl[$option] ?: $default; } elseif ($this->sslOptions[$option] != $domain->ssl[$option]) { $needsUpdate = true; } } if (!$needsUpdate) { $this->stdErr->writeln('There is nothing to update.'); return 0; } $this->stdErr->writeln('Updating the domain <info>' . $this->domainName . '</info>'); $result = $domain->update(['ssl' => $this->sslOptions]); if ($this->shouldWait($input)) { /** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */ $activityMonitor = $this->getService('activity_monitor'); $activityMonitor->waitMultiple($result->getActivities(), $project); } return 0; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "validateInput", "(", "$", "input", ")", ";", "if", "(", "!", "$", "this", "->", "validateDomainInput", "(", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Domain/DomainUpdateCommand.php#L29-L70
platformsh/platformsh-cli
src/Command/Mount/MountCommandBase.php
MountCommandBase.getAppConfig
protected function getAppConfig($appName, $refresh = true) { $webApp = $this->api() ->getCurrentDeployment($this->getSelectedEnvironment(), $refresh) ->getWebApp($appName); return AppConfig::fromWebApp($webApp)->getNormalized(); }
php
protected function getAppConfig($appName, $refresh = true) { $webApp = $this->api() ->getCurrentDeployment($this->getSelectedEnvironment(), $refresh) ->getWebApp($appName); return AppConfig::fromWebApp($webApp)->getNormalized(); }
[ "protected", "function", "getAppConfig", "(", "$", "appName", ",", "$", "refresh", "=", "true", ")", "{", "$", "webApp", "=", "$", "this", "->", "api", "(", ")", "->", "getCurrentDeployment", "(", "$", "this", "->", "getSelectedEnvironment", "(", ")", ",...
Get the remote application config. @param string $appName @param bool $refresh @return array
[ "Get", "the", "remote", "application", "config", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Mount/MountCommandBase.php#L19-L26
platformsh/platformsh-cli
src/Command/Mount/MountCommandBase.php
MountCommandBase.getMountsAsOptions
protected function getMountsAsOptions(array $mounts) { $options = []; foreach ($mounts as $path => $definition) { if ($definition['source'] === 'local' && isset($definition['source_path'])) { $options[$path] = sprintf('<question>%s</question> (shared:files/%s)', $path, $definition['source_path']); } else { $options[$path] = sprintf('<question>%s</question>: %s', $path, $definition['source']); } } return $options; }
php
protected function getMountsAsOptions(array $mounts) { $options = []; foreach ($mounts as $path => $definition) { if ($definition['source'] === 'local' && isset($definition['source_path'])) { $options[$path] = sprintf('<question>%s</question> (shared:files/%s)', $path, $definition['source_path']); } else { $options[$path] = sprintf('<question>%s</question>: %s', $path, $definition['source']); } } return $options; }
[ "protected", "function", "getMountsAsOptions", "(", "array", "$", "mounts", ")", "{", "$", "options", "=", "[", "]", ";", "foreach", "(", "$", "mounts", "as", "$", "path", "=>", "$", "definition", ")", "{", "if", "(", "$", "definition", "[", "'source'"...
Format the mounts as an array of options for a ChoiceQuestion. @param array $mounts @return array
[ "Format", "the", "mounts", "as", "an", "array", "of", "options", "for", "a", "ChoiceQuestion", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Mount/MountCommandBase.php#L35-L47
platformsh/platformsh-cli
src/Command/Mount/MountCommandBase.php
MountCommandBase.validateDirectory
protected function validateDirectory($directory, $writable = false) { if (!is_dir($directory)) { throw new \InvalidArgumentException(sprintf('Directory not found: %s', $directory)); } elseif (!is_readable($directory)) { throw new \InvalidArgumentException(sprintf('Directory not readable: %s', $directory)); } elseif ($writable && !is_writable($directory)) { throw new \InvalidArgumentException(sprintf('Directory not writable: %s', $directory)); } }
php
protected function validateDirectory($directory, $writable = false) { if (!is_dir($directory)) { throw new \InvalidArgumentException(sprintf('Directory not found: %s', $directory)); } elseif (!is_readable($directory)) { throw new \InvalidArgumentException(sprintf('Directory not readable: %s', $directory)); } elseif ($writable && !is_writable($directory)) { throw new \InvalidArgumentException(sprintf('Directory not writable: %s', $directory)); } }
[ "protected", "function", "validateDirectory", "(", "$", "directory", ",", "$", "writable", "=", "false", ")", "{", "if", "(", "!", "is_dir", "(", "$", "directory", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Dire...
Validate a directory argument. @param string $directory @param bool $writable
[ "Validate", "a", "directory", "argument", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Mount/MountCommandBase.php#L55-L64
platformsh/platformsh-cli
src/Command/Mount/MountCommandBase.php
MountCommandBase.runSync
protected function runSync($appName, $mountPath, $localPath, $up, array $options = []) { /** @var \Platformsh\Cli\Service\Shell $shell */ $shell = $this->getService('shell'); $sshUrl = $this->getSelectedEnvironment() ->getSshUrl($appName); $params = ['rsync', '--archive', '--compress', '--human-readable']; if ($this->stdErr->isVeryVerbose()) { $params[] = '-vv'; } elseif (!$this->stdErr->isQuiet()) { $params[] = '-v'; } if ($up) { $params[] = rtrim($localPath, '/') . '/'; $params[] = sprintf('%s:%s', $sshUrl, $mountPath); } else { $params[] = sprintf('%s:%s/', $sshUrl, $mountPath); $params[] = $localPath; } if (!empty($options['delete'])) { $params[] = '--delete'; } foreach (['exclude', 'include'] as $option) { if (!empty($options[$option])) { foreach ($options[$option] as $value) { $params[] = '--' . $option . '=' . $value; } } } $start = microtime(true); $shell->execute($params, null, true, false, [], null); $this->stdErr->writeln(sprintf(' time: %ss', number_format(microtime(true) - $start, 2)), OutputInterface::VERBOSITY_NORMAL); if ($up) { $this->stdErr->writeln('The upload completed successfully.'); } else { $this->stdErr->writeln('The download completed successfully.'); } }
php
protected function runSync($appName, $mountPath, $localPath, $up, array $options = []) { /** @var \Platformsh\Cli\Service\Shell $shell */ $shell = $this->getService('shell'); $sshUrl = $this->getSelectedEnvironment() ->getSshUrl($appName); $params = ['rsync', '--archive', '--compress', '--human-readable']; if ($this->stdErr->isVeryVerbose()) { $params[] = '-vv'; } elseif (!$this->stdErr->isQuiet()) { $params[] = '-v'; } if ($up) { $params[] = rtrim($localPath, '/') . '/'; $params[] = sprintf('%s:%s', $sshUrl, $mountPath); } else { $params[] = sprintf('%s:%s/', $sshUrl, $mountPath); $params[] = $localPath; } if (!empty($options['delete'])) { $params[] = '--delete'; } foreach (['exclude', 'include'] as $option) { if (!empty($options[$option])) { foreach ($options[$option] as $value) { $params[] = '--' . $option . '=' . $value; } } } $start = microtime(true); $shell->execute($params, null, true, false, [], null); $this->stdErr->writeln(sprintf(' time: %ss', number_format(microtime(true) - $start, 2)), OutputInterface::VERBOSITY_NORMAL); if ($up) { $this->stdErr->writeln('The upload completed successfully.'); } else { $this->stdErr->writeln('The download completed successfully.'); } }
[ "protected", "function", "runSync", "(", "$", "appName", ",", "$", "mountPath", ",", "$", "localPath", ",", "$", "up", ",", "array", "$", "options", "=", "[", "]", ")", "{", "/** @var \\Platformsh\\Cli\\Service\\Shell $shell */", "$", "shell", "=", "$", "thi...
Push the local contents to the chosen mount. @param string $appName @param string $mountPath @param string $localPath @param bool $up @param array $options
[ "Push", "the", "local", "contents", "to", "the", "chosen", "mount", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Mount/MountCommandBase.php#L75-L120
platformsh/platformsh-cli
src/Service/SelfUpdater.php
SelfUpdater.update
public function update($manifestUrl = null, $currentVersion = null) { $currentVersion = $currentVersion ?: $this->config->getVersion(); $manifestUrl = $manifestUrl ?: $this->config->get('application.manifest_url'); $applicationName = $this->config->get('application.name'); if (!extension_loaded('Phar') || !($localPhar = \Phar::running(false))) { $this->stdErr->writeln(sprintf( 'This instance of the %s was not installed as a Phar archive.', $applicationName )); // Instructions for users who are running a global Composer install. if (defined('CLI_ROOT') && file_exists(CLI_ROOT . '/../../autoload.php')) { $this->stdErr->writeln("Update using:\n\n composer global update"); $this->stdErr->writeln("\nOr you can switch to a Phar install (<options=bold>recommended</>):\n"); $this->stdErr->writeln(" composer global remove " . $this->config->get('application.package_name')); $this->stdErr->writeln(" curl -sS " . $this->config->get('application.installer_url') . " | php\n"); } return false; } $this->stdErr->writeln(sprintf( 'Checking for %s updates (current version: <info>%s</info>)', $applicationName, $currentVersion )); if (!is_writable($localPhar)) { $this->stdErr->writeln('Cannot update as the Phar file is not writable: ' . $localPhar); return false; } $updater = new Updater($localPhar, false); $strategy = new ManifestStrategy(ltrim($currentVersion, 'v'), $manifestUrl, $this->allowMajor, $this->allowUnstable); $strategy->setManifestTimeout($this->timeout); $updater->setStrategyObject($strategy); if (!$updater->hasUpdate()) { $this->stdErr->writeln('No updates found'); return false; } $newVersionString = $updater->getNewVersion(); if ($notes = $strategy->getUpdateNotes($updater)) { $this->stdErr->writeln(''); $this->stdErr->writeln(sprintf('Version <info>%s</info> is available. Update notes:', $newVersionString)); $this->stdErr->writeln(preg_replace('/^/m', ' ', $notes)); $this->stdErr->writeln(''); } if (!$this->questionHelper->confirm(sprintf('Update to version %s?', $newVersionString))) { return false; } $this->stdErr->writeln(sprintf('Updating to version %s', $newVersionString)); $updater->update(); $this->stdErr->writeln(sprintf( 'The %s has been successfully updated to version <info>%s</info>', $applicationName, $newVersionString )); return $newVersionString; }
php
public function update($manifestUrl = null, $currentVersion = null) { $currentVersion = $currentVersion ?: $this->config->getVersion(); $manifestUrl = $manifestUrl ?: $this->config->get('application.manifest_url'); $applicationName = $this->config->get('application.name'); if (!extension_loaded('Phar') || !($localPhar = \Phar::running(false))) { $this->stdErr->writeln(sprintf( 'This instance of the %s was not installed as a Phar archive.', $applicationName )); // Instructions for users who are running a global Composer install. if (defined('CLI_ROOT') && file_exists(CLI_ROOT . '/../../autoload.php')) { $this->stdErr->writeln("Update using:\n\n composer global update"); $this->stdErr->writeln("\nOr you can switch to a Phar install (<options=bold>recommended</>):\n"); $this->stdErr->writeln(" composer global remove " . $this->config->get('application.package_name')); $this->stdErr->writeln(" curl -sS " . $this->config->get('application.installer_url') . " | php\n"); } return false; } $this->stdErr->writeln(sprintf( 'Checking for %s updates (current version: <info>%s</info>)', $applicationName, $currentVersion )); if (!is_writable($localPhar)) { $this->stdErr->writeln('Cannot update as the Phar file is not writable: ' . $localPhar); return false; } $updater = new Updater($localPhar, false); $strategy = new ManifestStrategy(ltrim($currentVersion, 'v'), $manifestUrl, $this->allowMajor, $this->allowUnstable); $strategy->setManifestTimeout($this->timeout); $updater->setStrategyObject($strategy); if (!$updater->hasUpdate()) { $this->stdErr->writeln('No updates found'); return false; } $newVersionString = $updater->getNewVersion(); if ($notes = $strategy->getUpdateNotes($updater)) { $this->stdErr->writeln(''); $this->stdErr->writeln(sprintf('Version <info>%s</info> is available. Update notes:', $newVersionString)); $this->stdErr->writeln(preg_replace('/^/m', ' ', $notes)); $this->stdErr->writeln(''); } if (!$this->questionHelper->confirm(sprintf('Update to version %s?', $newVersionString))) { return false; } $this->stdErr->writeln(sprintf('Updating to version %s', $newVersionString)); $updater->update(); $this->stdErr->writeln(sprintf( 'The %s has been successfully updated to version <info>%s</info>', $applicationName, $newVersionString )); return $newVersionString; }
[ "public", "function", "update", "(", "$", "manifestUrl", "=", "null", ",", "$", "currentVersion", "=", "null", ")", "{", "$", "currentVersion", "=", "$", "currentVersion", "?", ":", "$", "this", "->", "config", "->", "getVersion", "(", ")", ";", "$", "...
Run the update. @param string|null $manifestUrl @param string|null $currentVersion @return false|string The new version number, or false if there was no update.
[ "Run", "the", "update", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/SelfUpdater.php#L85-L153
platformsh/platformsh-cli
src/Service/Table.php
Table.configureInput
public static function configureInput(InputDefinition $definition) { $description = 'The output format ("table", "csv", or "tsv")'; $option = new InputOption('format', null, InputOption::VALUE_REQUIRED, $description, 'table'); $definition->addOption($option); $description = 'Columns to display (comma-separated list, or multiple values)'; $option = new InputOption('columns', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, $description); $definition->addOption($option); $description = 'Do not output the table header'; $option = new InputOption('no-header', null, InputOption::VALUE_NONE, $description); $definition->addOption($option); }
php
public static function configureInput(InputDefinition $definition) { $description = 'The output format ("table", "csv", or "tsv")'; $option = new InputOption('format', null, InputOption::VALUE_REQUIRED, $description, 'table'); $definition->addOption($option); $description = 'Columns to display (comma-separated list, or multiple values)'; $option = new InputOption('columns', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, $description); $definition->addOption($option); $description = 'Do not output the table header'; $option = new InputOption('no-header', null, InputOption::VALUE_NONE, $description); $definition->addOption($option); }
[ "public", "static", "function", "configureInput", "(", "InputDefinition", "$", "definition", ")", "{", "$", "description", "=", "'The output format (\"table\", \"csv\", or \"tsv\")'", ";", "$", "option", "=", "new", "InputOption", "(", "'format'", ",", "null", ",", ...
Add the --format and --columns options to a command's input definition. @param InputDefinition $definition
[ "Add", "the", "--", "format", "and", "--", "columns", "options", "to", "a", "command", "s", "input", "definition", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Table.php#L51-L62
platformsh/platformsh-cli
src/Service/Table.php
Table.renderSimple
public function renderSimple(array $values, array $propertyNames) { $data = []; foreach ($propertyNames as $key => $label) { $data[] = [$label, $values[$key]]; } $this->render($data, ['Property', 'Value']); }
php
public function renderSimple(array $values, array $propertyNames) { $data = []; foreach ($propertyNames as $key => $label) { $data[] = [$label, $values[$key]]; } $this->render($data, ['Property', 'Value']); }
[ "public", "function", "renderSimple", "(", "array", "$", "values", ",", "array", "$", "propertyNames", ")", "{", "$", "data", "=", "[", "]", ";", "foreach", "(", "$", "propertyNames", "as", "$", "key", "=>", "$", "label", ")", "{", "$", "data", "[", ...
Render an single-dimensional array of values, with their property names. @param string[] $values @param string[] $propertyNames
[ "Render", "an", "single", "-", "dimensional", "array", "of", "values", "with", "their", "property", "names", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Table.php#L70-L77
platformsh/platformsh-cli
src/Service/Table.php
Table.render
public function render(array $rows, array $header = [], $defaultColumns = []) { $format = $this->getFormat(); $columnsToDisplay = $this->columnsToDisplay() ?: $defaultColumns; $rows = $this->filterColumns($rows, $header, $columnsToDisplay); $header = $this->filterColumns([0 => $header], $header, $columnsToDisplay)[0]; if ($this->input->hasOption('no-header') && $this->input->getOption('no-header')) { $header = []; } switch ($format) { case 'csv': $this->renderCsv($rows, $header); break; case 'tsv': $this->renderCsv($rows, $header, "\t"); break; case null: case 'table': $this->renderTable($rows, $header); break; default: throw new InvalidArgumentException(sprintf('Invalid format: %s', $format)); } }
php
public function render(array $rows, array $header = [], $defaultColumns = []) { $format = $this->getFormat(); $columnsToDisplay = $this->columnsToDisplay() ?: $defaultColumns; $rows = $this->filterColumns($rows, $header, $columnsToDisplay); $header = $this->filterColumns([0 => $header], $header, $columnsToDisplay)[0]; if ($this->input->hasOption('no-header') && $this->input->getOption('no-header')) { $header = []; } switch ($format) { case 'csv': $this->renderCsv($rows, $header); break; case 'tsv': $this->renderCsv($rows, $header, "\t"); break; case null: case 'table': $this->renderTable($rows, $header); break; default: throw new InvalidArgumentException(sprintf('Invalid format: %s', $format)); } }
[ "public", "function", "render", "(", "array", "$", "rows", ",", "array", "$", "header", "=", "[", "]", ",", "$", "defaultColumns", "=", "[", "]", ")", "{", "$", "format", "=", "$", "this", "->", "getFormat", "(", ")", ";", "$", "columnsToDisplay", ...
Render a table of data to output. @param array $rows The table rows. @param string[] $header The table header (optional). @param string[] $defaultColumns Default columns to display (optional). Columns are identified by their name in $header, or alternatively by their key in $rows.
[ "Render", "a", "table", "of", "data", "to", "output", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Table.php#L90-L119
platformsh/platformsh-cli
src/Service/Table.php
Table.columnsToDisplay
protected function columnsToDisplay() { if (!$this->input->hasOption('columns')) { return []; } $columns = $this->input->getOption('columns'); if (count($columns) === 1) { $columns = preg_split('/\s*,\s*/', $columns[0]); } return $columns; }
php
protected function columnsToDisplay() { if (!$this->input->hasOption('columns')) { return []; } $columns = $this->input->getOption('columns'); if (count($columns) === 1) { $columns = preg_split('/\s*,\s*/', $columns[0]); } return $columns; }
[ "protected", "function", "columnsToDisplay", "(", ")", "{", "if", "(", "!", "$", "this", "->", "input", "->", "hasOption", "(", "'columns'", ")", ")", "{", "return", "[", "]", ";", "}", "$", "columns", "=", "$", "this", "->", "input", "->", "getOptio...
Get the columns specified by the user. @return array
[ "Get", "the", "columns", "specified", "by", "the", "user", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Table.php#L138-L149
platformsh/platformsh-cli
src/Service/Table.php
Table.filterColumns
private function filterColumns(array $rows, array $header, array $columnsToDisplay) { if (empty($columnsToDisplay)) { return $rows; } // The available columns are all the (lower-cased) values and string // keys in $header. $availableColumns = []; foreach ($header as $key => $column) { $columnName = is_string($key) ? $key : $column; $availableColumns[strtolower($columnName)] = $key; } // Validate the column names. foreach ($columnsToDisplay as &$columnName) { $columnNameLowered = strtolower($columnName); if (!isset($availableColumns[$columnNameLowered])) { throw new InvalidArgumentException( sprintf('Column not found: %s (available columns: %s)', $columnName, implode(', ', array_keys($availableColumns))) ); } $columnName = $columnNameLowered; } // Filter the rows for keys matching those in $availableColumns. If a // key doesn't exist in a row, then the cell will be an empty string. $newRows = []; foreach ($rows as $row) { $newRow = []; foreach ($columnsToDisplay as $columnNameLowered) { $key = $availableColumns[$columnNameLowered]; $newRow[] = array_key_exists($key, $row) ? $row[$key] : ''; } $newRows[] = $newRow; } return $newRows; }
php
private function filterColumns(array $rows, array $header, array $columnsToDisplay) { if (empty($columnsToDisplay)) { return $rows; } // The available columns are all the (lower-cased) values and string // keys in $header. $availableColumns = []; foreach ($header as $key => $column) { $columnName = is_string($key) ? $key : $column; $availableColumns[strtolower($columnName)] = $key; } // Validate the column names. foreach ($columnsToDisplay as &$columnName) { $columnNameLowered = strtolower($columnName); if (!isset($availableColumns[$columnNameLowered])) { throw new InvalidArgumentException( sprintf('Column not found: %s (available columns: %s)', $columnName, implode(', ', array_keys($availableColumns))) ); } $columnName = $columnNameLowered; } // Filter the rows for keys matching those in $availableColumns. If a // key doesn't exist in a row, then the cell will be an empty string. $newRows = []; foreach ($rows as $row) { $newRow = []; foreach ($columnsToDisplay as $columnNameLowered) { $key = $availableColumns[$columnNameLowered]; $newRow[] = array_key_exists($key, $row) ? $row[$key] : ''; } $newRows[] = $newRow; } return $newRows; }
[ "private", "function", "filterColumns", "(", "array", "$", "rows", ",", "array", "$", "header", ",", "array", "$", "columnsToDisplay", ")", "{", "if", "(", "empty", "(", "$", "columnsToDisplay", ")", ")", "{", "return", "$", "rows", ";", "}", "// The ava...
Filter rows by column names. @param array $rows @param array $header @param string[] $columnsToDisplay @return array
[ "Filter", "rows", "by", "column", "names", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Table.php#L160-L198
platformsh/platformsh-cli
src/Service/Table.php
Table.getFormat
protected function getFormat() { if ($this->input->hasOption('format') && $this->input->getOption('format')) { return strtolower($this->input->getOption('format')); } return null; }
php
protected function getFormat() { if ($this->input->hasOption('format') && $this->input->getOption('format')) { return strtolower($this->input->getOption('format')); } return null; }
[ "protected", "function", "getFormat", "(", ")", "{", "if", "(", "$", "this", "->", "input", "->", "hasOption", "(", "'format'", ")", "&&", "$", "this", "->", "input", "->", "getOption", "(", "'format'", ")", ")", "{", "return", "strtolower", "(", "$", ...
Get the user-specified format. @return string|null
[ "Get", "the", "user", "-", "specified", "format", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Table.php#L205-L212
platformsh/platformsh-cli
src/Service/Table.php
Table.renderCsv
protected function renderCsv(array $rows, array $header, $delimiter = ',') { if (!empty($header)) { array_unshift($rows, $header); } // RFC 4180 (the closest thing to a CSV standard) asks for CRLF line // breaks, but these do not play nicely with POSIX shells whose // default internal field separator (IFS) does not account for CR. So // the line break character is forced as LF. $this->output->write((new Csv($delimiter, "\n"))->format($rows)); }
php
protected function renderCsv(array $rows, array $header, $delimiter = ',') { if (!empty($header)) { array_unshift($rows, $header); } // RFC 4180 (the closest thing to a CSV standard) asks for CRLF line // breaks, but these do not play nicely with POSIX shells whose // default internal field separator (IFS) does not account for CR. So // the line break character is forced as LF. $this->output->write((new Csv($delimiter, "\n"))->format($rows)); }
[ "protected", "function", "renderCsv", "(", "array", "$", "rows", ",", "array", "$", "header", ",", "$", "delimiter", "=", "','", ")", "{", "if", "(", "!", "empty", "(", "$", "header", ")", ")", "{", "array_unshift", "(", "$", "rows", ",", "$", "hea...
Render CSV output. @param array $rows @param array $header @param string $delimiter
[ "Render", "CSV", "output", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Table.php#L221-L231
platformsh/platformsh-cli
src/Service/Table.php
Table.renderTable
protected function renderTable(array $rows, array $header) { $table = new AdaptiveTable($this->output); $table->setHeaders($header); $table->setRows($rows); $table->render(); }
php
protected function renderTable(array $rows, array $header) { $table = new AdaptiveTable($this->output); $table->setHeaders($header); $table->setRows($rows); $table->render(); }
[ "protected", "function", "renderTable", "(", "array", "$", "rows", ",", "array", "$", "header", ")", "{", "$", "table", "=", "new", "AdaptiveTable", "(", "$", "this", "->", "output", ")", ";", "$", "table", "->", "setHeaders", "(", "$", "header", ")", ...
Render a Symfony Console table. @param array $rows @param array $header
[ "Render", "a", "Symfony", "Console", "table", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Table.php#L239-L245
platformsh/platformsh-cli
src/Service/GitDataApi.php
GitDataApi.parseParents
private function parseParents($sha) { if (!strpos($sha, '^') && !strpos($sha, '~')) { return []; } preg_match_all('#[\^~][0-9]*#', $sha, $matches); $parents = []; foreach ($matches[0] as $match) { $sign = $match[0]; $number = intval(substr($match, 1) ?: 1); if ($sign === '~') { for ($i = 1; $i <= $number; $i++) { $parents[] = 1; } } elseif ($sign === '^') { $parents[] = intval($number); } } return $parents; }
php
private function parseParents($sha) { if (!strpos($sha, '^') && !strpos($sha, '~')) { return []; } preg_match_all('#[\^~][0-9]*#', $sha, $matches); $parents = []; foreach ($matches[0] as $match) { $sign = $match[0]; $number = intval(substr($match, 1) ?: 1); if ($sign === '~') { for ($i = 1; $i <= $number; $i++) { $parents[] = 1; } } elseif ($sign === '^') { $parents[] = intval($number); } } return $parents; }
[ "private", "function", "parseParents", "(", "$", "sha", ")", "{", "if", "(", "!", "strpos", "(", "$", "sha", ",", "'^'", ")", "&&", "!", "strpos", "(", "$", "sha", ",", "'~'", ")", ")", "{", "return", "[", "]", ";", "}", "preg_match_all", "(", ...
Parse the parents in a Git commit spec. @param string $sha @return int[] A list of parents.
[ "Parse", "the", "parents", "in", "a", "Git", "commit", "spec", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/GitDataApi.php#L35-L55
platformsh/platformsh-cli
src/Service/GitDataApi.php
GitDataApi.getCommit
public function getCommit(Environment $environment, $sha = null) { $sha = $this->normalizeSha($environment, $sha); if ($sha === null) { return false; } $parents = $this->parseParents($sha); $sha = preg_replace('/[\^~].*$/', '', $sha); // Get the first commit. $commit = $this->getCommitByShaHash($environment, $sha); if (!$commit) { return false; } // Fetch parent commits recursively. while ($commit !== false && count($parents)) { $parent = array_shift($parents); if (isset($commit->parents[$parent - 1])) { $commit = $this->getCommitByShaHash($environment, $commit->parents[$parent - 1]); } else { return false; } } return $commit; }
php
public function getCommit(Environment $environment, $sha = null) { $sha = $this->normalizeSha($environment, $sha); if ($sha === null) { return false; } $parents = $this->parseParents($sha); $sha = preg_replace('/[\^~].*$/', '', $sha); // Get the first commit. $commit = $this->getCommitByShaHash($environment, $sha); if (!$commit) { return false; } // Fetch parent commits recursively. while ($commit !== false && count($parents)) { $parent = array_shift($parents); if (isset($commit->parents[$parent - 1])) { $commit = $this->getCommitByShaHash($environment, $commit->parents[$parent - 1]); } else { return false; } } return $commit; }
[ "public", "function", "getCommit", "(", "Environment", "$", "environment", ",", "$", "sha", "=", "null", ")", "{", "$", "sha", "=", "$", "this", "->", "normalizeSha", "(", "$", "environment", ",", "$", "sha", ")", ";", "if", "(", "$", "sha", "===", ...
Get a Git Commit object for an environment. @param \Platformsh\Client\Model\Environment $environment @param string|null $sha @return \Platformsh\Client\Model\Git\Commit|false
[ "Get", "a", "Git", "Commit", "object", "for", "an", "environment", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/GitDataApi.php#L65-L92
platformsh/platformsh-cli
src/Service/GitDataApi.php
GitDataApi.getCommitByShaHash
private function getCommitByShaHash(Environment $environment, $sha) { $cacheKey = $environment->project . ':' . $sha; $client = $this->api->getHttpClient(); if ($cached = $this->cache->fetch($cacheKey)) { return new Commit($cached['data'], $cached['uri'], $client, true); } $baseUrl = Project::getProjectBaseFromUrl($environment->getUri()) . '/git/commits'; $commit = \Platformsh\Client\Model\Git\Commit::get($sha, $baseUrl, $client); if ($commit === false) { return false; } $data = $commit->getData(); // No need to cache API metadata. if (isset($data['_links']['self']['meta'])) { unset($data['_links']['self']['meta']); } $this->cache->save($cacheKey, [ 'data' => $data, 'uri' => $baseUrl, ], 0); return $commit; }
php
private function getCommitByShaHash(Environment $environment, $sha) { $cacheKey = $environment->project . ':' . $sha; $client = $this->api->getHttpClient(); if ($cached = $this->cache->fetch($cacheKey)) { return new Commit($cached['data'], $cached['uri'], $client, true); } $baseUrl = Project::getProjectBaseFromUrl($environment->getUri()) . '/git/commits'; $commit = \Platformsh\Client\Model\Git\Commit::get($sha, $baseUrl, $client); if ($commit === false) { return false; } $data = $commit->getData(); // No need to cache API metadata. if (isset($data['_links']['self']['meta'])) { unset($data['_links']['self']['meta']); } $this->cache->save($cacheKey, [ 'data' => $data, 'uri' => $baseUrl, ], 0); return $commit; }
[ "private", "function", "getCommitByShaHash", "(", "Environment", "$", "environment", ",", "$", "sha", ")", "{", "$", "cacheKey", "=", "$", "environment", "->", "project", ".", "':'", ".", "$", "sha", ";", "$", "client", "=", "$", "this", "->", "api", "...
Get a specific commit from the API. @param Environment $environment @param string $sha The "pure" commit SHA hash. @return \Platformsh\Client\Model\Git\Commit|false
[ "Get", "a", "specific", "commit", "from", "the", "API", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/GitDataApi.php#L102-L125
platformsh/platformsh-cli
src/Service/GitDataApi.php
GitDataApi.normalizeSha
private function normalizeSha(Environment $environment, $sha = null) { if ($environment->head_commit === null) { return null; } if ($sha === null) { return $environment->head_commit; } if (strpos($sha, 'HEAD') === 0) { $sha = $environment->head_commit . substr($sha, 4); } return $sha; }
php
private function normalizeSha(Environment $environment, $sha = null) { if ($environment->head_commit === null) { return null; } if ($sha === null) { return $environment->head_commit; } if (strpos($sha, 'HEAD') === 0) { $sha = $environment->head_commit . substr($sha, 4); } return $sha; }
[ "private", "function", "normalizeSha", "(", "Environment", "$", "environment", ",", "$", "sha", "=", "null", ")", "{", "if", "(", "$", "environment", "->", "head_commit", "===", "null", ")", "{", "return", "null", ";", "}", "if", "(", "$", "sha", "==="...
Normalize a commit SHA for API and caching purposes. @param \Platformsh\Client\Model\Environment $environment @param string|null $sha @return string|null
[ "Normalize", "a", "commit", "SHA", "for", "API", "and", "caching", "purposes", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/GitDataApi.php#L135-L148
platformsh/platformsh-cli
src/Service/GitDataApi.php
GitDataApi.readFile
public function readFile($filename, Environment $environment, $commitSha = null) { $commitSha = $this->normalizeSha($environment, $commitSha); $cacheKey = implode(':', ['raw', $environment->project, $filename, $commitSha]); $data = $this->cache->fetch($cacheKey); if (!is_array($data)) { // Find the file. if (($tree = $this->getTree($environment, dirname($filename), $commitSha)) && ($blob = $tree->getBlob(basename($filename)))) { $raw = $blob->getRawContent(); } else { $raw = false; } $data = ['raw' => $raw]; // Skip caching if the file is bigger than 100 KiB. if ($raw === false || strlen($raw) <= 102400) { $this->cache->save($cacheKey, $data); } } return $data['raw']; }
php
public function readFile($filename, Environment $environment, $commitSha = null) { $commitSha = $this->normalizeSha($environment, $commitSha); $cacheKey = implode(':', ['raw', $environment->project, $filename, $commitSha]); $data = $this->cache->fetch($cacheKey); if (!is_array($data)) { // Find the file. if (($tree = $this->getTree($environment, dirname($filename), $commitSha)) && ($blob = $tree->getBlob(basename($filename)))) { $raw = $blob->getRawContent(); } else { $raw = false; } $data = ['raw' => $raw]; // Skip caching if the file is bigger than 100 KiB. if ($raw === false || strlen($raw) <= 102400) { $this->cache->save($cacheKey, $data); } } return $data['raw']; }
[ "public", "function", "readFile", "(", "$", "filename", ",", "Environment", "$", "environment", ",", "$", "commitSha", "=", "null", ")", "{", "$", "commitSha", "=", "$", "this", "->", "normalizeSha", "(", "$", "environment", ",", "$", "commitSha", ")", "...
Read a file in the environment, using the Git Data API. @param string $filename @param Environment $environment @param string|null $commitSha @throws \RuntimeException on error. @return string|false The raw contents of the file, or false if the file is not found.
[ "Read", "a", "file", "in", "the", "environment", "using", "the", "Git", "Data", "API", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/GitDataApi.php#L162-L183
platformsh/platformsh-cli
src/Service/GitDataApi.php
GitDataApi.getTree
public function getTree(Environment $environment, $path = '.', $commitSha = null) { $normalizedSha = $this->normalizeSha($environment, $commitSha); $cacheKey = implode(':', ['tree', $environment->project, $path, $normalizedSha]); $data = $this->cache->fetch($cacheKey); if (!is_array($data)) { if (!$commit = $this->getCommit($environment, $normalizedSha)) { throw new \InvalidArgumentException(sprintf( 'Commit not found: %s', $commitSha )); } if (!$rootTree = $commit->getTree()) { // This is unlikely to happen. throw new \RuntimeException('Failed to get tree for commit: ' . $commit->id); } $tree = $rootTree->getTree($path); $this->cache->save($cacheKey, [ 'tree' => $tree ? $tree->getData() : null, 'uri' => $tree ? $tree->getUri() : null, ]); } elseif (empty($data['tree'])) { return false; } else { $tree = new Tree($data['tree'], $data['uri'], $this->api->getHttpClient(), true); } return $tree; }
php
public function getTree(Environment $environment, $path = '.', $commitSha = null) { $normalizedSha = $this->normalizeSha($environment, $commitSha); $cacheKey = implode(':', ['tree', $environment->project, $path, $normalizedSha]); $data = $this->cache->fetch($cacheKey); if (!is_array($data)) { if (!$commit = $this->getCommit($environment, $normalizedSha)) { throw new \InvalidArgumentException(sprintf( 'Commit not found: %s', $commitSha )); } if (!$rootTree = $commit->getTree()) { // This is unlikely to happen. throw new \RuntimeException('Failed to get tree for commit: ' . $commit->id); } $tree = $rootTree->getTree($path); $this->cache->save($cacheKey, [ 'tree' => $tree ? $tree->getData() : null, 'uri' => $tree ? $tree->getUri() : null, ]); } elseif (empty($data['tree'])) { return false; } else { $tree = new Tree($data['tree'], $data['uri'], $this->api->getHttpClient(), true); } return $tree; }
[ "public", "function", "getTree", "(", "Environment", "$", "environment", ",", "$", "path", "=", "'.'", ",", "$", "commitSha", "=", "null", ")", "{", "$", "normalizedSha", "=", "$", "this", "->", "normalizeSha", "(", "$", "environment", ",", "$", "commitS...
Get a Git Tree object (a repository directory) for an environment. @param Environment $environment @param string $path @param string|null $commitSha @return Tree|false
[ "Get", "a", "Git", "Tree", "object", "(", "a", "repository", "directory", ")", "for", "an", "environment", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/GitDataApi.php#L194-L222
platformsh/platformsh-cli
src/Service/CacheFactory.php
CacheFactory.createCacheProvider
public static function createCacheProvider(Config $cliConfig) { if (!empty($cliConfig->get('api.disable_cache'))) { return new VoidCache(); } return new FilesystemCache( $cliConfig->getWritableUserDir() . '/cache', FilesystemCache::EXTENSION, 0077 // Remove all permissions from the group and others. ); }
php
public static function createCacheProvider(Config $cliConfig) { if (!empty($cliConfig->get('api.disable_cache'))) { return new VoidCache(); } return new FilesystemCache( $cliConfig->getWritableUserDir() . '/cache', FilesystemCache::EXTENSION, 0077 // Remove all permissions from the group and others. ); }
[ "public", "static", "function", "createCacheProvider", "(", "Config", "$", "cliConfig", ")", "{", "if", "(", "!", "empty", "(", "$", "cliConfig", "->", "get", "(", "'api.disable_cache'", ")", ")", ")", "{", "return", "new", "VoidCache", "(", ")", ";", "}...
@param \Platformsh\Cli\Service\Config $cliConfig @return \Doctrine\Common\Cache\CacheProvider
[ "@param", "\\", "Platformsh", "\\", "Cli", "\\", "Service", "\\", "Config", "$cliConfig" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/CacheFactory.php#L16-L27
platformsh/platformsh-cli
src/Command/Environment/EnvironmentListCommand.php
EnvironmentListCommand.configure
protected function configure() { $this ->setName('environment:list') ->setAliases(['environments', 'env']) ->setDescription('Get a list of environments') ->addOption('no-inactive', 'I', InputOption::VALUE_NONE, 'Do not show inactive environments') ->addOption('pipe', null, InputOption::VALUE_NONE, 'Output a simple list of environment IDs.') ->addOption('refresh', null, InputOption::VALUE_REQUIRED, 'Whether to refresh the list.', 1) ->addOption('sort', null, InputOption::VALUE_REQUIRED, 'A property to sort by', 'title') ->addOption('reverse', null, InputOption::VALUE_NONE, 'Sort in reverse (descending) order'); Table::configureInput($this->getDefinition()); $this->addProjectOption(); }
php
protected function configure() { $this ->setName('environment:list') ->setAliases(['environments', 'env']) ->setDescription('Get a list of environments') ->addOption('no-inactive', 'I', InputOption::VALUE_NONE, 'Do not show inactive environments') ->addOption('pipe', null, InputOption::VALUE_NONE, 'Output a simple list of environment IDs.') ->addOption('refresh', null, InputOption::VALUE_REQUIRED, 'Whether to refresh the list.', 1) ->addOption('sort', null, InputOption::VALUE_REQUIRED, 'A property to sort by', 'title') ->addOption('reverse', null, InputOption::VALUE_NONE, 'Sort in reverse (descending) order'); Table::configureInput($this->getDefinition()); $this->addProjectOption(); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'environment:list'", ")", "->", "setAliases", "(", "[", "'environments'", ",", "'env'", "]", ")", "->", "setDescription", "(", "'Get a list of environments'", ")", "->", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentListCommand.php#L27-L40
platformsh/platformsh-cli
src/Command/Environment/EnvironmentListCommand.php
EnvironmentListCommand.buildEnvironmentTree
protected function buildEnvironmentTree(array $environments, $parent = null) { $children = []; foreach ($environments as $environment) { // Root nodes are both the environments whose parent is null, and // environments whose parent does not exist. if ($environment->parent === $parent || ($parent === null && !isset($environments[$environment->parent]))) { $this->children[$environment->id] = $this->buildEnvironmentTree( $environments, $environment->id ); $children[$environment->id] = $environment; } } return $children; }
php
protected function buildEnvironmentTree(array $environments, $parent = null) { $children = []; foreach ($environments as $environment) { // Root nodes are both the environments whose parent is null, and // environments whose parent does not exist. if ($environment->parent === $parent || ($parent === null && !isset($environments[$environment->parent]))) { $this->children[$environment->id] = $this->buildEnvironmentTree( $environments, $environment->id ); $children[$environment->id] = $environment; } } return $children; }
[ "protected", "function", "buildEnvironmentTree", "(", "array", "$", "environments", ",", "$", "parent", "=", "null", ")", "{", "$", "children", "=", "[", "]", ";", "foreach", "(", "$", "environments", "as", "$", "environment", ")", "{", "// Root nodes are bo...
Build a tree out of a list of environments. @param Environment[] $environments The list of environments, keyed by ID. @param string|null $parent The parent environment for which to build a tree. @return Environment[] A list of the children of $parent, keyed by ID. Children of all environments are stored in the property $this->children.
[ "Build", "a", "tree", "out", "of", "a", "list", "of", "environments", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentListCommand.php#L53-L70
platformsh/platformsh-cli
src/Command/Environment/EnvironmentListCommand.php
EnvironmentListCommand.buildEnvironmentRows
protected function buildEnvironmentRows(array $tree, $indent = true, $indicateCurrent = true, $indentAmount = 0) { $rows = []; foreach ($tree as $environment) { $row = []; // Format the environment ID. $id = $environment->id; if ($indent) { $id = str_repeat(' ', $indentAmount) . $id; } // Add an indicator for the current environment. $cellOptions = []; if ($indicateCurrent && $this->currentEnvironment && $environment->id == $this->currentEnvironment->id) { $id .= '<info>*</info>'; // Prevent table cell wrapping so formatting is not broken. $cellOptions['wrap'] = false; } $row[] = new AdaptiveTableCell($id, $cellOptions); if ($branch = array_search($environment->id, $this->mapping)) { $row[] = sprintf('%s (%s)', $environment->title, $branch); } else { $row[] = $environment->title; } $row[] = $this->formatEnvironmentStatus($environment->status); $row[] = $this->formatter->format($environment->created_at, 'created_at'); $row[] = $this->formatter->format($environment->updated_at, 'updated_at'); $rows[] = $row; if (isset($this->children[$environment->id])) { $childRows = $this->buildEnvironmentRows( $this->children[$environment->id], $indent, $indicateCurrent, $indentAmount + 1 ); $rows = array_merge($rows, $childRows); } } return $rows; }
php
protected function buildEnvironmentRows(array $tree, $indent = true, $indicateCurrent = true, $indentAmount = 0) { $rows = []; foreach ($tree as $environment) { $row = []; // Format the environment ID. $id = $environment->id; if ($indent) { $id = str_repeat(' ', $indentAmount) . $id; } // Add an indicator for the current environment. $cellOptions = []; if ($indicateCurrent && $this->currentEnvironment && $environment->id == $this->currentEnvironment->id) { $id .= '<info>*</info>'; // Prevent table cell wrapping so formatting is not broken. $cellOptions['wrap'] = false; } $row[] = new AdaptiveTableCell($id, $cellOptions); if ($branch = array_search($environment->id, $this->mapping)) { $row[] = sprintf('%s (%s)', $environment->title, $branch); } else { $row[] = $environment->title; } $row[] = $this->formatEnvironmentStatus($environment->status); $row[] = $this->formatter->format($environment->created_at, 'created_at'); $row[] = $this->formatter->format($environment->updated_at, 'updated_at'); $rows[] = $row; if (isset($this->children[$environment->id])) { $childRows = $this->buildEnvironmentRows( $this->children[$environment->id], $indent, $indicateCurrent, $indentAmount + 1 ); $rows = array_merge($rows, $childRows); } } return $rows; }
[ "protected", "function", "buildEnvironmentRows", "(", "array", "$", "tree", ",", "$", "indent", "=", "true", ",", "$", "indicateCurrent", "=", "true", ",", "$", "indentAmount", "=", "0", ")", "{", "$", "rows", "=", "[", "]", ";", "foreach", "(", "$", ...
Recursively build rows of the environment table. @param Environment[] $tree @param bool $indent @param int $indentAmount @param bool $indicateCurrent @return array
[ "Recursively", "build", "rows", "of", "the", "environment", "table", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentListCommand.php#L82-L129
platformsh/platformsh-cli
src/Command/Environment/EnvironmentListCommand.php
EnvironmentListCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $refresh = $input->hasOption('refresh') && $input->getOption('refresh'); $environments = $this->api()->getEnvironments($this->getSelectedProject(), $refresh ? true : null); if ($input->getOption('no-inactive')) { $environments = array_filter($environments, function ($environment) { return $environment->status !== 'inactive'; }); } if ($input->getOption('sort')) { $this->api()->sortResources($environments, $input->getOption('sort')); } if ($input->getOption('reverse')) { $environments = array_reverse($environments, true); } if ($input->getOption('pipe')) { $output->writeln(array_keys($environments)); return; } $project = $this->getSelectedProject(); $this->currentEnvironment = $this->getCurrentEnvironment($project); if (($currentProject = $this->getCurrentProject()) && $currentProject == $project) { /** @var \Platformsh\Cli\Local\LocalProject $localProject */ $localProject = $this->getService('local.project'); $projectConfig = $localProject->getProjectConfig($this->getProjectRoot()); if (isset($projectConfig['mapping'])) { $this->mapping = $projectConfig['mapping']; } } $tree = $this->buildEnvironmentTree($environments); // To make the display nicer, we move all the children of master // to the top level. if (isset($this->children['master'])) { $tree += $this->children['master']; $this->children['master'] = []; } $headers = ['ID', 'Title', 'Status', 'Created', 'Updated']; $defaultColumns = ['id', 'title', 'status']; /** @var \Platformsh\Cli\Service\Table $table */ $table = $this->getService('table'); /** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */ $this->formatter = $this->getService('property_formatter'); if ($table->formatIsMachineReadable()) { $table->render($this->buildEnvironmentRows($tree, false, false), $headers, $defaultColumns); return; } $this->stdErr->writeln("Your environments are: "); $table->render($this->buildEnvironmentRows($tree), $headers, $defaultColumns); if (!$this->currentEnvironment) { return; } $this->stdErr->writeln("<info>*</info> - Indicates the current environment\n"); $currentEnvironment = $this->currentEnvironment; $executable = $this->config()->get('application.executable'); $this->stdErr->writeln( 'Check out a different environment by running <info>' . $executable . ' checkout [id]</info>' ); if ($currentEnvironment->operationAvailable('branch')) { $this->stdErr->writeln( 'Branch a new environment by running <info>' . $executable . ' environment:branch [new-name]</info>' ); } if ($currentEnvironment->operationAvailable('activate')) { $this->stdErr->writeln( 'Activate the current environment by running <info>' . $executable . ' environment:activate</info>' ); } if ($currentEnvironment->operationAvailable('delete')) { $this->stdErr->writeln( 'Delete the current environment by running <info>' . $executable . ' environment:delete</info>' ); } if ($currentEnvironment->operationAvailable('backup')) { $this->stdErr->writeln( 'Make a snapshot of the current environment by running <info>' . $executable . ' snapshot:create</info>' ); } if ($currentEnvironment->operationAvailable('merge')) { $this->stdErr->writeln( 'Merge the current environment by running <info>' . $executable . ' environment:merge</info>' ); } if ($currentEnvironment->operationAvailable('synchronize')) { $this->stdErr->writeln( 'Sync the current environment by running <info>' . $executable . ' environment:synchronize</info>' ); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $refresh = $input->hasOption('refresh') && $input->getOption('refresh'); $environments = $this->api()->getEnvironments($this->getSelectedProject(), $refresh ? true : null); if ($input->getOption('no-inactive')) { $environments = array_filter($environments, function ($environment) { return $environment->status !== 'inactive'; }); } if ($input->getOption('sort')) { $this->api()->sortResources($environments, $input->getOption('sort')); } if ($input->getOption('reverse')) { $environments = array_reverse($environments, true); } if ($input->getOption('pipe')) { $output->writeln(array_keys($environments)); return; } $project = $this->getSelectedProject(); $this->currentEnvironment = $this->getCurrentEnvironment($project); if (($currentProject = $this->getCurrentProject()) && $currentProject == $project) { /** @var \Platformsh\Cli\Local\LocalProject $localProject */ $localProject = $this->getService('local.project'); $projectConfig = $localProject->getProjectConfig($this->getProjectRoot()); if (isset($projectConfig['mapping'])) { $this->mapping = $projectConfig['mapping']; } } $tree = $this->buildEnvironmentTree($environments); // To make the display nicer, we move all the children of master // to the top level. if (isset($this->children['master'])) { $tree += $this->children['master']; $this->children['master'] = []; } $headers = ['ID', 'Title', 'Status', 'Created', 'Updated']; $defaultColumns = ['id', 'title', 'status']; /** @var \Platformsh\Cli\Service\Table $table */ $table = $this->getService('table'); /** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */ $this->formatter = $this->getService('property_formatter'); if ($table->formatIsMachineReadable()) { $table->render($this->buildEnvironmentRows($tree, false, false), $headers, $defaultColumns); return; } $this->stdErr->writeln("Your environments are: "); $table->render($this->buildEnvironmentRows($tree), $headers, $defaultColumns); if (!$this->currentEnvironment) { return; } $this->stdErr->writeln("<info>*</info> - Indicates the current environment\n"); $currentEnvironment = $this->currentEnvironment; $executable = $this->config()->get('application.executable'); $this->stdErr->writeln( 'Check out a different environment by running <info>' . $executable . ' checkout [id]</info>' ); if ($currentEnvironment->operationAvailable('branch')) { $this->stdErr->writeln( 'Branch a new environment by running <info>' . $executable . ' environment:branch [new-name]</info>' ); } if ($currentEnvironment->operationAvailable('activate')) { $this->stdErr->writeln( 'Activate the current environment by running <info>' . $executable . ' environment:activate</info>' ); } if ($currentEnvironment->operationAvailable('delete')) { $this->stdErr->writeln( 'Delete the current environment by running <info>' . $executable . ' environment:delete</info>' ); } if ($currentEnvironment->operationAvailable('backup')) { $this->stdErr->writeln( 'Make a snapshot of the current environment by running <info>' . $executable . ' snapshot:create</info>' ); } if ($currentEnvironment->operationAvailable('merge')) { $this->stdErr->writeln( 'Merge the current environment by running <info>' . $executable . ' environment:merge</info>' ); } if ($currentEnvironment->operationAvailable('synchronize')) { $this->stdErr->writeln( 'Sync the current environment by running <info>' . $executable . ' environment:synchronize</info>' ); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "validateInput", "(", "$", "input", ")", ";", "$", "refresh", "=", "$", "input", "->", "hasOption", "(", "'refresh'...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentListCommand.php#L134-L244
platformsh/platformsh-cli
src/Model/AppConfig.php
AppConfig.getNormalized
public function getNormalized() { if (!isset($this->normalizedConfig)) { $this->normalizedConfig = $this->normalizeConfig($this->config); } return $this->normalizedConfig; }
php
public function getNormalized() { if (!isset($this->normalizedConfig)) { $this->normalizedConfig = $this->normalizeConfig($this->config); } return $this->normalizedConfig; }
[ "public", "function", "getNormalized", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "normalizedConfig", ")", ")", "{", "$", "this", "->", "normalizedConfig", "=", "$", "this", "->", "normalizeConfig", "(", "$", "this", "->", "config", ...
Get normalized configuration. @return array
[ "Get", "normalized", "configuration", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Model/AppConfig.php#L42-L49
platformsh/platformsh-cli
src/Model/AppConfig.php
AppConfig.getDocumentRoot
public function getDocumentRoot() { $documentRoot = ''; $normalized = $this->getNormalized(); if (empty($normalized['web']['locations'])) { return $documentRoot; } foreach ($this->getNormalized()['web']['locations'] as $path => $location) { if (isset($location['root'])) { $documentRoot = $location['root']; } if ($path === '/') { break; } } return ltrim($documentRoot, '/'); }
php
public function getDocumentRoot() { $documentRoot = ''; $normalized = $this->getNormalized(); if (empty($normalized['web']['locations'])) { return $documentRoot; } foreach ($this->getNormalized()['web']['locations'] as $path => $location) { if (isset($location['root'])) { $documentRoot = $location['root']; } if ($path === '/') { break; } } return ltrim($documentRoot, '/'); }
[ "public", "function", "getDocumentRoot", "(", ")", "{", "$", "documentRoot", "=", "''", ";", "$", "normalized", "=", "$", "this", "->", "getNormalized", "(", ")", ";", "if", "(", "empty", "(", "$", "normalized", "[", "'web'", "]", "[", "'locations'", "...
Get the (normalized) document root as a relative path. @return string
[ "Get", "the", "(", "normalized", ")", "document", "root", "as", "a", "relative", "path", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Model/AppConfig.php#L56-L73
platformsh/platformsh-cli
src/Model/AppConfig.php
AppConfig.normalizeConfig
private function normalizeConfig(array $config) { // Backwards compatibility with old config format: `toolstack` is // changed to application `type` and `build`.`flavor`. if (isset($config['toolstack'])) { if (!strpos($config['toolstack'], ':')) { throw new InvalidConfigException("Invalid value for 'toolstack'"); } list($config['type'], $config['build']['flavor']) = explode(':', $config['toolstack'], 2); } // The `web` section has changed to `web`.`locations`. if (isset($config['web']['document_root']) && empty($config['web']['locations'])) { $oldConfig = $config['web'] + $this->getOldWebDefaults(); $location = &$config['web']['locations']['/']; $location['root'] = $oldConfig['document_root']; $location['expires'] = $oldConfig['expires']; $location['passthru'] = $oldConfig['passthru']; $location['allow'] = true; foreach ($oldConfig['whitelist'] as $pattern) { $location['allow'] = false; $location['rules'][$pattern]['allow'] = true; } foreach ($oldConfig['blacklist'] as $pattern) { $location['rules'][$pattern]['allow'] = false; } } return $config; }
php
private function normalizeConfig(array $config) { // Backwards compatibility with old config format: `toolstack` is // changed to application `type` and `build`.`flavor`. if (isset($config['toolstack'])) { if (!strpos($config['toolstack'], ':')) { throw new InvalidConfigException("Invalid value for 'toolstack'"); } list($config['type'], $config['build']['flavor']) = explode(':', $config['toolstack'], 2); } // The `web` section has changed to `web`.`locations`. if (isset($config['web']['document_root']) && empty($config['web']['locations'])) { $oldConfig = $config['web'] + $this->getOldWebDefaults(); $location = &$config['web']['locations']['/']; $location['root'] = $oldConfig['document_root']; $location['expires'] = $oldConfig['expires']; $location['passthru'] = $oldConfig['passthru']; $location['allow'] = true; foreach ($oldConfig['whitelist'] as $pattern) { $location['allow'] = false; $location['rules'][$pattern]['allow'] = true; } foreach ($oldConfig['blacklist'] as $pattern) { $location['rules'][$pattern]['allow'] = false; } } return $config; }
[ "private", "function", "normalizeConfig", "(", "array", "$", "config", ")", "{", "// Backwards compatibility with old config format: `toolstack` is", "// changed to application `type` and `build`.`flavor`.", "if", "(", "isset", "(", "$", "config", "[", "'toolstack'", "]", ")"...
Normalize the application config. @param array $config @return array
[ "Normalize", "the", "application", "config", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Model/AppConfig.php#L82-L115
platformsh/platformsh-cli
src/Command/Service/MongoDB/MongoDumpCommand.php
MongoDumpCommand.getDefaultFilename
private function getDefaultFilename( Environment $environment, $appName = null, $collection = '', $gzip = false) { $defaultFilename = $environment->project . '--' . $environment->id; if ($appName !== null) { $defaultFilename .= '--' . $appName; } if ($collection) { $defaultFilename .= '--' . $collection; } $defaultFilename .= '--archive.bson'; if ($gzip) { $defaultFilename .= '.gz'; } return $defaultFilename; }
php
private function getDefaultFilename( Environment $environment, $appName = null, $collection = '', $gzip = false) { $defaultFilename = $environment->project . '--' . $environment->id; if ($appName !== null) { $defaultFilename .= '--' . $appName; } if ($collection) { $defaultFilename .= '--' . $collection; } $defaultFilename .= '--archive.bson'; if ($gzip) { $defaultFilename .= '.gz'; } return $defaultFilename; }
[ "private", "function", "getDefaultFilename", "(", "Environment", "$", "environment", ",", "$", "appName", "=", "null", ",", "$", "collection", "=", "''", ",", "$", "gzip", "=", "false", ")", "{", "$", "defaultFilename", "=", "$", "environment", "->", "proj...
Get the default dump filename. @param Environment $environment @param string|null $appName @param string $collection @param bool $gzip @return string
[ "Get", "the", "default", "dump", "filename", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Service/MongoDB/MongoDumpCommand.php#L148-L167
platformsh/platformsh-cli
src/Command/Self/SelfInstallCommand.php
SelfInstallCommand.getRunAdvice
private function getRunAdvice($shellConfigFile, $binDir) { $advice = [ sprintf('To use the %s, run:', $this->config()->get('application.name')) ]; if (!$this->inPath($binDir)) { $sourceAdvice = sprintf(' <info>source %s</info>', $this->formatSourceArg($shellConfigFile)); $sourceAdvice .= ' # (make sure your shell does this by default)'; $advice[] = $sourceAdvice; } $advice[] = sprintf(' <info>%s</info>', $this->config()->get('application.executable')); return $advice; }
php
private function getRunAdvice($shellConfigFile, $binDir) { $advice = [ sprintf('To use the %s, run:', $this->config()->get('application.name')) ]; if (!$this->inPath($binDir)) { $sourceAdvice = sprintf(' <info>source %s</info>', $this->formatSourceArg($shellConfigFile)); $sourceAdvice .= ' # (make sure your shell does this by default)'; $advice[] = $sourceAdvice; } $advice[] = sprintf(' <info>%s</info>', $this->config()->get('application.executable')); return $advice; }
[ "private", "function", "getRunAdvice", "(", "$", "shellConfigFile", ",", "$", "binDir", ")", "{", "$", "advice", "=", "[", "sprintf", "(", "'To use the %s, run:'", ",", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'application.name'", ")", ")"...
@param string $shellConfigFile @param string $binDir @return string[]
[ "@param", "string", "$shellConfigFile", "@param", "string", "$binDir" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Self/SelfInstallCommand.php#L203-L216
platformsh/platformsh-cli
src/Command/Self/SelfInstallCommand.php
SelfInstallCommand.inPath
private function inPath($dir) { $PATH = getenv('PATH'); $realpath = realpath($dir); if (!$PATH || !$realpath) { return false; } return in_array($realpath, explode(':', $PATH)); }
php
private function inPath($dir) { $PATH = getenv('PATH'); $realpath = realpath($dir); if (!$PATH || !$realpath) { return false; } return in_array($realpath, explode(':', $PATH)); }
[ "private", "function", "inPath", "(", "$", "dir", ")", "{", "$", "PATH", "=", "getenv", "(", "'PATH'", ")", ";", "$", "realpath", "=", "realpath", "(", "$", "dir", ")", ";", "if", "(", "!", "$", "PATH", "||", "!", "$", "realpath", ")", "{", "re...
Check if a directory is in the PATH. @return bool
[ "Check", "if", "a", "directory", "is", "in", "the", "PATH", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Self/SelfInstallCommand.php#L223-L232
platformsh/platformsh-cli
src/Command/Self/SelfInstallCommand.php
SelfInstallCommand.formatSourceArg
private function formatSourceArg($filename) { $arg = $filename; // Replace the home directory with ~, if not on Windows. if (DIRECTORY_SEPARATOR !== '\\') { $realpath = realpath($filename); $homeDir = Filesystem::getHomeDirectory(); if ($realpath && strpos($realpath, $homeDir) === 0) { $arg = '~/' . ltrim(substr($realpath, strlen($homeDir)), '/'); } } // Ensure the argument isn't a basename ('source' would look it up in // the PATH). if ($arg === basename($filename)) { $arg = '.' . DIRECTORY_SEPARATOR . $filename; } // Crude argument escaping (escapeshellarg() would prevent tilde // substitution). return str_replace(' ', '\\ ', $arg); }
php
private function formatSourceArg($filename) { $arg = $filename; // Replace the home directory with ~, if not on Windows. if (DIRECTORY_SEPARATOR !== '\\') { $realpath = realpath($filename); $homeDir = Filesystem::getHomeDirectory(); if ($realpath && strpos($realpath, $homeDir) === 0) { $arg = '~/' . ltrim(substr($realpath, strlen($homeDir)), '/'); } } // Ensure the argument isn't a basename ('source' would look it up in // the PATH). if ($arg === basename($filename)) { $arg = '.' . DIRECTORY_SEPARATOR . $filename; } // Crude argument escaping (escapeshellarg() would prevent tilde // substitution). return str_replace(' ', '\\ ', $arg); }
[ "private", "function", "formatSourceArg", "(", "$", "filename", ")", "{", "$", "arg", "=", "$", "filename", ";", "// Replace the home directory with ~, if not on Windows.", "if", "(", "DIRECTORY_SEPARATOR", "!==", "'\\\\'", ")", "{", "$", "realpath", "=", "realpath"...
Transform a filename into an argument for the 'source' command. This is only shown as advice to the user. @param string $filename @return string
[ "Transform", "a", "filename", "into", "an", "argument", "for", "the", "source", "command", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Self/SelfInstallCommand.php#L243-L265
platformsh/platformsh-cli
src/Command/Self/SelfInstallCommand.php
SelfInstallCommand.getShortPath
private function getShortPath($filename) { if (getcwd() === dirname($filename)) { return basename($filename); } $homeDir = Filesystem::getHomeDirectory(); if (strpos($filename, $homeDir) === 0) { return str_replace($homeDir, '~', $filename); } return $filename; }
php
private function getShortPath($filename) { if (getcwd() === dirname($filename)) { return basename($filename); } $homeDir = Filesystem::getHomeDirectory(); if (strpos($filename, $homeDir) === 0) { return str_replace($homeDir, '~', $filename); } return $filename; }
[ "private", "function", "getShortPath", "(", "$", "filename", ")", "{", "if", "(", "getcwd", "(", ")", "===", "dirname", "(", "$", "filename", ")", ")", "{", "return", "basename", "(", "$", "filename", ")", ";", "}", "$", "homeDir", "=", "Filesystem", ...
Shorten a filename for display. @param string $filename @return string
[ "Shorten", "a", "filename", "for", "display", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Self/SelfInstallCommand.php#L274-L285