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
youzan/zanphp
toolkit/debugger_trace_httpd.php
TraceServer.checkAndCalcWebSocketKey
private function checkAndCalcWebSocketKey(array $header) { if (isset($header['sec-websocket-key'])) { $wsSecKey = $header['sec-websocket-key']; // base64 RFC http://www.ietf.org/rfc/rfc4648.txt // http://stackoverflow.com/questions/475074/regex-to-parse-or-validate-base64-data // ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ // The number of '=' signs at the end of a base64 value must not exceed 2 // In base64, if the value ends with '=' then the last character must be one of [AEIMQUYcgkosw048] // In base64, if the value ends with '==' then the last character must be one of [AQgw] $isValidBase64 = preg_match('#^[+/0-9A-Za-z]{21}[AQgw]==$#', $wsSecKey) != 0; $isValidLen = strlen(base64_decode($wsSecKey)) === 16; if ($isValidBase64 && $isValidLen) { return base64_encode(sha1($wsSecKey . self::RFC6455GUID, true)); } } return false; }
php
private function checkAndCalcWebSocketKey(array $header) { if (isset($header['sec-websocket-key'])) { $wsSecKey = $header['sec-websocket-key']; // base64 RFC http://www.ietf.org/rfc/rfc4648.txt // http://stackoverflow.com/questions/475074/regex-to-parse-or-validate-base64-data // ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ // The number of '=' signs at the end of a base64 value must not exceed 2 // In base64, if the value ends with '=' then the last character must be one of [AEIMQUYcgkosw048] // In base64, if the value ends with '==' then the last character must be one of [AQgw] $isValidBase64 = preg_match('#^[+/0-9A-Za-z]{21}[AQgw]==$#', $wsSecKey) != 0; $isValidLen = strlen(base64_decode($wsSecKey)) === 16; if ($isValidBase64 && $isValidLen) { return base64_encode(sha1($wsSecKey . self::RFC6455GUID, true)); } } return false; }
[ "private", "function", "checkAndCalcWebSocketKey", "(", "array", "$", "header", ")", "{", "if", "(", "isset", "(", "$", "header", "[", "'sec-websocket-key'", "]", ")", ")", "{", "$", "wsSecKey", "=", "$", "header", "[", "'sec-websocket-key'", "]", ";", "//...
Sec-WebSocket-Key是随机的字符串,服务器端会用这些数据来构造出一个SHA-1的信息摘要。 把“Sec-WebSocket-Key”加上一个特殊字符串“258EAFA5-E914-47DA-95CA-C5AB0DC85B11”, 然后计算SHA-1摘要,之后进行BASE-64编码,将结果做为“Sec-WebSocket-Accept”头的值,返回给客户端。 如此操作,可以尽量避免普通HTTP请求被误认为Websocket协议。 @from https://zh.wikipedia.org/wiki/WebSocket @param array $header @return bool|string
[ "Sec", "-", "WebSocket", "-", "Key是随机的字符串,服务器端会用这些数据来构造出一个SHA", "-", "1的信息摘要。", "把“Sec", "-", "WebSocket", "-", "Key”加上一个特殊字符串“258EAFA5", "-", "E914", "-", "47DA", "-", "95CA", "-", "C5AB0DC85B11”,", "然后计算SHA", "-", "1摘要,之后进行BASE", "-", "64编码,将结果做为“Sec", "-", "Web...
train
https://github.com/youzan/zanphp/blob/48cb1180f08368c7690b240949ad951ba0be308c/toolkit/debugger_trace_httpd.php#L430-L452
platformsh/platformsh-cli
src/Command/Project/ProjectInfoCommand.php
ProjectInfoCommand.listProperties
protected function listProperties(array $properties) { $headings = []; $values = []; foreach ($properties as $key => $value) { $headings[] = new AdaptiveTableCell($key, ['wrap' => false]); $values[] = $this->formatter->format($value, $key); } /** @var \Platformsh\Cli\Service\Table $table */ $table = $this->getService('table'); $table->renderSimple($values, $headings); return 0; }
php
protected function listProperties(array $properties) { $headings = []; $values = []; foreach ($properties as $key => $value) { $headings[] = new AdaptiveTableCell($key, ['wrap' => false]); $values[] = $this->formatter->format($value, $key); } /** @var \Platformsh\Cli\Service\Table $table */ $table = $this->getService('table'); $table->renderSimple($values, $headings); return 0; }
[ "protected", "function", "listProperties", "(", "array", "$", "properties", ")", "{", "$", "headings", "=", "[", "]", ";", "$", "values", "=", "[", "]", ";", "foreach", "(", "$", "properties", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "h...
@param array $properties @return int
[ "@param", "array", "$properties" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Project/ProjectInfoCommand.php#L95-L108
platformsh/platformsh-cli
src/Command/Project/ProjectInfoCommand.php
ProjectInfoCommand.setProperty
protected function setProperty($property, $value, Project $project, $noWait) { $type = $this->getType($property); if (!$type) { $this->stdErr->writeln("Property not writable: <error>$property</error>"); return 1; } if ($type === 'boolean' && $value === 'false') { $value = false; } settype($value, $type); $currentValue = $project->getProperty($property); if ($currentValue === $value) { $this->stdErr->writeln( "Property <info>$property</info> already set as: " . $this->formatter->format($value, $property) ); return 0; } $project->ensureFull(); $result = $project->update([$property => $value]); $this->stdErr->writeln(sprintf( 'Property <info>%s</info> set to: %s', $property, $this->formatter->format($value, $property) )); $this->api()->clearProjectsCache(); $success = true; if (!$noWait) { /** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */ $activityMonitor = $this->getService('activity_monitor'); $success = $activityMonitor->waitMultiple($result->getActivities(), $this->getSelectedProject()); } return $success ? 0 : 1; }
php
protected function setProperty($property, $value, Project $project, $noWait) { $type = $this->getType($property); if (!$type) { $this->stdErr->writeln("Property not writable: <error>$property</error>"); return 1; } if ($type === 'boolean' && $value === 'false') { $value = false; } settype($value, $type); $currentValue = $project->getProperty($property); if ($currentValue === $value) { $this->stdErr->writeln( "Property <info>$property</info> already set as: " . $this->formatter->format($value, $property) ); return 0; } $project->ensureFull(); $result = $project->update([$property => $value]); $this->stdErr->writeln(sprintf( 'Property <info>%s</info> set to: %s', $property, $this->formatter->format($value, $property) )); $this->api()->clearProjectsCache(); $success = true; if (!$noWait) { /** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */ $activityMonitor = $this->getService('activity_monitor'); $success = $activityMonitor->waitMultiple($result->getActivities(), $this->getSelectedProject()); } return $success ? 0 : 1; }
[ "protected", "function", "setProperty", "(", "$", "property", ",", "$", "value", ",", "Project", "$", "project", ",", "$", "noWait", ")", "{", "$", "type", "=", "$", "this", "->", "getType", "(", "$", "property", ")", ";", "if", "(", "!", "$", "typ...
@param string $property @param string $value @param Project $project @param bool $noWait @return int
[ "@param", "string", "$property", "@param", "string", "$value", "@param", "Project", "$project", "@param", "bool", "$noWait" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Project/ProjectInfoCommand.php#L118-L156
platformsh/platformsh-cli
resources/oauth-listener/index.php
Listener.run
public function run() { // Respond after a successful OAuth2 redirect. if (isset($_GET['state'], $_GET['code'])) { if ($_GET['state'] !== $this->state) { $this->reportError('Invalid state parameter'); return; } if (!file_put_contents($this->file, $_GET['code'], LOCK_EX)) { $this->reportError('Failed to write authorization code to file'); return; } $this->setRedirect($this->localUrl . '/?done'); $this->response->content = '<p>Authentication response received, please wait...</p>'; return; } // Show the final result page. if (array_key_exists('done', $_GET)) { $this->response->content = '<p><strong>Successfully logged in.</strong></p>' . '<p>You can return to the command line.</p>'; return; } // Redirect to login. $url = $this->getOAuthUrl(); $this->setRedirect($url); $this->response->content = '<p><a href="' . htmlspecialchars($url) .'">Log in</a>.</p>'; return; }
php
public function run() { // Respond after a successful OAuth2 redirect. if (isset($_GET['state'], $_GET['code'])) { if ($_GET['state'] !== $this->state) { $this->reportError('Invalid state parameter'); return; } if (!file_put_contents($this->file, $_GET['code'], LOCK_EX)) { $this->reportError('Failed to write authorization code to file'); return; } $this->setRedirect($this->localUrl . '/?done'); $this->response->content = '<p>Authentication response received, please wait...</p>'; return; } // Show the final result page. if (array_key_exists('done', $_GET)) { $this->response->content = '<p><strong>Successfully logged in.</strong></p>' . '<p>You can return to the command line.</p>'; return; } // Redirect to login. $url = $this->getOAuthUrl(); $this->setRedirect($url); $this->response->content = '<p><a href="' . htmlspecialchars($url) .'">Log in</a>.</p>'; return; }
[ "public", "function", "run", "(", ")", "{", "// Respond after a successful OAuth2 redirect.", "if", "(", "isset", "(", "$", "_GET", "[", "'state'", "]", ",", "$", "_GET", "[", "'code'", "]", ")", ")", "{", "if", "(", "$", "_GET", "[", "'state'", "]", "...
Check state, run logic, set page content.
[ "Check", "state", "run", "logic", "set", "page", "content", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/resources/oauth-listener/index.php#L48-L79
platformsh/platformsh-cli
src/Service/RemoteEnvVars.php
RemoteEnvVars.getEnvVar
public function getEnvVar($variable, $sshUrl, $refresh = false, $ttl = 3600) { $varName = $this->config->get('service.env_prefix') . $variable; $cacheKey = 'env-' . $sshUrl . '-' . $varName; $cached = $this->cache->fetch($cacheKey); if ($refresh || $cached === false) { $args = ['ssh']; $args = array_merge($args, $this->ssh->getSshArgs()); $args[] = $sshUrl; $args[] = 'echo $' . $varName; $cached = $this->shellHelper->execute($args, null, true); $this->cache->save($cacheKey, $cached, $ttl); } return $cached ?: ''; }
php
public function getEnvVar($variable, $sshUrl, $refresh = false, $ttl = 3600) { $varName = $this->config->get('service.env_prefix') . $variable; $cacheKey = 'env-' . $sshUrl . '-' . $varName; $cached = $this->cache->fetch($cacheKey); if ($refresh || $cached === false) { $args = ['ssh']; $args = array_merge($args, $this->ssh->getSshArgs()); $args[] = $sshUrl; $args[] = 'echo $' . $varName; $cached = $this->shellHelper->execute($args, null, true); $this->cache->save($cacheKey, $cached, $ttl); } return $cached ?: ''; }
[ "public", "function", "getEnvVar", "(", "$", "variable", ",", "$", "sshUrl", ",", "$", "refresh", "=", "false", ",", "$", "ttl", "=", "3600", ")", "{", "$", "varName", "=", "$", "this", "->", "config", "->", "get", "(", "'service.env_prefix'", ")", "...
Read an environment variable from a remote application. @param string $variable The unprefixed name of the variable. @param string $sshUrl The SSH URL to the application. @param bool $refresh Whether to refresh the cache. @param int $ttl The cache lifetime of the result. @throws \Symfony\Component\Process\Exception\RuntimeException If the SSH command fails. @return string The environment variable or an empty string.
[ "Read", "an", "environment", "variable", "from", "a", "remote", "application", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/RemoteEnvVars.php#L47-L62
platformsh/platformsh-cli
src/Service/RemoteEnvVars.php
RemoteEnvVars.getArrayEnvVar
public function getArrayEnvVar($variable, $sshUrl, $refresh = false) { $value = $this->getEnvVar($variable, $sshUrl, $refresh); return json_decode(base64_decode($value), true) ?: []; }
php
public function getArrayEnvVar($variable, $sshUrl, $refresh = false) { $value = $this->getEnvVar($variable, $sshUrl, $refresh); return json_decode(base64_decode($value), true) ?: []; }
[ "public", "function", "getArrayEnvVar", "(", "$", "variable", ",", "$", "sshUrl", ",", "$", "refresh", "=", "false", ")", "{", "$", "value", "=", "$", "this", "->", "getEnvVar", "(", "$", "variable", ",", "$", "sshUrl", ",", "$", "refresh", ")", ";",...
Read a complex environment variable (an associative array) from the application. @see \Platformsh\Cli\Service\RemoteEnvVars::getEnvVar() @param string $variable @param string $sshUrl @param bool $refresh @return array
[ "Read", "a", "complex", "environment", "variable", "(", "an", "associative", "array", ")", "from", "the", "application", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/RemoteEnvVars.php#L75-L80
platformsh/platformsh-cli
src/Service/RemoteEnvVars.php
RemoteEnvVars.clearCaches
public function clearCaches($sshUrl, array $variables = ['APPLICATION', 'RELATIONSHIPS', 'ROUTES']) { $prefix = $this->config->get('service.env_prefix'); foreach ($variables as $variable) { $this->cache->delete('env-' . $sshUrl . '-' . $prefix . $variable); } }
php
public function clearCaches($sshUrl, array $variables = ['APPLICATION', 'RELATIONSHIPS', 'ROUTES']) { $prefix = $this->config->get('service.env_prefix'); foreach ($variables as $variable) { $this->cache->delete('env-' . $sshUrl . '-' . $prefix . $variable); } }
[ "public", "function", "clearCaches", "(", "$", "sshUrl", ",", "array", "$", "variables", "=", "[", "'APPLICATION'", ",", "'RELATIONSHIPS'", ",", "'ROUTES'", "]", ")", "{", "$", "prefix", "=", "$", "this", "->", "config", "->", "get", "(", "'service.env_pre...
Clear caches for remote environment variables. @param string $sshUrl The SSH URL to the application. @param array $variables A list of unprefixed variables.
[ "Clear", "caches", "for", "remote", "environment", "variables", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/RemoteEnvVars.php#L88-L94
platformsh/platformsh-cli
src/Command/Integration/IntegrationListCommand.php
IntegrationListCommand.getIntegrationSummary
protected function getIntegrationSummary(Integration $integration) { $details = $integration->getProperties(); unset($details['id'], $details['type']); switch ($integration->type) { case 'github': case 'bitbucket': $summary = sprintf('Repository: %s', $details['repository']); if ($integration->hasLink('#hook')) { $summary .= "\n" . sprintf('Hook URL: %s', $integration->getLink('#hook')); } break; case 'gitlab': $summary = sprintf('Project: %s', $details['project']); $summary .= "\n" . sprintf('Base URL: %s', $details['base_url']); if ($integration->hasLink('#hook')) { $summary .= "\n" . sprintf('Hook URL: %s', $integration->getLink('#hook')); } break; case 'hipchat': $summary = sprintf('Room ID: %s', $details['room']); break; case 'webhook': $summary = sprintf('URL: %s', $details['url']); break; case 'health.email': $summary = sprintf("From: %s\nTo: %s", $details['from_address'], implode(', ', $details['recipients'])); break; case 'health.slack': $summary = sprintf('Channel: %s', $details['channel']); break; case 'health.pagerduty': $summary = sprintf('Routing key: %s', $details['routing_key']); break; default: $summary = json_encode($details); } if (strlen($summary) > 240) { $summary = substr($summary, 0, 237) . '...'; } return $summary; }
php
protected function getIntegrationSummary(Integration $integration) { $details = $integration->getProperties(); unset($details['id'], $details['type']); switch ($integration->type) { case 'github': case 'bitbucket': $summary = sprintf('Repository: %s', $details['repository']); if ($integration->hasLink('#hook')) { $summary .= "\n" . sprintf('Hook URL: %s', $integration->getLink('#hook')); } break; case 'gitlab': $summary = sprintf('Project: %s', $details['project']); $summary .= "\n" . sprintf('Base URL: %s', $details['base_url']); if ($integration->hasLink('#hook')) { $summary .= "\n" . sprintf('Hook URL: %s', $integration->getLink('#hook')); } break; case 'hipchat': $summary = sprintf('Room ID: %s', $details['room']); break; case 'webhook': $summary = sprintf('URL: %s', $details['url']); break; case 'health.email': $summary = sprintf("From: %s\nTo: %s", $details['from_address'], implode(', ', $details['recipients'])); break; case 'health.slack': $summary = sprintf('Channel: %s', $details['channel']); break; case 'health.pagerduty': $summary = sprintf('Routing key: %s', $details['routing_key']); break; default: $summary = json_encode($details); } if (strlen($summary) > 240) { $summary = substr($summary, 0, 237) . '...'; } return $summary; }
[ "protected", "function", "getIntegrationSummary", "(", "Integration", "$", "integration", ")", "{", "$", "details", "=", "$", "integration", "->", "getProperties", "(", ")", ";", "unset", "(", "$", "details", "[", "'id'", "]", ",", "$", "details", "[", "'t...
@param Integration $integration @return string
[ "@param", "Integration", "$integration" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Integration/IntegrationListCommand.php#L67-L118
platformsh/platformsh-cli
src/Command/Worker/WorkerListCommand.php
WorkerListCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $workers = $this->api() ->getCurrentDeployment($this->getSelectedEnvironment(), $input->getOption('refresh')) ->workers; if (empty($workers)) { $this->stdErr->writeln('No workers found.'); return 0; } /** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */ $formatter = $this->getService('property_formatter'); $rows = []; foreach ($workers as $worker) { $commands = isset($worker->worker['commands']) ? $worker->worker['commands'] : []; $rows[] = [$worker->name, $worker->type, $formatter->format($commands)]; } /** @var \Platformsh\Cli\Service\Table $table */ $table = $this->getService('table'); if (!$table->formatIsMachineReadable()) { $this->stdErr->writeln(sprintf( 'Workers on the project <info>%s</info>, environment <info>%s</info>:', $this->api()->getProjectLabel($this->getSelectedProject()), $this->api()->getEnvironmentLabel($this->getSelectedEnvironment()) )); } $table->render($rows, ['Name', 'Type', 'Commands']); return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $workers = $this->api() ->getCurrentDeployment($this->getSelectedEnvironment(), $input->getOption('refresh')) ->workers; if (empty($workers)) { $this->stdErr->writeln('No workers found.'); return 0; } /** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */ $formatter = $this->getService('property_formatter'); $rows = []; foreach ($workers as $worker) { $commands = isset($worker->worker['commands']) ? $worker->worker['commands'] : []; $rows[] = [$worker->name, $worker->type, $formatter->format($commands)]; } /** @var \Platformsh\Cli\Service\Table $table */ $table = $this->getService('table'); if (!$table->formatIsMachineReadable()) { $this->stdErr->writeln(sprintf( 'Workers on the project <info>%s</info>, environment <info>%s</info>:', $this->api()->getProjectLabel($this->getSelectedProject()), $this->api()->getEnvironmentLabel($this->getSelectedEnvironment()) )); } $table->render($rows, ['Name', 'Type', 'Commands']); return 0; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "validateInput", "(", "$", "input", ")", ";", "$", "workers", "=", "$", "this", "->", "api", "(", ")", "->", "g...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Worker/WorkerListCommand.php#L29-L64
platformsh/platformsh-cli
src/Console/EventSubscriber.php
EventSubscriber.onException
public function onException(ConsoleExceptionEvent $event) { $exception = $event->getException(); // Replace Guzzle connect exceptions with a friendlier message. This // also prevents the user from seeing two exceptions (one direct from // Guzzle, one from RingPHP). if ($exception instanceof ConnectException && strpos($exception->getMessage(), 'cURL error 6') !== false) { $request = $exception->getRequest(); $event->setException(new ConnectionFailedException( "Failed to connect to host: " . $request->getHost() . " \nPlease check your Internet connection.", $request )); $event->stopPropagation(); } // Handle Guzzle exceptions, i.e. HTTP 4xx or 5xx errors. if (($exception instanceof ClientException || $exception instanceof ServerException) && ($response = $exception->getResponse())) { $request = $exception->getRequest(); $requestConfig = $request->getConfig(); $response->getBody()->seek(0); $json = (array) json_decode($response->getBody()->getContents(), true); // Create a friendlier message for the OAuth2 "Invalid refresh token" // error. if ($response->getStatusCode() === 400 && isset($json['error_description']) && $json['error_description'] === 'Invalid refresh token') { $event->setException(new LoginRequiredException( 'Invalid refresh token.', $request, $response, $this->config )); $event->stopPropagation(); } elseif ($response->getStatusCode() === 401 && $requestConfig['auth'] === 'oauth2') { $event->setException(new LoginRequiredException( 'Unauthorized.', $request, $response, $this->config )); $event->stopPropagation(); } elseif ($response->getStatusCode() === 403 && $requestConfig['auth'] === 'oauth2') { $event->setException(new PermissionDeniedException( "Permission denied. Check your project or environment permissions.", $request, $response )); $event->stopPropagation(); } else { $event->setException(new HttpException(null, $request, $response)); $event->stopPropagation(); } } // When an environment is found to be in the wrong state, perhaps our // cache is old - we should invalidate it. if ($exception instanceof EnvironmentStateException) { (new Api())->clearEnvironmentsCache($exception->getEnvironment()->project); } }
php
public function onException(ConsoleExceptionEvent $event) { $exception = $event->getException(); // Replace Guzzle connect exceptions with a friendlier message. This // also prevents the user from seeing two exceptions (one direct from // Guzzle, one from RingPHP). if ($exception instanceof ConnectException && strpos($exception->getMessage(), 'cURL error 6') !== false) { $request = $exception->getRequest(); $event->setException(new ConnectionFailedException( "Failed to connect to host: " . $request->getHost() . " \nPlease check your Internet connection.", $request )); $event->stopPropagation(); } // Handle Guzzle exceptions, i.e. HTTP 4xx or 5xx errors. if (($exception instanceof ClientException || $exception instanceof ServerException) && ($response = $exception->getResponse())) { $request = $exception->getRequest(); $requestConfig = $request->getConfig(); $response->getBody()->seek(0); $json = (array) json_decode($response->getBody()->getContents(), true); // Create a friendlier message for the OAuth2 "Invalid refresh token" // error. if ($response->getStatusCode() === 400 && isset($json['error_description']) && $json['error_description'] === 'Invalid refresh token') { $event->setException(new LoginRequiredException( 'Invalid refresh token.', $request, $response, $this->config )); $event->stopPropagation(); } elseif ($response->getStatusCode() === 401 && $requestConfig['auth'] === 'oauth2') { $event->setException(new LoginRequiredException( 'Unauthorized.', $request, $response, $this->config )); $event->stopPropagation(); } elseif ($response->getStatusCode() === 403 && $requestConfig['auth'] === 'oauth2') { $event->setException(new PermissionDeniedException( "Permission denied. Check your project or environment permissions.", $request, $response )); $event->stopPropagation(); } else { $event->setException(new HttpException(null, $request, $response)); $event->stopPropagation(); } } // When an environment is found to be in the wrong state, perhaps our // cache is old - we should invalidate it. if ($exception instanceof EnvironmentStateException) { (new Api())->clearEnvironmentsCache($exception->getEnvironment()->project); } }
[ "public", "function", "onException", "(", "ConsoleExceptionEvent", "$", "event", ")", "{", "$", "exception", "=", "$", "event", "->", "getException", "(", ")", ";", "// Replace Guzzle connect exceptions with a friendlier message. This", "// also prevents the user from seeing ...
React to any console exceptions. @param ConsoleExceptionEvent $event
[ "React", "to", "any", "console", "exceptions", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/EventSubscriber.php#L43-L106
platformsh/platformsh-cli
src/SelfUpdate/ManifestStrategy.php
ManifestStrategy.getCurrentRemoteVersion
public function getCurrentRemoteVersion(Updater $updater) { $versions = array_keys($this->getAvailableVersions()); if (!$this->allowMajor) { $versions = $this->filterByLocalMajorVersion($versions); } if (!$this->ignorePhpReq) { $versions = $this->filterByPhpVersion($versions); } $versionParser = new VersionParser($versions); $mostRecent = $versionParser->getMostRecentStable(); // Look for unstable updates if explicitly allowed, or if the local // version is already unstable and there is no new stable version. if ($this->allowUnstable || ($versionParser->isUnstable($this->localVersion) && version_compare($mostRecent, $this->localVersion, '<'))) { $mostRecent = $versionParser->getMostRecentAll(); } return version_compare($mostRecent, $this->localVersion, '>') ? $mostRecent : false; }
php
public function getCurrentRemoteVersion(Updater $updater) { $versions = array_keys($this->getAvailableVersions()); if (!$this->allowMajor) { $versions = $this->filterByLocalMajorVersion($versions); } if (!$this->ignorePhpReq) { $versions = $this->filterByPhpVersion($versions); } $versionParser = new VersionParser($versions); $mostRecent = $versionParser->getMostRecentStable(); // Look for unstable updates if explicitly allowed, or if the local // version is already unstable and there is no new stable version. if ($this->allowUnstable || ($versionParser->isUnstable($this->localVersion) && version_compare($mostRecent, $this->localVersion, '<'))) { $mostRecent = $versionParser->getMostRecentAll(); } return version_compare($mostRecent, $this->localVersion, '>') ? $mostRecent : false; }
[ "public", "function", "getCurrentRemoteVersion", "(", "Updater", "$", "updater", ")", "{", "$", "versions", "=", "array_keys", "(", "$", "this", "->", "getAvailableVersions", "(", ")", ")", ";", "if", "(", "!", "$", "this", "->", "allowMajor", ")", "{", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SelfUpdate/ManifestStrategy.php#L82-L105
platformsh/platformsh-cli
src/SelfUpdate/ManifestStrategy.php
ManifestStrategy.getUpdateNotes
public function getUpdateNotes(Updater $updater) { $versionInfo = $this->getRemoteVersionInfo($updater); if (empty($versionInfo['updating'])) { return false; } $localVersion = $this->getCurrentLocalVersion($updater); $items = isset($versionInfo['updating'][0]) ? $versionInfo['updating'] : [$versionInfo['updating']]; foreach ($items as $updating) { if (!isset($updating['notes'])) { continue; } elseif (isset($updating['hide from']) && version_compare($localVersion, $updating['hide from'], '>=')) { continue; } elseif (isset($updating['show from']) && version_compare($localVersion, $updating['show from'], '<')) { continue; } return $updating['notes']; } return false; }
php
public function getUpdateNotes(Updater $updater) { $versionInfo = $this->getRemoteVersionInfo($updater); if (empty($versionInfo['updating'])) { return false; } $localVersion = $this->getCurrentLocalVersion($updater); $items = isset($versionInfo['updating'][0]) ? $versionInfo['updating'] : [$versionInfo['updating']]; foreach ($items as $updating) { if (!isset($updating['notes'])) { continue; } elseif (isset($updating['hide from']) && version_compare($localVersion, $updating['hide from'], '>=')) { continue; } elseif (isset($updating['show from']) && version_compare($localVersion, $updating['show from'], '<')) { continue; } return $updating['notes']; } return false; }
[ "public", "function", "getUpdateNotes", "(", "Updater", "$", "updater", ")", "{", "$", "versionInfo", "=", "$", "this", "->", "getRemoteVersionInfo", "(", "$", "updater", ")", ";", "if", "(", "empty", "(", "$", "versionInfo", "[", "'updating'", "]", ")", ...
Find update/upgrade notes for the new remote version. @param Updater $updater @return string|false A string if notes are found, or false otherwise.
[ "Find", "update", "/", "upgrade", "notes", "for", "the", "new", "remote", "version", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SelfUpdate/ManifestStrategy.php#L115-L135
platformsh/platformsh-cli
src/SelfUpdate/ManifestStrategy.php
ManifestStrategy.download
public function download(Updater $updater) { $versionInfo = $this->getRemoteVersionInfo($updater); $context = stream_context_create(['http' => ['timeout' => $this->downloadTimeout]]); $fileContents = file_get_contents($versionInfo['url'], false, $context); if ($fileContents === false) { throw new HttpRequestException(sprintf('Failed to download file from URL: %s', $versionInfo['url'])); } $tmpFilename = $updater->getTempPharFile(); if (file_put_contents($tmpFilename, $fileContents) === false) { throw new \RuntimeException(sprintf('Failed to write file: %s', $tmpFilename)); } $tmpSha = hash_file('sha256', $tmpFilename); if ($tmpSha !== $versionInfo['sha256']) { unlink($tmpFilename); throw new \RuntimeException( sprintf( 'SHA-256 verification failed: expected %s, actual %s', $versionInfo['sha256'], $tmpSha ) ); } }
php
public function download(Updater $updater) { $versionInfo = $this->getRemoteVersionInfo($updater); $context = stream_context_create(['http' => ['timeout' => $this->downloadTimeout]]); $fileContents = file_get_contents($versionInfo['url'], false, $context); if ($fileContents === false) { throw new HttpRequestException(sprintf('Failed to download file from URL: %s', $versionInfo['url'])); } $tmpFilename = $updater->getTempPharFile(); if (file_put_contents($tmpFilename, $fileContents) === false) { throw new \RuntimeException(sprintf('Failed to write file: %s', $tmpFilename)); } $tmpSha = hash_file('sha256', $tmpFilename); if ($tmpSha !== $versionInfo['sha256']) { unlink($tmpFilename); throw new \RuntimeException( sprintf( 'SHA-256 verification failed: expected %s, actual %s', $versionInfo['sha256'], $tmpSha ) ); } }
[ "public", "function", "download", "(", "Updater", "$", "updater", ")", "{", "$", "versionInfo", "=", "$", "this", "->", "getRemoteVersionInfo", "(", "$", "updater", ")", ";", "$", "context", "=", "stream_context_create", "(", "[", "'http'", "=>", "[", "'ti...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SelfUpdate/ManifestStrategy.php#L140-L166
platformsh/platformsh-cli
src/SelfUpdate/ManifestStrategy.php
ManifestStrategy.getAvailableVersions
private function getAvailableVersions() { if (!isset($this->availableVersions)) { $this->availableVersions = []; foreach ($this->getManifest() as $key => $item) { if ($missing = array_diff(self::$requiredKeys, array_keys($item))) { throw new \RuntimeException(sprintf( 'Manifest item %s missing required key(s): %s', $key, implode(',', $missing) )); } $this->availableVersions[$item['version']] = $item; } } return $this->availableVersions; }
php
private function getAvailableVersions() { if (!isset($this->availableVersions)) { $this->availableVersions = []; foreach ($this->getManifest() as $key => $item) { if ($missing = array_diff(self::$requiredKeys, array_keys($item))) { throw new \RuntimeException(sprintf( 'Manifest item %s missing required key(s): %s', $key, implode(',', $missing) )); } $this->availableVersions[$item['version']] = $item; } } return $this->availableVersions; }
[ "private", "function", "getAvailableVersions", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "availableVersions", ")", ")", "{", "$", "this", "->", "availableVersions", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getManifest...
Get available versions to update to. @return array An array keyed by the version name, whose elements are arrays containing version information ('version', 'sha256', and 'url').
[ "Get", "available", "versions", "to", "update", "to", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SelfUpdate/ManifestStrategy.php#L175-L192
platformsh/platformsh-cli
src/SelfUpdate/ManifestStrategy.php
ManifestStrategy.getRemoteVersionInfo
private function getRemoteVersionInfo(Updater $updater) { $version = $this->getCurrentRemoteVersion($updater); if ($version === false) { throw new \RuntimeException('No remote versions found'); } $versionInfo = $this->getAvailableVersions(); if (!isset($versionInfo[$version])) { throw new \RuntimeException(sprintf('Failed to find manifest item for version %s', $version)); } return $versionInfo[$version]; }
php
private function getRemoteVersionInfo(Updater $updater) { $version = $this->getCurrentRemoteVersion($updater); if ($version === false) { throw new \RuntimeException('No remote versions found'); } $versionInfo = $this->getAvailableVersions(); if (!isset($versionInfo[$version])) { throw new \RuntimeException(sprintf('Failed to find manifest item for version %s', $version)); } return $versionInfo[$version]; }
[ "private", "function", "getRemoteVersionInfo", "(", "Updater", "$", "updater", ")", "{", "$", "version", "=", "$", "this", "->", "getCurrentRemoteVersion", "(", "$", "updater", ")", ";", "if", "(", "$", "version", "===", "false", ")", "{", "throw", "new", ...
Get version information for the latest remote version. @param Updater $updater @return array
[ "Get", "version", "information", "for", "the", "latest", "remote", "version", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SelfUpdate/ManifestStrategy.php#L201-L213
platformsh/platformsh-cli
src/SelfUpdate/ManifestStrategy.php
ManifestStrategy.getManifest
private function getManifest() { if (!isset($this->manifest)) { $context = stream_context_create(['http' => ['timeout' => $this->manifestTimeout]]); $manifestContents = file_get_contents($this->manifestUrl, false, $context); if ($manifestContents === false) { throw new \RuntimeException(sprintf('Failed to download manifest: %s', $this->manifestUrl)); } $this->manifest = (array) json_decode($manifestContents, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new JsonParsingException( 'Error parsing manifest file' . (function_exists('json_last_error_msg') ? ': ' . json_last_error_msg() : '') ); } } return $this->manifest; }
php
private function getManifest() { if (!isset($this->manifest)) { $context = stream_context_create(['http' => ['timeout' => $this->manifestTimeout]]); $manifestContents = file_get_contents($this->manifestUrl, false, $context); if ($manifestContents === false) { throw new \RuntimeException(sprintf('Failed to download manifest: %s', $this->manifestUrl)); } $this->manifest = (array) json_decode($manifestContents, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new JsonParsingException( 'Error parsing manifest file' . (function_exists('json_last_error_msg') ? ': ' . json_last_error_msg() : '') ); } } return $this->manifest; }
[ "private", "function", "getManifest", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "manifest", ")", ")", "{", "$", "context", "=", "stream_context_create", "(", "[", "'http'", "=>", "[", "'timeout'", "=>", "$", "this", "->", "manifes...
Download and decode the JSON manifest file. @return array
[ "Download", "and", "decode", "the", "JSON", "manifest", "file", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SelfUpdate/ManifestStrategy.php#L220-L239
platformsh/platformsh-cli
src/SelfUpdate/ManifestStrategy.php
ManifestStrategy.filterByLocalMajorVersion
private function filterByLocalMajorVersion(array $versions) { list($localMajorVersion, ) = explode('.', $this->localVersion, 2); return array_filter($versions, function ($version) use ($localMajorVersion) { list($majorVersion, ) = explode('.', $version, 2); return $majorVersion === $localMajorVersion; }); }
php
private function filterByLocalMajorVersion(array $versions) { list($localMajorVersion, ) = explode('.', $this->localVersion, 2); return array_filter($versions, function ($version) use ($localMajorVersion) { list($majorVersion, ) = explode('.', $version, 2); return $majorVersion === $localMajorVersion; }); }
[ "private", "function", "filterByLocalMajorVersion", "(", "array", "$", "versions", ")", "{", "list", "(", "$", "localMajorVersion", ",", ")", "=", "explode", "(", "'.'", ",", "$", "this", "->", "localVersion", ",", "2", ")", ";", "return", "array_filter", ...
Filter a list of versions to those that match the current local version. @param string[] $versions @return string[]
[ "Filter", "a", "list", "of", "versions", "to", "those", "that", "match", "the", "current", "local", "version", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SelfUpdate/ManifestStrategy.php#L248-L256
platformsh/platformsh-cli
src/SelfUpdate/ManifestStrategy.php
ManifestStrategy.filterByPhpVersion
private function filterByPhpVersion(array $versions) { $versionInfo = $this->getAvailableVersions(); return array_filter($versions, function ($version) use ($versionInfo) { if (isset($versionInfo[$version]['php']['min']) && version_compare(PHP_VERSION, $versionInfo[$version]['php']['min'], '<')) { return false; } elseif (isset($versionInfo[$version]['php']['max']) && version_compare(PHP_VERSION, $versionInfo[$version]['php']['max'], '>')) { return false; } return true; }); }
php
private function filterByPhpVersion(array $versions) { $versionInfo = $this->getAvailableVersions(); return array_filter($versions, function ($version) use ($versionInfo) { if (isset($versionInfo[$version]['php']['min']) && version_compare(PHP_VERSION, $versionInfo[$version]['php']['min'], '<')) { return false; } elseif (isset($versionInfo[$version]['php']['max']) && version_compare(PHP_VERSION, $versionInfo[$version]['php']['max'], '>')) { return false; } return true; }); }
[ "private", "function", "filterByPhpVersion", "(", "array", "$", "versions", ")", "{", "$", "versionInfo", "=", "$", "this", "->", "getAvailableVersions", "(", ")", ";", "return", "array_filter", "(", "$", "versions", ",", "function", "(", "$", "version", ")"...
Filter a list of versions to those that allow the current PHP version. @param string[] $versions @return string[]
[ "Filter", "a", "list", "of", "versions", "to", "those", "that", "allow", "the", "current", "PHP", "version", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SelfUpdate/ManifestStrategy.php#L265-L280
platformsh/platformsh-cli
src/Service/Mount.php
Mount.getSharedFileMounts
public function getSharedFileMounts(array $appConfig) { $sharedFileMounts = []; if (!empty($appConfig['mounts'])) { foreach ($this->normalizeMounts($appConfig['mounts']) as $path => $definition) { if (isset($definition['source_path'])) { $sharedFileMounts[$path] = $definition['source_path'] ?: 'files'; } } } return $sharedFileMounts; }
php
public function getSharedFileMounts(array $appConfig) { $sharedFileMounts = []; if (!empty($appConfig['mounts'])) { foreach ($this->normalizeMounts($appConfig['mounts']) as $path => $definition) { if (isset($definition['source_path'])) { $sharedFileMounts[$path] = $definition['source_path'] ?: 'files'; } } } return $sharedFileMounts; }
[ "public", "function", "getSharedFileMounts", "(", "array", "$", "appConfig", ")", "{", "$", "sharedFileMounts", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "appConfig", "[", "'mounts'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", ...
Get a list of shared file mounts configured for an app. @param array $appConfig The app configuration. @return array An array of shared file paths, keyed by the mount path. Leading and trailing slashes are stripped. An empty shared path defaults to 'files'.
[ "Get", "a", "list", "of", "shared", "file", "mounts", "configured", "for", "an", "app", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Mount.php#L21-L33
platformsh/platformsh-cli
src/Service/Mount.php
Mount.normalizeMounts
public function normalizeMounts(array $mounts) { $normalized = []; foreach ($mounts as $path => $definition) { $normalized[$this->normalizeRelativePath($path)] = $this->normalizeDefinition($definition); } return $normalized; }
php
public function normalizeMounts(array $mounts) { $normalized = []; foreach ($mounts as $path => $definition) { $normalized[$this->normalizeRelativePath($path)] = $this->normalizeDefinition($definition); } return $normalized; }
[ "public", "function", "normalizeMounts", "(", "array", "$", "mounts", ")", "{", "$", "normalized", "=", "[", "]", ";", "foreach", "(", "$", "mounts", "as", "$", "path", "=>", "$", "definition", ")", "{", "$", "normalized", "[", "$", "this", "->", "no...
Normalize a list of mounts. @param array $mounts @return array
[ "Normalize", "a", "list", "of", "mounts", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Mount.php#L42-L50
platformsh/platformsh-cli
src/Service/Mount.php
Mount.validateMountPath
public function validateMountPath($inputPath, array $mounts) { $normalized = $this->normalizeRelativePath($inputPath); if (isset($mounts[$normalized])) { return $normalized; } throw new \InvalidArgumentException(sprintf('Mount not found: <error>%s</error>', $inputPath)); }
php
public function validateMountPath($inputPath, array $mounts) { $normalized = $this->normalizeRelativePath($inputPath); if (isset($mounts[$normalized])) { return $normalized; } throw new \InvalidArgumentException(sprintf('Mount not found: <error>%s</error>', $inputPath)); }
[ "public", "function", "validateMountPath", "(", "$", "inputPath", ",", "array", "$", "mounts", ")", "{", "$", "normalized", "=", "$", "this", "->", "normalizeRelativePath", "(", "$", "inputPath", ")", ";", "if", "(", "isset", "(", "$", "mounts", "[", "$"...
Validate and normalize a path to a mount. @param string $inputPath @param array $mounts @return string The normalized mount path.
[ "Validate", "and", "normalize", "a", "path", "to", "a", "mount", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Mount.php#L61-L69
platformsh/platformsh-cli
src/Service/Mount.php
Mount.normalizeDefinition
private function normalizeDefinition($definition) { if (!is_array($definition)) { if (!is_string($definition) || strpos($definition, 'shared:files') === false) { throw new \RuntimeException('Failed to parse mount definition: ' . json_encode($definition)); } $definition = [ 'source' => 'local', 'source_path' => str_replace('shared:files', '', $definition), ]; } elseif (!isset($definition['source'])) { throw new \InvalidArgumentException('Invalid mount definition: ' . json_encode($definition)); } if (isset($definition['source_path'])) { $definition['source_path'] = $this->normalizeRelativePath($definition['source_path']); } return $definition; }
php
private function normalizeDefinition($definition) { if (!is_array($definition)) { if (!is_string($definition) || strpos($definition, 'shared:files') === false) { throw new \RuntimeException('Failed to parse mount definition: ' . json_encode($definition)); } $definition = [ 'source' => 'local', 'source_path' => str_replace('shared:files', '', $definition), ]; } elseif (!isset($definition['source'])) { throw new \InvalidArgumentException('Invalid mount definition: ' . json_encode($definition)); } if (isset($definition['source_path'])) { $definition['source_path'] = $this->normalizeRelativePath($definition['source_path']); } return $definition; }
[ "private", "function", "normalizeDefinition", "(", "$", "definition", ")", "{", "if", "(", "!", "is_array", "(", "$", "definition", ")", ")", "{", "if", "(", "!", "is_string", "(", "$", "definition", ")", "||", "strpos", "(", "$", "definition", ",", "'...
Normalize a mount definition. @param array|string $definition @return array An array containing at least 'source', and probably 'source_path'.
[ "Normalize", "a", "mount", "definition", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Mount.php#L91-L109
platformsh/platformsh-cli
src/Local/DependencyManager/Composer.php
Composer.install
public function install($path, array $dependencies, $global = false) { if ($global) { $this->installGlobal($dependencies); return; } $composerJson = $path . '/composer.json'; $contents = file_exists($composerJson) ? file_get_contents($composerJson) : null; $newContents = json_encode(['require' => $dependencies]); if ($contents !== $newContents) { file_put_contents($composerJson, $newContents); if (file_exists($path . '/composer.lock')) { unlink($path . '/composer.lock'); } } $this->runCommand('composer install --no-progress --prefer-dist --optimize-autoloader --no-interaction', $path); }
php
public function install($path, array $dependencies, $global = false) { if ($global) { $this->installGlobal($dependencies); return; } $composerJson = $path . '/composer.json'; $contents = file_exists($composerJson) ? file_get_contents($composerJson) : null; $newContents = json_encode(['require' => $dependencies]); if ($contents !== $newContents) { file_put_contents($composerJson, $newContents); if (file_exists($path . '/composer.lock')) { unlink($path . '/composer.lock'); } } $this->runCommand('composer install --no-progress --prefer-dist --optimize-autoloader --no-interaction', $path); }
[ "public", "function", "install", "(", "$", "path", ",", "array", "$", "dependencies", ",", "$", "global", "=", "false", ")", "{", "if", "(", "$", "global", ")", "{", "$", "this", "->", "installGlobal", "(", "$", "dependencies", ")", ";", "return", ";...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyManager/Composer.php#L28-L45
platformsh/platformsh-cli
src/Local/DependencyManager/Composer.php
Composer.installGlobal
private function installGlobal(array $dependencies) { $requirements = []; foreach ($dependencies as $package => $version) { $requirements[] = $version === '*' ? $package : $package . ':' . $version; } $this->runCommand( 'composer global require ' . '--no-progress --prefer-dist --optimize-autoloader --no-interaction ' . implode(' ', array_map('escapeshellarg', $requirements)) ); }
php
private function installGlobal(array $dependencies) { $requirements = []; foreach ($dependencies as $package => $version) { $requirements[] = $version === '*' ? $package : $package . ':' . $version; } $this->runCommand( 'composer global require ' . '--no-progress --prefer-dist --optimize-autoloader --no-interaction ' . implode(' ', array_map('escapeshellarg', $requirements)) ); }
[ "private", "function", "installGlobal", "(", "array", "$", "dependencies", ")", "{", "$", "requirements", "=", "[", "]", ";", "foreach", "(", "$", "dependencies", "as", "$", "package", "=>", "$", "version", ")", "{", "$", "requirements", "[", "]", "=", ...
Install dependencies globally. @param array $dependencies
[ "Install", "dependencies", "globally", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyManager/Composer.php#L52-L63
platformsh/platformsh-cli
src/Command/Variable/VariableSetCommand.php
VariableSetCommand.configure
protected function configure() { $this ->setName('variable:set') ->setAliases(['vset']) ->addArgument('name', InputArgument::REQUIRED, 'The variable name') ->addArgument('value', InputArgument::REQUIRED, 'The variable value') ->addOption('json', null, InputOption::VALUE_NONE, 'Mark the value as JSON') ->addOption('disabled', null, InputOption::VALUE_NONE, 'Mark the variable as disabled') ->setDescription('Set a variable for an environment'); $this->addProjectOption() ->addEnvironmentOption() ->addWaitOptions(); $this->addExample('Set the variable "example" to the string "123"', 'example 123'); $this->addExample('Set the variable "example" to the Boolean TRUE', 'example --json true'); $this->addExample('Set the variable "example" to a list of values', 'example --json \'["value1", "value2"]\''); }
php
protected function configure() { $this ->setName('variable:set') ->setAliases(['vset']) ->addArgument('name', InputArgument::REQUIRED, 'The variable name') ->addArgument('value', InputArgument::REQUIRED, 'The variable value') ->addOption('json', null, InputOption::VALUE_NONE, 'Mark the value as JSON') ->addOption('disabled', null, InputOption::VALUE_NONE, 'Mark the variable as disabled') ->setDescription('Set a variable for an environment'); $this->addProjectOption() ->addEnvironmentOption() ->addWaitOptions(); $this->addExample('Set the variable "example" to the string "123"', 'example 123'); $this->addExample('Set the variable "example" to the Boolean TRUE', 'example --json true'); $this->addExample('Set the variable "example" to a list of values', 'example --json \'["value1", "value2"]\''); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'variable:set'", ")", "->", "setAliases", "(", "[", "'vset'", "]", ")", "->", "addArgument", "(", "'name'", ",", "InputArgument", "::", "REQUIRED", ",", "'The variable n...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Variable/VariableSetCommand.php#L21-L37
platformsh/platformsh-cli
src/Command/Environment/EnvironmentHttpAccessCommand.php
EnvironmentHttpAccessCommand.parseAuth
protected function parseAuth($auth) { $parts = explode(':', $auth, 2); if (count($parts) != 2) { $message = sprintf('Auth "<error>%s</error>" is not valid. The format should be username:password', $auth); throw new InvalidArgumentException($message); } if (!preg_match('#^[a-zA-Z0-9]{2,}$#', $parts[0])) { $message = sprintf('The username "<error>%s</error>" for --auth is not valid', $parts[0]); throw new InvalidArgumentException($message); } $minLength = 6; if (strlen($parts[1]) < $minLength) { $message = sprintf('The minimum password length for --auth is %d characters', $minLength); throw new InvalidArgumentException($message); } return ["username" => $parts[0], "password" => $parts[1]]; }
php
protected function parseAuth($auth) { $parts = explode(':', $auth, 2); if (count($parts) != 2) { $message = sprintf('Auth "<error>%s</error>" is not valid. The format should be username:password', $auth); throw new InvalidArgumentException($message); } if (!preg_match('#^[a-zA-Z0-9]{2,}$#', $parts[0])) { $message = sprintf('The username "<error>%s</error>" for --auth is not valid', $parts[0]); throw new InvalidArgumentException($message); } $minLength = 6; if (strlen($parts[1]) < $minLength) { $message = sprintf('The minimum password length for --auth is %d characters', $minLength); throw new InvalidArgumentException($message); } return ["username" => $parts[0], "password" => $parts[1]]; }
[ "protected", "function", "parseAuth", "(", "$", "auth", ")", "{", "$", "parts", "=", "explode", "(", "':'", ",", "$", "auth", ",", "2", ")", ";", "if", "(", "count", "(", "$", "parts", ")", "!=", "2", ")", "{", "$", "message", "=", "sprintf", "...
@param $auth @throws InvalidArgumentException @return array
[ "@param", "$auth" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentHttpAccessCommand.php#L54-L74
platformsh/platformsh-cli
src/Command/Environment/EnvironmentHttpAccessCommand.php
EnvironmentHttpAccessCommand.parseAccess
protected function parseAccess($access) { $parts = explode(':', $access, 2); if (count($parts) != 2) { $message = sprintf( 'Access "<error>%s</error>" is not valid, please use the format: permission:address', $access ); throw new InvalidArgumentException($message); } if (!in_array($parts[0], ['allow', 'deny'])) { $message = sprintf( "The permission type '<error>%s</error>' is not valid; it must be one of 'allow' or 'deny'", $parts[0] ); throw new InvalidArgumentException($message); } list($permission, $address) = $parts; $this->validateAddress($address); // Normalize the address so that we can compare accurately with the // current value returned from the API. if ($address == 'any') { $address = '0.0.0.0/0'; } elseif ($address && !strpos($address, '/')) { $address .= '/32'; } return ["address" => $address, "permission" => $permission]; }
php
protected function parseAccess($access) { $parts = explode(':', $access, 2); if (count($parts) != 2) { $message = sprintf( 'Access "<error>%s</error>" is not valid, please use the format: permission:address', $access ); throw new InvalidArgumentException($message); } if (!in_array($parts[0], ['allow', 'deny'])) { $message = sprintf( "The permission type '<error>%s</error>' is not valid; it must be one of 'allow' or 'deny'", $parts[0] ); throw new InvalidArgumentException($message); } list($permission, $address) = $parts; $this->validateAddress($address); // Normalize the address so that we can compare accurately with the // current value returned from the API. if ($address == 'any') { $address = '0.0.0.0/0'; } elseif ($address && !strpos($address, '/')) { $address .= '/32'; } return ["address" => $address, "permission" => $permission]; }
[ "protected", "function", "parseAccess", "(", "$", "access", ")", "{", "$", "parts", "=", "explode", "(", "':'", ",", "$", "access", ",", "2", ")", ";", "if", "(", "count", "(", "$", "parts", ")", "!=", "2", ")", "{", "$", "message", "=", "sprintf...
@param $access @throws InvalidArgumentException @return array
[ "@param", "$access" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentHttpAccessCommand.php#L83-L115
platformsh/platformsh-cli
src/Command/Environment/EnvironmentHttpAccessCommand.php
EnvironmentHttpAccessCommand.validateAddress
protected function validateAddress($address) { if ($address == 'any') { return; } $extractIp = preg_match('#^([^/]+)(/([0-9]{1,2}))?$#', $address, $matches); if (!$extractIp || !filter_var($matches[1], FILTER_VALIDATE_IP) || (isset($matches[3]) && $matches[3] > 32)) { $message = sprintf('The address "<error>%s</error>" is not a valid IP address or CIDR', $address); throw new InvalidArgumentException($message); } }
php
protected function validateAddress($address) { if ($address == 'any') { return; } $extractIp = preg_match('#^([^/]+)(/([0-9]{1,2}))?$#', $address, $matches); if (!$extractIp || !filter_var($matches[1], FILTER_VALIDATE_IP) || (isset($matches[3]) && $matches[3] > 32)) { $message = sprintf('The address "<error>%s</error>" is not a valid IP address or CIDR', $address); throw new InvalidArgumentException($message); } }
[ "protected", "function", "validateAddress", "(", "$", "address", ")", "{", "if", "(", "$", "address", "==", "'any'", ")", "{", "return", ";", "}", "$", "extractIp", "=", "preg_match", "(", "'#^([^/]+)(/([0-9]{1,2}))?$#'", ",", "$", "address", ",", "$", "ma...
@param string $address @throws InvalidArgumentException
[ "@param", "string", "$address" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentHttpAccessCommand.php#L122-L132
platformsh/platformsh-cli
src/Console/CustomTextDescriptor.php
CustomTextDescriptor.getColumnWidth
protected function getColumnWidth(array $commands) { $width = 0; foreach ($commands as $command) { $aliasesString = $this->formatAliases($command->getAliases()); $commandWidth = strlen($command->getName()) + strlen($aliasesString); $width = $commandWidth > $width ? $commandWidth : $width; } // Limit to a maximum. $terminalWidth = (new Terminal())->getWidth(); if ($width / $terminalWidth > 0.4) { $width = floor($terminalWidth * 0.4); } // Start at a minimum. if ($width < 20) { $width = 20; } // Add the indent. $width += 2; // Accommodate tags. $width += strlen('<info></info>'); return $width; }
php
protected function getColumnWidth(array $commands) { $width = 0; foreach ($commands as $command) { $aliasesString = $this->formatAliases($command->getAliases()); $commandWidth = strlen($command->getName()) + strlen($aliasesString); $width = $commandWidth > $width ? $commandWidth : $width; } // Limit to a maximum. $terminalWidth = (new Terminal())->getWidth(); if ($width / $terminalWidth > 0.4) { $width = floor($terminalWidth * 0.4); } // Start at a minimum. if ($width < 20) { $width = 20; } // Add the indent. $width += 2; // Accommodate tags. $width += strlen('<info></info>'); return $width; }
[ "protected", "function", "getColumnWidth", "(", "array", "$", "commands", ")", "{", "$", "width", "=", "0", ";", "foreach", "(", "$", "commands", "as", "$", "command", ")", "{", "$", "aliasesString", "=", "$", "this", "->", "formatAliases", "(", "$", "...
@param Command[] $commands @return int
[ "@param", "Command", "[]", "$commands" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/CustomTextDescriptor.php#L206-L233
platformsh/platformsh-cli
src/Console/CustomTextDescriptor.php
CustomTextDescriptor.describeInputOption
protected function describeInputOption(InputOption $option, array $options = array()) { if ($option->acceptValue() && null !== $option->getDefault() && (!is_array($option->getDefault()) || count($option->getDefault()))) { $default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($option->getDefault())); } else { $default = ''; } $value = ''; if ($option->acceptValue()) { $value = '='.strtoupper($option->getName()); if ($option->isValueOptional()) { $value = '['.$value.']'; } } $totalWidth = isset($options['total_width']) ? $options['total_width'] : $this->calculateTotalWidthForOptions(array($option)); $synopsis = sprintf('%s%s', $option->getShortcut() ? sprintf('-%s, ', $option->getShortcut()) : ' ', sprintf('--%s%s', $option->getName(), $value) ); $spacingWidth = $totalWidth - Helper::strlen($synopsis); // Ensure the description is indented and word-wrapped to fit the // terminal width. $descriptionWidth = (new Terminal())->getWidth() - $totalWidth - 4; $description = $option->getDescription(); $description .= $default; if ($option->isArray()) { $description .= '<comment> (multiple values allowed)</comment>'; } $description = preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), wordwrap($description, $descriptionWidth)); $this->writeText(sprintf(' <info>%s</info> %s%s', $synopsis, str_repeat(' ', $spacingWidth), $description ), $options); }
php
protected function describeInputOption(InputOption $option, array $options = array()) { if ($option->acceptValue() && null !== $option->getDefault() && (!is_array($option->getDefault()) || count($option->getDefault()))) { $default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($option->getDefault())); } else { $default = ''; } $value = ''; if ($option->acceptValue()) { $value = '='.strtoupper($option->getName()); if ($option->isValueOptional()) { $value = '['.$value.']'; } } $totalWidth = isset($options['total_width']) ? $options['total_width'] : $this->calculateTotalWidthForOptions(array($option)); $synopsis = sprintf('%s%s', $option->getShortcut() ? sprintf('-%s, ', $option->getShortcut()) : ' ', sprintf('--%s%s', $option->getName(), $value) ); $spacingWidth = $totalWidth - Helper::strlen($synopsis); // Ensure the description is indented and word-wrapped to fit the // terminal width. $descriptionWidth = (new Terminal())->getWidth() - $totalWidth - 4; $description = $option->getDescription(); $description .= $default; if ($option->isArray()) { $description .= '<comment> (multiple values allowed)</comment>'; } $description = preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), wordwrap($description, $descriptionWidth)); $this->writeText(sprintf(' <info>%s</info> %s%s', $synopsis, str_repeat(' ', $spacingWidth), $description ), $options); }
[ "protected", "function", "describeInputOption", "(", "InputOption", "$", "option", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "if", "(", "$", "option", "->", "acceptValue", "(", ")", "&&", "null", "!==", "$", "option", "->", "getDefa...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/CustomTextDescriptor.php#L238-L278
platformsh/platformsh-cli
src/Console/CustomTextDescriptor.php
CustomTextDescriptor.calculateTotalWidthForOptions
private function calculateTotalWidthForOptions(array $options) { $totalWidth = 0; foreach ($options as $option) { // "-" + shortcut + ", --" + name $nameLength = 1 + max(Helper::strlen($option->getShortcut()), 1) + 4 + Helper::strlen($option->getName()); if ($option->acceptValue()) { $valueLength = 1 + Helper::strlen($option->getName()); // = + value $valueLength += $option->isValueOptional() ? 2 : 0; // [ + ] $nameLength += $valueLength; } $totalWidth = max($totalWidth, $nameLength); } return $totalWidth; }
php
private function calculateTotalWidthForOptions(array $options) { $totalWidth = 0; foreach ($options as $option) { // "-" + shortcut + ", --" + name $nameLength = 1 + max(Helper::strlen($option->getShortcut()), 1) + 4 + Helper::strlen($option->getName()); if ($option->acceptValue()) { $valueLength = 1 + Helper::strlen($option->getName()); // = + value $valueLength += $option->isValueOptional() ? 2 : 0; // [ + ] $nameLength += $valueLength; } $totalWidth = max($totalWidth, $nameLength); } return $totalWidth; }
[ "private", "function", "calculateTotalWidthForOptions", "(", "array", "$", "options", ")", "{", "$", "totalWidth", "=", "0", ";", "foreach", "(", "$", "options", "as", "$", "option", ")", "{", "// \"-\" + shortcut + \", --\" + name", "$", "nameLength", "=", "1",...
@param InputOption[] $options @return int
[ "@param", "InputOption", "[]", "$options" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/CustomTextDescriptor.php#L285-L302
platformsh/platformsh-cli
src/Local/BuildFlavor/Drupal.php
Drupal.isDrupal
public static function isDrupal($directory, $depth = '< 2') { if (!is_dir($directory)) { return false; } $finder = new Finder(); // Look for at least one Drush make file. $finder->in($directory) ->files() ->depth($depth) ->exclude(['node_modules', 'vendor']) ->name('project.make*') ->name('drupal-org.make*'); foreach ($finder as $file) { return true; } // Check whether there is an index.php file whose first few lines // contain the word "Drupal". $finder->in($directory) ->files() ->depth($depth) ->name('index.php'); foreach ($finder as $file) { $f = fopen($file, 'r'); $beginning = fread($f, 3178); fclose($f); if (strpos($beginning, 'Drupal') !== false) { return true; } } // Check whether there is a composer.json file requiring Drupal core. $finder->in($directory) ->files() ->depth($depth) ->name('composer.json'); foreach ($finder as $file) { $composerJson = json_decode(file_get_contents($file), true); if (isset($composerJson['require']['drupal/core']) || isset($composerJson['require']['drupal/phing-drush-task'])) { return true; } } return false; }
php
public static function isDrupal($directory, $depth = '< 2') { if (!is_dir($directory)) { return false; } $finder = new Finder(); // Look for at least one Drush make file. $finder->in($directory) ->files() ->depth($depth) ->exclude(['node_modules', 'vendor']) ->name('project.make*') ->name('drupal-org.make*'); foreach ($finder as $file) { return true; } // Check whether there is an index.php file whose first few lines // contain the word "Drupal". $finder->in($directory) ->files() ->depth($depth) ->name('index.php'); foreach ($finder as $file) { $f = fopen($file, 'r'); $beginning = fread($f, 3178); fclose($f); if (strpos($beginning, 'Drupal') !== false) { return true; } } // Check whether there is a composer.json file requiring Drupal core. $finder->in($directory) ->files() ->depth($depth) ->name('composer.json'); foreach ($finder as $file) { $composerJson = json_decode(file_get_contents($file), true); if (isset($composerJson['require']['drupal/core']) || isset($composerJson['require']['drupal/phing-drush-task'])) { return true; } } return false; }
[ "public", "static", "function", "isDrupal", "(", "$", "directory", ",", "$", "depth", "=", "'< 2'", ")", "{", "if", "(", "!", "is_dir", "(", "$", "directory", ")", ")", "{", "return", "false", ";", "}", "$", "finder", "=", "new", "Finder", "(", ")"...
Detect if there are any Drupal applications in a folder. @param string $directory @param mixed $depth @return bool
[ "Detect", "if", "there", "are", "any", "Drupal", "applications", "in", "a", "folder", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/Drupal.php#L30-L78
platformsh/platformsh-cli
src/Local/BuildFlavor/Drupal.php
Drupal.checkIgnored
protected function checkIgnored($filename, $suggestion = null) { if (!file_exists($filename)) { return; } if (!$repositoryDir = $this->gitHelper->getRoot($this->appRoot)) { return; } $relative = $this->fsHelper->makePathRelative($filename, $repositoryDir); if (!$this->gitHelper->checkIgnore($relative, $repositoryDir)) { $suggestion = $suggestion ?: $relative; $this->stdErr->writeln("<comment>You should exclude this file using .gitignore:</comment> $suggestion"); } }
php
protected function checkIgnored($filename, $suggestion = null) { if (!file_exists($filename)) { return; } if (!$repositoryDir = $this->gitHelper->getRoot($this->appRoot)) { return; } $relative = $this->fsHelper->makePathRelative($filename, $repositoryDir); if (!$this->gitHelper->checkIgnore($relative, $repositoryDir)) { $suggestion = $suggestion ?: $relative; $this->stdErr->writeln("<comment>You should exclude this file using .gitignore:</comment> $suggestion"); } }
[ "protected", "function", "checkIgnored", "(", "$", "filename", ",", "$", "suggestion", "=", "null", ")", "{", "if", "(", "!", "file_exists", "(", "$", "filename", ")", ")", "{", "return", ";", "}", "if", "(", "!", "$", "repositoryDir", "=", "$", "thi...
Check that an application file is ignored in .gitignore. @param string $filename @param string $suggestion
[ "Check", "that", "an", "application", "file", "is", "ignored", "in", ".", "gitignore", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/Drupal.php#L112-L125
platformsh/platformsh-cli
src/Local/BuildFlavor/Drupal.php
Drupal.getDrushFlags
protected function getDrushFlags() { $drushFlags = [ '--yes', ]; $verbosity = $this->stdErr->getVerbosity(); if ($verbosity === OutputInterface::VERBOSITY_QUIET) { $drushFlags[] = '--quiet'; } elseif ($verbosity === OutputInterface::VERBOSITY_DEBUG) { $drushFlags[] = '--debug'; } elseif ($verbosity >= OutputInterface::VERBOSITY_VERY_VERBOSE) { $drushFlags[] = '--verbose'; } if (!empty($this->settings['working-copy'])) { $drushFlags[] = '--working-copy'; } if (!empty($this->settings['no-cache'])) { $drushFlags[] = '--no-cache'; } else { $drushFlags[] = '--cache-duration-releasexml=300'; } if (!empty($this->settings['concurrency'])) { $drushFlags[] = '--concurrency=' . $this->settings['concurrency']; } return $drushFlags; }
php
protected function getDrushFlags() { $drushFlags = [ '--yes', ]; $verbosity = $this->stdErr->getVerbosity(); if ($verbosity === OutputInterface::VERBOSITY_QUIET) { $drushFlags[] = '--quiet'; } elseif ($verbosity === OutputInterface::VERBOSITY_DEBUG) { $drushFlags[] = '--debug'; } elseif ($verbosity >= OutputInterface::VERBOSITY_VERY_VERBOSE) { $drushFlags[] = '--verbose'; } if (!empty($this->settings['working-copy'])) { $drushFlags[] = '--working-copy'; } if (!empty($this->settings['no-cache'])) { $drushFlags[] = '--no-cache'; } else { $drushFlags[] = '--cache-duration-releasexml=300'; } if (!empty($this->settings['concurrency'])) { $drushFlags[] = '--concurrency=' . $this->settings['concurrency']; } return $drushFlags; }
[ "protected", "function", "getDrushFlags", "(", ")", "{", "$", "drushFlags", "=", "[", "'--yes'", ",", "]", ";", "$", "verbosity", "=", "$", "this", "->", "stdErr", "->", "getVerbosity", "(", ")", ";", "if", "(", "$", "verbosity", "===", "OutputInterface"...
Set up options to pass to the drush commands. @return array
[ "Set", "up", "options", "to", "pass", "to", "the", "drush", "commands", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/Drupal.php#L132-L162
platformsh/platformsh-cli
src/Local/BuildFlavor/Drupal.php
Drupal.findDrushMakeFile
protected function findDrushMakeFile($required = false, $core = false) { $candidates = [ 'project.make.yml', 'project.make', 'drupal-org.make.yml', 'drupal-org.make', ]; if (!empty($this->settings['lock'])) { $candidates = array_merge([ 'project.make.lock', 'project.make.yml.lock', 'drupal-org.make.yml.lock', 'drupal-org.make.lock', ], $candidates); } foreach ($candidates as &$candidate) { if ($core) { $candidate = str_replace('.make', '-core.make', $candidate); } if (file_exists($this->appRoot . '/' . $candidate)) { return $this->appRoot . '/' . $candidate; } } if ($required) { throw new \Exception( ($core ? "Couldn't find a core make file in the directory." : "Couldn't find a make file in the directory." ) . " Possible filenames: " . implode(',', $candidates) ); } return false; }
php
protected function findDrushMakeFile($required = false, $core = false) { $candidates = [ 'project.make.yml', 'project.make', 'drupal-org.make.yml', 'drupal-org.make', ]; if (!empty($this->settings['lock'])) { $candidates = array_merge([ 'project.make.lock', 'project.make.yml.lock', 'drupal-org.make.yml.lock', 'drupal-org.make.lock', ], $candidates); } foreach ($candidates as &$candidate) { if ($core) { $candidate = str_replace('.make', '-core.make', $candidate); } if (file_exists($this->appRoot . '/' . $candidate)) { return $this->appRoot . '/' . $candidate; } } if ($required) { throw new \Exception( ($core ? "Couldn't find a core make file in the directory." : "Couldn't find a make file in the directory." ) . " Possible filenames: " . implode(',', $candidates) ); } return false; }
[ "protected", "function", "findDrushMakeFile", "(", "$", "required", "=", "false", ",", "$", "core", "=", "false", ")", "{", "$", "candidates", "=", "[", "'project.make.yml'", ",", "'project.make'", ",", "'drupal-org.make.yml'", ",", "'drupal-org.make'", ",", "]"...
Find the preferred Drush Make file in the app root. @param bool $required @param bool $core @throws \Exception @return string|false The absolute filename of the make file.
[ "Find", "the", "preferred", "Drush", "Make", "file", "in", "the", "app", "root", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/Drupal.php#L175-L210
platformsh/platformsh-cli
src/Local/BuildFlavor/Drupal.php
Drupal.buildInProjectMode
protected function buildInProjectMode($projectMake) { $drushHelper = $this->getDrushHelper(); $drushHelper->ensureInstalled(); $drushFlags = $this->getDrushFlags(); $drupalRoot = $this->getWebRoot(); $args = array_merge( ['make', $projectMake, $drupalRoot], $drushFlags ); // Create a lock file automatically. if (!strpos($projectMake, '.lock') && !empty($this->settings['lock']) && $drushHelper->supportsMakeLock()) { $args[] = "--lock=$projectMake.lock"; } // Run Drush make. // // Note that this is run inside the make file's directory. This fixes an // issue with the 'copy' Drush Make download type. According to the // Drush documentation, URLs for copying files can be either absolute or // relative to the make file's directory. However, in Drush's actual // implementation, it's actually relative to the current working // directory. $drushHelper->execute($args, dirname($projectMake), true, false); $this->processSettingsPhp(); $this->ignoredFiles[] = '*.make'; $this->ignoredFiles[] = '*.make.lock'; $this->ignoredFiles[] = '*.make.yml'; $this->ignoredFiles[] = '*.make.yml.lock'; $this->ignoredFiles[] = 'settings.local.php'; $this->specialDestinations['sites.php'] = '{webroot}/sites'; // Symlink, non-recursively, all files from the app into the // 'sites/default' directory. $this->fsHelper->symlinkAll( $this->appRoot, $drupalRoot . '/sites/default', true, false, array_merge($this->ignoredFiles, array_keys($this->specialDestinations)), $this->copy ); }
php
protected function buildInProjectMode($projectMake) { $drushHelper = $this->getDrushHelper(); $drushHelper->ensureInstalled(); $drushFlags = $this->getDrushFlags(); $drupalRoot = $this->getWebRoot(); $args = array_merge( ['make', $projectMake, $drupalRoot], $drushFlags ); // Create a lock file automatically. if (!strpos($projectMake, '.lock') && !empty($this->settings['lock']) && $drushHelper->supportsMakeLock()) { $args[] = "--lock=$projectMake.lock"; } // Run Drush make. // // Note that this is run inside the make file's directory. This fixes an // issue with the 'copy' Drush Make download type. According to the // Drush documentation, URLs for copying files can be either absolute or // relative to the make file's directory. However, in Drush's actual // implementation, it's actually relative to the current working // directory. $drushHelper->execute($args, dirname($projectMake), true, false); $this->processSettingsPhp(); $this->ignoredFiles[] = '*.make'; $this->ignoredFiles[] = '*.make.lock'; $this->ignoredFiles[] = '*.make.yml'; $this->ignoredFiles[] = '*.make.yml.lock'; $this->ignoredFiles[] = 'settings.local.php'; $this->specialDestinations['sites.php'] = '{webroot}/sites'; // Symlink, non-recursively, all files from the app into the // 'sites/default' directory. $this->fsHelper->symlinkAll( $this->appRoot, $drupalRoot . '/sites/default', true, false, array_merge($this->ignoredFiles, array_keys($this->specialDestinations)), $this->copy ); }
[ "protected", "function", "buildInProjectMode", "(", "$", "projectMake", ")", "{", "$", "drushHelper", "=", "$", "this", "->", "getDrushHelper", "(", ")", ";", "$", "drushHelper", "->", "ensureInstalled", "(", ")", ";", "$", "drushFlags", "=", "$", "this", ...
Build in 'project' mode, i.e. just using a Drush make file. @param string $projectMake
[ "Build", "in", "project", "mode", "i", ".", "e", ".", "just", "using", "a", "Drush", "make", "file", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/Drupal.php#L230-L277
platformsh/platformsh-cli
src/Local/BuildFlavor/Drupal.php
Drupal.buildInProfileMode
protected function buildInProfileMode($profileName) { $drushHelper = $this->getDrushHelper(); $drushHelper->ensureInstalled(); $drushFlags = $this->getDrushFlags(); $updateLock = !empty($this->settings['lock']) && $drushHelper->supportsMakeLock(); $projectMake = $this->findDrushMakeFile(true); $projectCoreMake = $this->findDrushMakeFile(true, true); $drupalRoot = $this->getWebRoot(); $this->stdErr->writeln("Building profile <info>$profileName</info>"); $profileDir = $drupalRoot . '/profiles/' . $profileName; if ($projectMake) { // Create a temporary profile directory. If it already exists, // ensure that it is empty. $tempProfileDir = $this->buildDir . '/tmp-' . $profileName; if (file_exists($tempProfileDir)) { $this->fsHelper->remove($tempProfileDir); } $this->fsHelper->mkdir($tempProfileDir); $args = array_merge( ['make', '--no-core', '--contrib-destination=.', $projectMake, $tempProfileDir], $drushFlags ); // Create a lock file automatically. if (!strpos($projectMake, '.lock') && $updateLock) { $args[] = "--lock=$projectMake.lock"; } $drushHelper->execute($args, dirname($projectMake), true, false); } if ($projectCoreMake) { $args = array_merge( ['make', $projectCoreMake, $drupalRoot], $drushFlags ); // Create a lock file automatically. if (!strpos($projectCoreMake, '.lock') && $updateLock) { $args[] = "--lock=$projectCoreMake.lock"; } $drushHelper->execute($args, dirname($projectCoreMake), true, false); } if (!empty($tempProfileDir) && is_dir($tempProfileDir) && !rename($tempProfileDir, $profileDir)) { throw new \RuntimeException('Failed to move profile directory to: ' . $profileDir); } if ($this->copy) { $this->stdErr->writeln("Copying existing app files to the profile"); } else { $this->stdErr->writeln("Symlinking existing app files to the profile"); } $this->ignoredFiles[] = '*.make'; $this->ignoredFiles[] = '*.make.lock'; $this->ignoredFiles[] = '*.make.yml'; $this->ignoredFiles[] = '*.make.yml.lock'; $this->ignoredFiles[] = 'settings.local.php'; $this->specialDestinations['settings*.php'] = '{webroot}/sites/default'; $this->specialDestinations['sites.php'] = '{webroot}/sites'; $this->processSettingsPhp(); // Symlink recursively; skip existing files (built by Drush make) for // example 'modules/contrib', but include files from the app such as // 'modules/custom'. $this->fsHelper->symlinkAll( $this->appRoot, $profileDir, true, true, array_merge($this->ignoredFiles, array_keys($this->specialDestinations)), $this->copy ); }
php
protected function buildInProfileMode($profileName) { $drushHelper = $this->getDrushHelper(); $drushHelper->ensureInstalled(); $drushFlags = $this->getDrushFlags(); $updateLock = !empty($this->settings['lock']) && $drushHelper->supportsMakeLock(); $projectMake = $this->findDrushMakeFile(true); $projectCoreMake = $this->findDrushMakeFile(true, true); $drupalRoot = $this->getWebRoot(); $this->stdErr->writeln("Building profile <info>$profileName</info>"); $profileDir = $drupalRoot . '/profiles/' . $profileName; if ($projectMake) { // Create a temporary profile directory. If it already exists, // ensure that it is empty. $tempProfileDir = $this->buildDir . '/tmp-' . $profileName; if (file_exists($tempProfileDir)) { $this->fsHelper->remove($tempProfileDir); } $this->fsHelper->mkdir($tempProfileDir); $args = array_merge( ['make', '--no-core', '--contrib-destination=.', $projectMake, $tempProfileDir], $drushFlags ); // Create a lock file automatically. if (!strpos($projectMake, '.lock') && $updateLock) { $args[] = "--lock=$projectMake.lock"; } $drushHelper->execute($args, dirname($projectMake), true, false); } if ($projectCoreMake) { $args = array_merge( ['make', $projectCoreMake, $drupalRoot], $drushFlags ); // Create a lock file automatically. if (!strpos($projectCoreMake, '.lock') && $updateLock) { $args[] = "--lock=$projectCoreMake.lock"; } $drushHelper->execute($args, dirname($projectCoreMake), true, false); } if (!empty($tempProfileDir) && is_dir($tempProfileDir) && !rename($tempProfileDir, $profileDir)) { throw new \RuntimeException('Failed to move profile directory to: ' . $profileDir); } if ($this->copy) { $this->stdErr->writeln("Copying existing app files to the profile"); } else { $this->stdErr->writeln("Symlinking existing app files to the profile"); } $this->ignoredFiles[] = '*.make'; $this->ignoredFiles[] = '*.make.lock'; $this->ignoredFiles[] = '*.make.yml'; $this->ignoredFiles[] = '*.make.yml.lock'; $this->ignoredFiles[] = 'settings.local.php'; $this->specialDestinations['settings*.php'] = '{webroot}/sites/default'; $this->specialDestinations['sites.php'] = '{webroot}/sites'; $this->processSettingsPhp(); // Symlink recursively; skip existing files (built by Drush make) for // example 'modules/contrib', but include files from the app such as // 'modules/custom'. $this->fsHelper->symlinkAll( $this->appRoot, $profileDir, true, true, array_merge($this->ignoredFiles, array_keys($this->specialDestinations)), $this->copy ); }
[ "protected", "function", "buildInProfileMode", "(", "$", "profileName", ")", "{", "$", "drushHelper", "=", "$", "this", "->", "getDrushHelper", "(", ")", ";", "$", "drushHelper", "->", "ensureInstalled", "(", ")", ";", "$", "drushFlags", "=", "$", "this", ...
Build in 'profile' mode: the application contains a site profile. @param string $profileName
[ "Build", "in", "profile", "mode", ":", "the", "application", "contains", "a", "site", "profile", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/Drupal.php#L284-L368
platformsh/platformsh-cli
src/Local/BuildFlavor/Drupal.php
Drupal.processSettingsPhp
protected function processSettingsPhp() { if ($this->copy) { // This behaviour only relates to symlinking. return; } $settingsPhpFile = $this->appRoot . '/settings.php'; if (file_exists($settingsPhpFile)) { $this->stdErr->writeln("Found a custom settings.php file: $settingsPhpFile"); $this->fsHelper->copy($settingsPhpFile, $this->getWebRoot() . '/sites/default/settings.php'); $this->stdErr->writeln( " <comment>Your settings.php file has been copied (not symlinked) into the build directory." . "\n You will need to rebuild if you edit this file.</comment>" ); $this->ignoredFiles[] = 'settings.php'; } }
php
protected function processSettingsPhp() { if ($this->copy) { // This behaviour only relates to symlinking. return; } $settingsPhpFile = $this->appRoot . '/settings.php'; if (file_exists($settingsPhpFile)) { $this->stdErr->writeln("Found a custom settings.php file: $settingsPhpFile"); $this->fsHelper->copy($settingsPhpFile, $this->getWebRoot() . '/sites/default/settings.php'); $this->stdErr->writeln( " <comment>Your settings.php file has been copied (not symlinked) into the build directory." . "\n You will need to rebuild if you edit this file.</comment>" ); $this->ignoredFiles[] = 'settings.php'; } }
[ "protected", "function", "processSettingsPhp", "(", ")", "{", "if", "(", "$", "this", "->", "copy", ")", "{", "// This behaviour only relates to symlinking.", "return", ";", "}", "$", "settingsPhpFile", "=", "$", "this", "->", "appRoot", ".", "'/settings.php'", ...
Handle a custom settings.php file for project and profile mode. If the user has a custom settings.php file, and we symlink it into sites/default, then it will probably fail to pick up settings.local.php from the right place. So we need to copy the settings.php instead of symlinking it. See https://github.com/platformsh/platformsh-cli/issues/175
[ "Handle", "a", "custom", "settings", ".", "php", "file", "for", "project", "and", "profile", "mode", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/Drupal.php#L380-L396
platformsh/platformsh-cli
src/Command/DocsCommand.php
DocsCommand.getSearchQuery
protected function getSearchQuery(array $args) { return implode(' ', array_map(function ($term) { return strpos($term, ' ') ? '"' . $term . '"' : $term; }, $args)); }
php
protected function getSearchQuery(array $args) { return implode(' ', array_map(function ($term) { return strpos($term, ' ') ? '"' . $term . '"' : $term; }, $args)); }
[ "protected", "function", "getSearchQuery", "(", "array", "$", "args", ")", "{", "return", "implode", "(", "' '", ",", "array_map", "(", "function", "(", "$", "term", ")", "{", "return", "strpos", "(", "$", "term", ",", "' '", ")", "?", "'\"'", ".", "...
Turn a list of command arguments into a search query. Arguments containing a space would have been quoted on the command line, so quotes are added again here. @param string[] $args @return string
[ "Turn", "a", "list", "of", "command", "arguments", "into", "a", "search", "query", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/DocsCommand.php#L47-L52
platformsh/platformsh-cli
src/Console/ProcessManager.php
ProcessManager.fork
public static function fork() { $pid = pcntl_fork(); if ($pid === -1) { throw new \RuntimeException('Failed to fork PHP process'); } elseif ($pid > 0) { // This is the parent process. If the child process succeeds, this // receives SIGCHLD. If it fails, this receives SIGTERM. declare (ticks = 1); pcntl_signal(SIGCHLD, function () { exit; }); pcntl_signal(SIGTERM, function () { exit(1); }); // Wait a reasonable amount of time for the child processes to // finish. sleep(60); throw new \RuntimeException('Timeout in parent process'); } elseif (posix_setsid() === -1) { throw new \RuntimeException('Child process failed to become session leader'); } }
php
public static function fork() { $pid = pcntl_fork(); if ($pid === -1) { throw new \RuntimeException('Failed to fork PHP process'); } elseif ($pid > 0) { // This is the parent process. If the child process succeeds, this // receives SIGCHLD. If it fails, this receives SIGTERM. declare (ticks = 1); pcntl_signal(SIGCHLD, function () { exit; }); pcntl_signal(SIGTERM, function () { exit(1); }); // Wait a reasonable amount of time for the child processes to // finish. sleep(60); throw new \RuntimeException('Timeout in parent process'); } elseif (posix_setsid() === -1) { throw new \RuntimeException('Child process failed to become session leader'); } }
[ "public", "static", "function", "fork", "(", ")", "{", "$", "pid", "=", "pcntl_fork", "(", ")", ";", "if", "(", "$", "pid", "===", "-", "1", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Failed to fork PHP process'", ")", ";", "}", "elseif...
Fork the current PHP process. Code run after this method is run in a child process. The parent process merely waits for a SIGCHLD (successful) or SIGTERM (error) signal from the child. This depends on the PCNTL extension.
[ "Fork", "the", "current", "PHP", "process", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/ProcessManager.php#L65-L88
platformsh/platformsh-cli
src/Console/ProcessManager.php
ProcessManager.startProcess
public function startProcess(Process $process, $pidFile, OutputInterface $log) { $this->processes[$pidFile] = $process; try { $process->start(function ($type, $buffer) use ($log) { $output = $log instanceof ConsoleOutputInterface && $type === Process::ERR ? $log->getErrorOutput() : $log; $output->write($buffer); }); } catch (\Exception $e) { unset($this->processes[$pidFile]); throw $e; } $pid = $process->getPid(); if (file_put_contents($pidFile, $pid) === false) { throw new \RuntimeException('Failed to write PID file: ' . $pidFile); } $log->writeln(sprintf('Process started: %s', $process->getCommandLine())); return $pid; }
php
public function startProcess(Process $process, $pidFile, OutputInterface $log) { $this->processes[$pidFile] = $process; try { $process->start(function ($type, $buffer) use ($log) { $output = $log instanceof ConsoleOutputInterface && $type === Process::ERR ? $log->getErrorOutput() : $log; $output->write($buffer); }); } catch (\Exception $e) { unset($this->processes[$pidFile]); throw $e; } $pid = $process->getPid(); if (file_put_contents($pidFile, $pid) === false) { throw new \RuntimeException('Failed to write PID file: ' . $pidFile); } $log->writeln(sprintf('Process started: %s', $process->getCommandLine())); return $pid; }
[ "public", "function", "startProcess", "(", "Process", "$", "process", ",", "$", "pidFile", ",", "OutputInterface", "$", "log", ")", "{", "$", "this", "->", "processes", "[", "$", "pidFile", "]", "=", "$", "process", ";", "try", "{", "$", "process", "->...
Start a managed external process. @param Process $process The Symfony Process object to manage. @param string $pidFile The path to a lock file which governs the process: if the file is deleted then the process will be stopped in self::monitor(). @param OutputInterface $log An output stream to which log messages can be written. @throws \Exception on failure @return int The process PID.
[ "Start", "a", "managed", "external", "process", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/ProcessManager.php#L119-L143
platformsh/platformsh-cli
src/Console/ProcessManager.php
ProcessManager.monitor
public function monitor(OutputInterface $log) { while (count($this->processes)) { sleep(1); foreach ($this->processes as $pidFile => $process) { // The user can delete the PID file in order to stop the // process deliberately. if (!file_exists($pidFile)) { $log->writeln(sprintf('Process stopped: %s', $process->getCommandLine())); $process->stop(); unset($this->processes[$pidFile]); } elseif (!$process->isRunning()) { // If the process has been stopped via another method, remove it // from the list, and log a message. $exitCode = $process->getExitCode(); if ($signal = $this->getSignal($exitCode)) { $log->writeln(sprintf('Process stopped with signal %s: %s', $signal, $process->getCommandLine())); } elseif ($exitCode > 0) { $log->writeln(sprintf( 'Process failed with exit code %s: %s', $exitCode, $process->getCommandLine() )); } else { $log->writeln(sprintf( 'Process stopped with exit code %s: %s', $exitCode, $process->getCommandLine() )); } unlink($pidFile); unset($this->processes[$pidFile]); } } } }
php
public function monitor(OutputInterface $log) { while (count($this->processes)) { sleep(1); foreach ($this->processes as $pidFile => $process) { // The user can delete the PID file in order to stop the // process deliberately. if (!file_exists($pidFile)) { $log->writeln(sprintf('Process stopped: %s', $process->getCommandLine())); $process->stop(); unset($this->processes[$pidFile]); } elseif (!$process->isRunning()) { // If the process has been stopped via another method, remove it // from the list, and log a message. $exitCode = $process->getExitCode(); if ($signal = $this->getSignal($exitCode)) { $log->writeln(sprintf('Process stopped with signal %s: %s', $signal, $process->getCommandLine())); } elseif ($exitCode > 0) { $log->writeln(sprintf( 'Process failed with exit code %s: %s', $exitCode, $process->getCommandLine() )); } else { $log->writeln(sprintf( 'Process stopped with exit code %s: %s', $exitCode, $process->getCommandLine() )); } unlink($pidFile); unset($this->processes[$pidFile]); } } } }
[ "public", "function", "monitor", "(", "OutputInterface", "$", "log", ")", "{", "while", "(", "count", "(", "$", "this", "->", "processes", ")", ")", "{", "sleep", "(", "1", ")", ";", "foreach", "(", "$", "this", "->", "processes", "as", "$", "pidFile...
Monitor processes and stop them if their PID file no longer exists. @param OutputInterface $log A log file as a Symfony Console output object.
[ "Monitor", "processes", "and", "stop", "them", "if", "their", "PID", "file", "no", "longer", "exists", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Console/ProcessManager.php#L151-L186
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.api
protected function api() { if (!isset($this->api)) { $this->api = $this->getService('api'); $this->api ->dispatcher ->addListener('login_required', [$this, 'login']); $this->api ->dispatcher ->addListener('environments_changed', [$this, 'updateDrushAliases']); } return $this->api; }
php
protected function api() { if (!isset($this->api)) { $this->api = $this->getService('api'); $this->api ->dispatcher ->addListener('login_required', [$this, 'login']); $this->api ->dispatcher ->addListener('environments_changed', [$this, 'updateDrushAliases']); } return $this->api; }
[ "protected", "function", "api", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "api", ")", ")", "{", "$", "this", "->", "api", "=", "$", "this", "->", "getService", "(", "'api'", ")", ";", "$", "this", "->", "api", "->", "dispa...
Set up the API object. @return \Platformsh\Cli\Service\Api
[ "Set", "up", "the", "API", "object", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L140-L153
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.promptLegacyMigrate
private function promptLegacyMigrate() { static $asked = false; /** @var \Platformsh\Cli\Local\LocalProject $localProject */ $localProject = $this->getService('local.project'); if ($localProject->getLegacyProjectRoot() && $this->getName() !== 'legacy-migrate' && !$asked) { $asked = true; $projectRoot = $this->getProjectRoot(); $timestamp = time(); $promptMigrate = true; if ($projectRoot) { $projectConfig = $localProject->getProjectConfig($projectRoot); if (isset($projectConfig['migrate']['3.x']['last_asked']) && $projectConfig['migrate']['3.x']['last_asked'] > $timestamp - 3600) { $promptMigrate = false; } } $this->stdErr->writeln(sprintf( 'You are in a project using an old file structure, from previous versions of the %s.', $this->config()->get('application.name') )); if ($this->input->isInteractive() && $promptMigrate) { if ($projectRoot && isset($projectConfig)) { $projectConfig['migrate']['3.x']['last_asked'] = $timestamp; $localProject->writeCurrentProjectConfig($projectConfig, $projectRoot); } /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); if ($questionHelper->confirm('Migrate to the new structure?')) { $code = $this->runOtherCommand('legacy-migrate'); exit($code); } } else { $this->stdErr->writeln(sprintf( 'Fix this with: <comment>%s legacy-migrate</comment>', $this->config()->get('application.executable') )); } $this->stdErr->writeln(''); } }
php
private function promptLegacyMigrate() { static $asked = false; /** @var \Platformsh\Cli\Local\LocalProject $localProject */ $localProject = $this->getService('local.project'); if ($localProject->getLegacyProjectRoot() && $this->getName() !== 'legacy-migrate' && !$asked) { $asked = true; $projectRoot = $this->getProjectRoot(); $timestamp = time(); $promptMigrate = true; if ($projectRoot) { $projectConfig = $localProject->getProjectConfig($projectRoot); if (isset($projectConfig['migrate']['3.x']['last_asked']) && $projectConfig['migrate']['3.x']['last_asked'] > $timestamp - 3600) { $promptMigrate = false; } } $this->stdErr->writeln(sprintf( 'You are in a project using an old file structure, from previous versions of the %s.', $this->config()->get('application.name') )); if ($this->input->isInteractive() && $promptMigrate) { if ($projectRoot && isset($projectConfig)) { $projectConfig['migrate']['3.x']['last_asked'] = $timestamp; $localProject->writeCurrentProjectConfig($projectConfig, $projectRoot); } /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); if ($questionHelper->confirm('Migrate to the new structure?')) { $code = $this->runOtherCommand('legacy-migrate'); exit($code); } } else { $this->stdErr->writeln(sprintf( 'Fix this with: <comment>%s legacy-migrate</comment>', $this->config()->get('application.executable') )); } $this->stdErr->writeln(''); } }
[ "private", "function", "promptLegacyMigrate", "(", ")", "{", "static", "$", "asked", "=", "false", ";", "/** @var \\Platformsh\\Cli\\Local\\LocalProject $localProject */", "$", "localProject", "=", "$", "this", "->", "getService", "(", "'local.project'", ")", ";", "if...
Prompt the user to migrate from the legacy project file structure. If the input is interactive, the user will be asked to migrate up to once per hour. The time they were last asked will be stored in the project configuration. If the input is not interactive, the user will be warned (on every command run) that they should run the 'legacy-migrate' command.
[ "Prompt", "the", "user", "to", "migrate", "from", "the", "legacy", "project", "file", "structure", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L163-L205
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.interact
protected function interact(InputInterface $input, OutputInterface $output) { // Work around a bug in Console which means the default command's input // is always considered to be interactive. if ($this->getName() === 'welcome' && isset($GLOBALS['argv']) && array_intersect($GLOBALS['argv'], ['-n', '--no', '-y', '---yes'])) { $input->setInteractive(false); return; } $this->checkUpdates(); }
php
protected function interact(InputInterface $input, OutputInterface $output) { // Work around a bug in Console which means the default command's input // is always considered to be interactive. if ($this->getName() === 'welcome' && isset($GLOBALS['argv']) && array_intersect($GLOBALS['argv'], ['-n', '--no', '-y', '---yes'])) { $input->setInteractive(false); return; } $this->checkUpdates(); }
[ "protected", "function", "interact", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "// Work around a bug in Console which means the default command's input", "// is always considered to be interactive.", "if", "(", "$", "this", "->", "g...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L210-L222
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.checkUpdates
protected function checkUpdates() { // Avoid checking more than once in this process. if (self::$checkedUpdates) { return; } self::$checkedUpdates = true; // Check that the Phar extension is available. if (!extension_loaded('Phar')) { return; } // Get the filename of the Phar, or stop if this instance of the CLI is // not a Phar. $pharFilename = \Phar::running(false); if (!$pharFilename) { return; } // Check if the file is writable. if (!is_writable($pharFilename)) { return; } // Check if updates are configured. $config = $this->config(); if (!$config->get('updates.check')) { return; } // Determine an embargo time, after which updates can be checked. $timestamp = time(); $embargoTime = $timestamp - $config->get('updates.check_interval'); // Stop if updates were last checked after the embargo time. /** @var \Platformsh\Cli\Service\State $state */ $state = $this->getService('state'); if ($state->get('updates.last_checked') > $embargoTime) { return; } // Stop if the Phar was updated after the embargo time. if (filemtime($pharFilename) > $embargoTime) { return; } // Ensure classes are auto-loaded if they may be needed after the // update. /** @var \Platformsh\Cli\Service\Shell $shell */ $shell = $this->getService('shell'); /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $currentVersion = $this->config()->get('application.version'); /** @var \Platformsh\Cli\Service\SelfUpdater $cliUpdater */ $cliUpdater = $this->getService('self_updater'); $cliUpdater->setAllowMajor(true); $cliUpdater->setTimeout(5); try { $newVersion = $cliUpdater->update(null, $currentVersion); } catch (\RuntimeException $e) { if (strpos($e->getMessage(), 'Failed to download') !== false) { $this->stdErr->writeln('<error>' . $e->getMessage() . '</error>'); $newVersion = false; } else { throw $e; } } $state->set('updates.last_checked', $timestamp); // If the update was successful, and it's not a major version change, // then prompt the user to continue after updating. if ($newVersion !== false) { $exitCode = 0; list($currentMajorVersion,) = explode('.', $currentVersion, 2); list($newMajorVersion,) = explode('.', $newVersion, 2); if ($newMajorVersion === $currentMajorVersion && isset($this->input) && $this->input instanceof ArgvInput && is_executable($pharFilename)) { $originalCommand = $this->input->__toString(); $questionText = "\n" . 'Original command: <info>' . $originalCommand . '</info>' . "\n\n" . 'Continue?'; if ($questionHelper->confirm($questionText)) { $this->stdErr->writeln(''); $exitCode = $shell->executeSimple(escapeshellarg($pharFilename) . ' ' . $originalCommand); } } exit($exitCode); } $this->stdErr->writeln(''); }
php
protected function checkUpdates() { // Avoid checking more than once in this process. if (self::$checkedUpdates) { return; } self::$checkedUpdates = true; // Check that the Phar extension is available. if (!extension_loaded('Phar')) { return; } // Get the filename of the Phar, or stop if this instance of the CLI is // not a Phar. $pharFilename = \Phar::running(false); if (!$pharFilename) { return; } // Check if the file is writable. if (!is_writable($pharFilename)) { return; } // Check if updates are configured. $config = $this->config(); if (!$config->get('updates.check')) { return; } // Determine an embargo time, after which updates can be checked. $timestamp = time(); $embargoTime = $timestamp - $config->get('updates.check_interval'); // Stop if updates were last checked after the embargo time. /** @var \Platformsh\Cli\Service\State $state */ $state = $this->getService('state'); if ($state->get('updates.last_checked') > $embargoTime) { return; } // Stop if the Phar was updated after the embargo time. if (filemtime($pharFilename) > $embargoTime) { return; } // Ensure classes are auto-loaded if they may be needed after the // update. /** @var \Platformsh\Cli\Service\Shell $shell */ $shell = $this->getService('shell'); /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $currentVersion = $this->config()->get('application.version'); /** @var \Platformsh\Cli\Service\SelfUpdater $cliUpdater */ $cliUpdater = $this->getService('self_updater'); $cliUpdater->setAllowMajor(true); $cliUpdater->setTimeout(5); try { $newVersion = $cliUpdater->update(null, $currentVersion); } catch (\RuntimeException $e) { if (strpos($e->getMessage(), 'Failed to download') !== false) { $this->stdErr->writeln('<error>' . $e->getMessage() . '</error>'); $newVersion = false; } else { throw $e; } } $state->set('updates.last_checked', $timestamp); // If the update was successful, and it's not a major version change, // then prompt the user to continue after updating. if ($newVersion !== false) { $exitCode = 0; list($currentMajorVersion,) = explode('.', $currentVersion, 2); list($newMajorVersion,) = explode('.', $newVersion, 2); if ($newMajorVersion === $currentMajorVersion && isset($this->input) && $this->input instanceof ArgvInput && is_executable($pharFilename)) { $originalCommand = $this->input->__toString(); $questionText = "\n" . 'Original command: <info>' . $originalCommand . '</info>' . "\n\n" . 'Continue?'; if ($questionHelper->confirm($questionText)) { $this->stdErr->writeln(''); $exitCode = $shell->executeSimple(escapeshellarg($pharFilename) . ' ' . $originalCommand); } } exit($exitCode); } $this->stdErr->writeln(''); }
[ "protected", "function", "checkUpdates", "(", ")", "{", "// Avoid checking more than once in this process.", "if", "(", "self", "::", "$", "checkedUpdates", ")", "{", "return", ";", "}", "self", "::", "$", "checkedUpdates", "=", "true", ";", "// Check that the Phar ...
Check for updates.
[ "Check", "for", "updates", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L227-L323
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.login
public function login() { $success = false; if ($this->output && $this->input && $this->input->isInteractive()) { $method = $this->config()->getWithDefault('application.login_method', 'browser'); if ($method === 'browser') { /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $urlService = $this->getService('url'); if ($urlService->canOpenUrls() && $questionHelper->confirm("Authentication is required.\nLog in via a browser?")) { $this->stdErr->writeln(''); $exitCode = $this->runOtherCommand('auth:browser-login'); $this->stdErr->writeln(''); $success = $exitCode === 0; } } elseif ($method === 'password') { $exitCode = $this->runOtherCommand('auth:password-login'); $this->stdErr->writeln(''); $success = $exitCode === 0; } } if (!$success) { throw new LoginRequiredException(); } }
php
public function login() { $success = false; if ($this->output && $this->input && $this->input->isInteractive()) { $method = $this->config()->getWithDefault('application.login_method', 'browser'); if ($method === 'browser') { /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $urlService = $this->getService('url'); if ($urlService->canOpenUrls() && $questionHelper->confirm("Authentication is required.\nLog in via a browser?")) { $this->stdErr->writeln(''); $exitCode = $this->runOtherCommand('auth:browser-login'); $this->stdErr->writeln(''); $success = $exitCode === 0; } } elseif ($method === 'password') { $exitCode = $this->runOtherCommand('auth:password-login'); $this->stdErr->writeln(''); $success = $exitCode === 0; } } if (!$success) { throw new LoginRequiredException(); } }
[ "public", "function", "login", "(", ")", "{", "$", "success", "=", "false", ";", "if", "(", "$", "this", "->", "output", "&&", "$", "this", "->", "input", "&&", "$", "this", "->", "input", "->", "isInteractive", "(", ")", ")", "{", "$", "method", ...
Log in the user. This is called via the 'login_required' event. @see Api::getClient()
[ "Log", "in", "the", "user", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L332-L357
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.getCurrentProject
public function getCurrentProject() { if (isset($this->currentProject)) { return $this->currentProject; } if (!$projectRoot = $this->getProjectRoot()) { return false; } $project = false; /** @var \Platformsh\Cli\Local\LocalProject $localProject */ $localProject = $this->getService('local.project'); $config = $localProject->getProjectConfig($projectRoot); if ($config) { $project = $this->api()->getProject($config['id'], isset($config['host']) ? $config['host'] : null); if (!$project) { throw new ProjectNotFoundException( "Project not found: " . $config['id'] . "\nEither you do not have access to the project or it no longer exists." ); } $this->debug('Project ' . $config['id'] . ' is mapped to the current directory'); } $this->currentProject = $project; return $project; }
php
public function getCurrentProject() { if (isset($this->currentProject)) { return $this->currentProject; } if (!$projectRoot = $this->getProjectRoot()) { return false; } $project = false; /** @var \Platformsh\Cli\Local\LocalProject $localProject */ $localProject = $this->getService('local.project'); $config = $localProject->getProjectConfig($projectRoot); if ($config) { $project = $this->api()->getProject($config['id'], isset($config['host']) ? $config['host'] : null); if (!$project) { throw new ProjectNotFoundException( "Project not found: " . $config['id'] . "\nEither you do not have access to the project or it no longer exists." ); } $this->debug('Project ' . $config['id'] . ' is mapped to the current directory'); } $this->currentProject = $project; return $project; }
[ "public", "function", "getCurrentProject", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "currentProject", ")", ")", "{", "return", "$", "this", "->", "currentProject", ";", "}", "if", "(", "!", "$", "projectRoot", "=", "$", "this", "->", ...
Get the current project if the user is in a project directory. @throws \RuntimeException @return Project|false The current project
[ "Get", "the", "current", "project", "if", "the", "user", "is", "in", "a", "project", "directory", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L376-L402
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.getCurrentEnvironment
public function getCurrentEnvironment(Project $expectedProject = null, $refresh = null) { if (!($projectRoot = $this->getProjectRoot()) || !($project = $this->getCurrentProject()) || ($expectedProject !== null && $expectedProject->id !== $project->id)) { return false; } /** @var \Platformsh\Cli\Service\Git $git */ $git = $this->getService('git'); $git->setDefaultRepositoryDir($this->getProjectRoot()); /** @var \Platformsh\Cli\Local\LocalProject $localProject */ $localProject = $this->getService('local.project'); $config = $localProject->getProjectConfig($projectRoot); // Check if there is a manual mapping set for the current branch. if (!empty($config['mapping']) && ($currentBranch = $git->getCurrentBranch()) && !empty($config['mapping'][$currentBranch])) { $environment = $this->api()->getEnvironment($config['mapping'][$currentBranch], $project, $refresh); if ($environment) { $this->debug('Found mapped environment for branch ' . $currentBranch . ': ' . $this->api()->getEnvironmentLabel($environment)); return $environment; } else { unset($config['mapping'][$currentBranch]); $localProject->writeCurrentProjectConfig($config, $projectRoot); } } // Check whether the user has a Git upstream set to a remote environment // ID. $upstream = $git->getUpstream(); if ($upstream && strpos($upstream, '/') !== false) { list(, $potentialEnvironment) = explode('/', $upstream, 2); $environment = $this->api()->getEnvironment($potentialEnvironment, $project, $refresh); if ($environment) { $this->debug('Selected environment ' . $this->api()->getEnvironmentLabel($environment) . ', based on Git upstream: ' . $upstream); return $environment; } } // There is no Git remote set. Fall back to trying the current branch // name. if (!empty($currentBranch) || ($currentBranch = $git->getCurrentBranch())) { $environment = $this->api()->getEnvironment($currentBranch, $project, $refresh); if (!$environment) { // Try a sanitized version of the branch name too. $currentBranchSanitized = Environment::sanitizeId($currentBranch); if ($currentBranchSanitized !== $currentBranch) { $environment = $this->api()->getEnvironment($currentBranchSanitized, $project, $refresh); } } if ($environment) { $this->debug('Selected environment ' . $this->api()->getEnvironmentLabel($environment) . ' based on branch name: ' . $currentBranch); return $environment; } } return false; }
php
public function getCurrentEnvironment(Project $expectedProject = null, $refresh = null) { if (!($projectRoot = $this->getProjectRoot()) || !($project = $this->getCurrentProject()) || ($expectedProject !== null && $expectedProject->id !== $project->id)) { return false; } /** @var \Platformsh\Cli\Service\Git $git */ $git = $this->getService('git'); $git->setDefaultRepositoryDir($this->getProjectRoot()); /** @var \Platformsh\Cli\Local\LocalProject $localProject */ $localProject = $this->getService('local.project'); $config = $localProject->getProjectConfig($projectRoot); // Check if there is a manual mapping set for the current branch. if (!empty($config['mapping']) && ($currentBranch = $git->getCurrentBranch()) && !empty($config['mapping'][$currentBranch])) { $environment = $this->api()->getEnvironment($config['mapping'][$currentBranch], $project, $refresh); if ($environment) { $this->debug('Found mapped environment for branch ' . $currentBranch . ': ' . $this->api()->getEnvironmentLabel($environment)); return $environment; } else { unset($config['mapping'][$currentBranch]); $localProject->writeCurrentProjectConfig($config, $projectRoot); } } // Check whether the user has a Git upstream set to a remote environment // ID. $upstream = $git->getUpstream(); if ($upstream && strpos($upstream, '/') !== false) { list(, $potentialEnvironment) = explode('/', $upstream, 2); $environment = $this->api()->getEnvironment($potentialEnvironment, $project, $refresh); if ($environment) { $this->debug('Selected environment ' . $this->api()->getEnvironmentLabel($environment) . ', based on Git upstream: ' . $upstream); return $environment; } } // There is no Git remote set. Fall back to trying the current branch // name. if (!empty($currentBranch) || ($currentBranch = $git->getCurrentBranch())) { $environment = $this->api()->getEnvironment($currentBranch, $project, $refresh); if (!$environment) { // Try a sanitized version of the branch name too. $currentBranchSanitized = Environment::sanitizeId($currentBranch); if ($currentBranchSanitized !== $currentBranch) { $environment = $this->api()->getEnvironment($currentBranchSanitized, $project, $refresh); } } if ($environment) { $this->debug('Selected environment ' . $this->api()->getEnvironmentLabel($environment) . ' based on branch name: ' . $currentBranch); return $environment; } } return false; }
[ "public", "function", "getCurrentEnvironment", "(", "Project", "$", "expectedProject", "=", "null", ",", "$", "refresh", "=", "null", ")", "{", "if", "(", "!", "(", "$", "projectRoot", "=", "$", "this", "->", "getProjectRoot", "(", ")", ")", "||", "!", ...
Get the current environment if the user is in a project directory. @param Project $expectedProject The expected project. @param bool|null $refresh Whether to refresh the environments or projects cache. @return Environment|false The current environment.
[ "Get", "the", "current", "environment", "if", "the", "user", "is", "in", "a", "project", "directory", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L413-L472
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.updateDrushAliases
public function updateDrushAliases(EnvironmentsChangedEvent $event) { $projectRoot = $this->getProjectRoot(); if (!$projectRoot) { return; } // Make sure the local:drush-aliases command is enabled. if (!$this->getApplication()->has('local:drush-aliases')) { return; } // Double-check that the passed project is the current one, and that it // still exists. try { $currentProject = $this->getCurrentProject(); if (!$currentProject || $currentProject->id != $event->getProject()->id) { return; } } catch (ProjectNotFoundException $e) { return; } // Ignore the project if it doesn't contain a Drupal application. if (!Drupal::isDrupal($projectRoot)) { return; } /** @var \Platformsh\Cli\Service\Drush $drush */ $drush = $this->getService('drush'); if ($drush->getVersion() === false) { $this->debug('Not updating Drush aliases: the Drush version cannot be determined.'); return; } $this->debug('Updating Drush aliases'); try { $drush->createAliases($event->getProject(), $projectRoot, $event->getEnvironments()); } catch (\Exception $e) { $this->stdErr->writeln(sprintf( "<comment>Failed to update Drush aliases:</comment>\n%s\n", preg_replace('/^/m', ' ', trim($e->getMessage())) )); } }
php
public function updateDrushAliases(EnvironmentsChangedEvent $event) { $projectRoot = $this->getProjectRoot(); if (!$projectRoot) { return; } // Make sure the local:drush-aliases command is enabled. if (!$this->getApplication()->has('local:drush-aliases')) { return; } // Double-check that the passed project is the current one, and that it // still exists. try { $currentProject = $this->getCurrentProject(); if (!$currentProject || $currentProject->id != $event->getProject()->id) { return; } } catch (ProjectNotFoundException $e) { return; } // Ignore the project if it doesn't contain a Drupal application. if (!Drupal::isDrupal($projectRoot)) { return; } /** @var \Platformsh\Cli\Service\Drush $drush */ $drush = $this->getService('drush'); if ($drush->getVersion() === false) { $this->debug('Not updating Drush aliases: the Drush version cannot be determined.'); return; } $this->debug('Updating Drush aliases'); try { $drush->createAliases($event->getProject(), $projectRoot, $event->getEnvironments()); } catch (\Exception $e) { $this->stdErr->writeln(sprintf( "<comment>Failed to update Drush aliases:</comment>\n%s\n", preg_replace('/^/m', ' ', trim($e->getMessage())) )); } }
[ "public", "function", "updateDrushAliases", "(", "EnvironmentsChangedEvent", "$", "event", ")", "{", "$", "projectRoot", "=", "$", "this", "->", "getProjectRoot", "(", ")", ";", "if", "(", "!", "$", "projectRoot", ")", "{", "return", ";", "}", "// Make sure ...
Update the user's local Drush aliases. This is called via the 'environments_changed' event. @see \Platformsh\Cli\Service\Api::getEnvironments() @param EnvironmentsChangedEvent $event
[ "Update", "the", "user", "s", "local", "Drush", "aliases", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L483-L522
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.addProjectOption
protected function addProjectOption() { $this->addOption('project', 'p', InputOption::VALUE_REQUIRED, 'The project ID or URL'); $this->addOption('host', null, InputOption::VALUE_REQUIRED, "The project's API hostname"); return $this; }
php
protected function addProjectOption() { $this->addOption('project', 'p', InputOption::VALUE_REQUIRED, 'The project ID or URL'); $this->addOption('host', null, InputOption::VALUE_REQUIRED, "The project's API hostname"); return $this; }
[ "protected", "function", "addProjectOption", "(", ")", "{", "$", "this", "->", "addOption", "(", "'project'", ",", "'p'", ",", "InputOption", "::", "VALUE_REQUIRED", ",", "'The project ID or URL'", ")", ";", "$", "this", "->", "addOption", "(", "'host'", ",", ...
Add the --project and --host options. @return CommandBase
[ "Add", "the", "--", "project", "and", "--", "host", "options", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L585-L591
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.addWaitOptions
protected function addWaitOptions() { $this->addOption('no-wait', 'W', InputOption::VALUE_NONE, 'Do not wait for the operation to complete'); if ($this->detectRunningInHook()) { $this->addOption('wait', null, InputOption::VALUE_NONE, 'Wait for the operation to complete'); } else { $this->addOption('wait', null, InputOption::VALUE_NONE, 'Wait for the operation to complete (default)'); } }
php
protected function addWaitOptions() { $this->addOption('no-wait', 'W', InputOption::VALUE_NONE, 'Do not wait for the operation to complete'); if ($this->detectRunningInHook()) { $this->addOption('wait', null, InputOption::VALUE_NONE, 'Wait for the operation to complete'); } else { $this->addOption('wait', null, InputOption::VALUE_NONE, 'Wait for the operation to complete (default)'); } }
[ "protected", "function", "addWaitOptions", "(", ")", "{", "$", "this", "->", "addOption", "(", "'no-wait'", ",", "'W'", ",", "InputOption", "::", "VALUE_NONE", ",", "'Do not wait for the operation to complete'", ")", ";", "if", "(", "$", "this", "->", "detectRun...
Add both the --no-wait and --wait options.
[ "Add", "both", "the", "--", "no", "-", "wait", "and", "--", "wait", "options", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L618-L626
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.shouldWait
protected function shouldWait(InputInterface $input) { if ($input->hasOption('no-wait') && $input->getOption('no-wait')) { return false; } if ($input->hasOption('wait') && $input->getOption('wait')) { return true; } if ($this->detectRunningInHook()) { $serviceName = $this->config()->get('service.name'); $message = "\n<comment>Warning:</comment> $serviceName hook environment detected: assuming <comment>--no-wait</comment> by default." . "\nTo avoid ambiguity, please specify either --no-wait or --wait." . "\n"; $this->stdErr->writeln($message); return false; } return true; }
php
protected function shouldWait(InputInterface $input) { if ($input->hasOption('no-wait') && $input->getOption('no-wait')) { return false; } if ($input->hasOption('wait') && $input->getOption('wait')) { return true; } if ($this->detectRunningInHook()) { $serviceName = $this->config()->get('service.name'); $message = "\n<comment>Warning:</comment> $serviceName hook environment detected: assuming <comment>--no-wait</comment> by default." . "\nTo avoid ambiguity, please specify either --no-wait or --wait." . "\n"; $this->stdErr->writeln($message); return false; } return true; }
[ "protected", "function", "shouldWait", "(", "InputInterface", "$", "input", ")", "{", "if", "(", "$", "input", "->", "hasOption", "(", "'no-wait'", ")", "&&", "$", "input", "->", "getOption", "(", "'no-wait'", ")", ")", "{", "return", "false", ";", "}", ...
Returns whether we should wait for an operation to complete. @param \Symfony\Component\Console\Input\InputInterface $input @return bool
[ "Returns", "whether", "we", "should", "wait", "for", "an", "operation", "to", "complete", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L635-L654
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.detectRunningInHook
protected function detectRunningInHook() { $envPrefix = $this->config()->get('service.env_prefix'); if (getenv($envPrefix . 'PROJECT') && basename(getenv('SHELL')) === 'dash' && !$this->isTerminal(STDIN)) { return true; } return false; }
php
protected function detectRunningInHook() { $envPrefix = $this->config()->get('service.env_prefix'); if (getenv($envPrefix . 'PROJECT') && basename(getenv('SHELL')) === 'dash' && !$this->isTerminal(STDIN)) { return true; } return false; }
[ "protected", "function", "detectRunningInHook", "(", ")", "{", "$", "envPrefix", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'service.env_prefix'", ")", ";", "if", "(", "getenv", "(", "$", "envPrefix", ".", "'PROJECT'", ")", "&&", "bas...
Detects a Platform.sh non-terminal Dash environment; i.e. a hook. @return bool
[ "Detects", "a", "Platform", ".", "sh", "non", "-", "terminal", "Dash", "environment", ";", "i", ".", "e", ".", "a", "hook", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L661-L671
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.selectProject
protected function selectProject($projectId = null, $host = null) { if (!empty($projectId)) { $this->project = $this->api()->getProject($projectId, $host); if (!$this->project) { throw new ConsoleInvalidArgumentException($this->getProjectNotFoundMessage($projectId)); } $this->debug('Selected project: ' . $this->project->id); return $this->project; } $this->project = $this->getCurrentProject(); if (!$this->project && isset($this->input) && $this->input->isInteractive()) { $projects = $this->api()->getProjects(); if (count($projects) > 0 && count($projects) < 25) { $this->debug('No project specified: offering a choice...'); $projectId = $this->offerProjectChoice($projects); return $this->selectProject($projectId); } } if (!$this->project) { throw new RootNotFoundException( "Could not determine the current project." . "\n\nSpecify it using --project, or go to a project directory." ); } return $this->project; }
php
protected function selectProject($projectId = null, $host = null) { if (!empty($projectId)) { $this->project = $this->api()->getProject($projectId, $host); if (!$this->project) { throw new ConsoleInvalidArgumentException($this->getProjectNotFoundMessage($projectId)); } $this->debug('Selected project: ' . $this->project->id); return $this->project; } $this->project = $this->getCurrentProject(); if (!$this->project && isset($this->input) && $this->input->isInteractive()) { $projects = $this->api()->getProjects(); if (count($projects) > 0 && count($projects) < 25) { $this->debug('No project specified: offering a choice...'); $projectId = $this->offerProjectChoice($projects); return $this->selectProject($projectId); } } if (!$this->project) { throw new RootNotFoundException( "Could not determine the current project." . "\n\nSpecify it using --project, or go to a project directory." ); } return $this->project; }
[ "protected", "function", "selectProject", "(", "$", "projectId", "=", "null", ",", "$", "host", "=", "null", ")", "{", "if", "(", "!", "empty", "(", "$", "projectId", ")", ")", "{", "$", "this", "->", "project", "=", "$", "this", "->", "api", "(", ...
Select the project for the user, based on input or the environment. @param string $projectId @param string $host @return Project
[ "Select", "the", "project", "for", "the", "user", "based", "on", "input", "or", "the", "environment", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L681-L712
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.getProjectNotFoundMessage
private function getProjectNotFoundMessage($projectId) { $message = 'Specified project not found: ' . $projectId; if ($projects = $this->api()->getProjects()) { $message .= "\n\nYour projects are:"; $limit = 8; foreach (array_slice($projects, 0, $limit) as $project) { $message .= "\n " . $project->id; if ($project->title) { $message .= ' - ' . $project->title; } } if (count($projects) > $limit) { $message .= "\n ..."; $message .= "\n\n List projects with: " . $this->config()->get('application.executable') . ' project:list'; } } return $message; }
php
private function getProjectNotFoundMessage($projectId) { $message = 'Specified project not found: ' . $projectId; if ($projects = $this->api()->getProjects()) { $message .= "\n\nYour projects are:"; $limit = 8; foreach (array_slice($projects, 0, $limit) as $project) { $message .= "\n " . $project->id; if ($project->title) { $message .= ' - ' . $project->title; } } if (count($projects) > $limit) { $message .= "\n ..."; $message .= "\n\n List projects with: " . $this->config()->get('application.executable') . ' project:list'; } } return $message; }
[ "private", "function", "getProjectNotFoundMessage", "(", "$", "projectId", ")", "{", "$", "message", "=", "'Specified project not found: '", ".", "$", "projectId", ";", "if", "(", "$", "projects", "=", "$", "this", "->", "api", "(", ")", "->", "getProjects", ...
Format an error message about a not-found project. @param string $projectId @return string
[ "Format", "an", "error", "message", "about", "a", "not", "-", "found", "project", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L721-L740
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.selectEnvironment
protected function selectEnvironment($environmentId = null, $required = true, $selectDefaultEnv = false) { $envPrefix = $this->config()->get('service.env_prefix'); if ($environmentId === null && getenv($envPrefix . 'BRANCH')) { $environmentId = getenv($envPrefix . 'BRANCH'); $this->stdErr->writeln(sprintf( 'Environment ID read from environment variable %s: %s', $envPrefix . 'BRANCH', $environmentId ), OutputInterface::VERBOSITY_VERBOSE); } if ($environmentId !== null) { $environment = $this->api()->getEnvironment($environmentId, $this->project, null, true); if (!$environment) { throw new ConsoleInvalidArgumentException('Specified environment not found: ' . $environmentId); } $this->environment = $environment; $this->debug('Selected environment: ' . $this->api()->getEnvironmentLabel($environment)); return; } if ($environment = $this->getCurrentEnvironment($this->project)) { $this->environment = $environment; return; } if ($selectDefaultEnv) { $environments = $this->api()->getEnvironments($this->project); $defaultId = $this->api()->getDefaultEnvironmentId($environments); if ($defaultId && isset($environments[$defaultId])) { $this->environment = $environments[$defaultId]; return; } } if ($required && isset($this->input) && $this->input->isInteractive()) { $this->debug('No environment specified: offering a choice...'); $this->environment = $this->offerEnvironmentChoice($this->api()->getEnvironments($this->project)); return; } if ($required) { if ($this->getProjectRoot()) { $message = 'Could not determine the current environment.' . "\n" . 'Specify it manually using --environment (-e).'; } else { $message = 'No environment specified.' . "\n" . 'Specify one using --environment (-e), or go to a project directory.'; } throw new ConsoleInvalidArgumentException($message); } }
php
protected function selectEnvironment($environmentId = null, $required = true, $selectDefaultEnv = false) { $envPrefix = $this->config()->get('service.env_prefix'); if ($environmentId === null && getenv($envPrefix . 'BRANCH')) { $environmentId = getenv($envPrefix . 'BRANCH'); $this->stdErr->writeln(sprintf( 'Environment ID read from environment variable %s: %s', $envPrefix . 'BRANCH', $environmentId ), OutputInterface::VERBOSITY_VERBOSE); } if ($environmentId !== null) { $environment = $this->api()->getEnvironment($environmentId, $this->project, null, true); if (!$environment) { throw new ConsoleInvalidArgumentException('Specified environment not found: ' . $environmentId); } $this->environment = $environment; $this->debug('Selected environment: ' . $this->api()->getEnvironmentLabel($environment)); return; } if ($environment = $this->getCurrentEnvironment($this->project)) { $this->environment = $environment; return; } if ($selectDefaultEnv) { $environments = $this->api()->getEnvironments($this->project); $defaultId = $this->api()->getDefaultEnvironmentId($environments); if ($defaultId && isset($environments[$defaultId])) { $this->environment = $environments[$defaultId]; return; } } if ($required && isset($this->input) && $this->input->isInteractive()) { $this->debug('No environment specified: offering a choice...'); $this->environment = $this->offerEnvironmentChoice($this->api()->getEnvironments($this->project)); return; } if ($required) { if ($this->getProjectRoot()) { $message = 'Could not determine the current environment.' . "\n" . 'Specify it manually using --environment (-e).'; } else { $message = 'No environment specified.' . "\n" . 'Specify one using --environment (-e), or go to a project directory.'; } throw new ConsoleInvalidArgumentException($message); } }
[ "protected", "function", "selectEnvironment", "(", "$", "environmentId", "=", "null", ",", "$", "required", "=", "true", ",", "$", "selectDefaultEnv", "=", "false", ")", "{", "$", "envPrefix", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(",...
Select the current environment for the user. @throws \RuntimeException If the current environment cannot be found. @param string|null $environmentId The environment ID specified by the user, or null to auto-detect the environment. @param bool $required Whether it's required to have an environment. @param bool $selectDefaultEnv Whether to select a default environment.
[ "Select", "the", "current", "environment", "for", "the", "user", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L755-L808
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.selectApp
protected function selectApp(InputInterface $input) { $appName = $input->getOption('app'); if ($appName) { return $appName; } try { $apps = array_map(function (WebApp $app) { return $app->name; }, $this->api()->getCurrentDeployment($this->getSelectedEnvironment())->webapps); if (!count($apps)) { return null; } } catch (EnvironmentStateException $e) { if (!$e->getEnvironment()->isActive()) { throw new EnvironmentStateException( sprintf('Could not find applications: the environment "%s" is not currently active.', $e->getEnvironment()->id), $e->getEnvironment() ); } throw $e; } $this->debug('Found app(s): ' . implode(',', $apps)); if (count($apps) === 1) { $appName = reset($apps); } elseif ($input->isInteractive()) { /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $choices = array_combine($apps, $apps); $appName = $questionHelper->choose($choices, 'Enter a number to choose an app:'); } $input->setOption('app', $appName); return $appName; }
php
protected function selectApp(InputInterface $input) { $appName = $input->getOption('app'); if ($appName) { return $appName; } try { $apps = array_map(function (WebApp $app) { return $app->name; }, $this->api()->getCurrentDeployment($this->getSelectedEnvironment())->webapps); if (!count($apps)) { return null; } } catch (EnvironmentStateException $e) { if (!$e->getEnvironment()->isActive()) { throw new EnvironmentStateException( sprintf('Could not find applications: the environment "%s" is not currently active.', $e->getEnvironment()->id), $e->getEnvironment() ); } throw $e; } $this->debug('Found app(s): ' . implode(',', $apps)); if (count($apps) === 1) { $appName = reset($apps); } elseif ($input->isInteractive()) { /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $choices = array_combine($apps, $apps); $appName = $questionHelper->choose($choices, 'Enter a number to choose an app:'); } $input->setOption('app', $appName); return $appName; }
[ "protected", "function", "selectApp", "(", "InputInterface", "$", "input", ")", "{", "$", "appName", "=", "$", "input", "->", "getOption", "(", "'app'", ")", ";", "if", "(", "$", "appName", ")", "{", "return", "$", "appName", ";", "}", "try", "{", "$...
Find the name of the app the user wants to use for an SSH command. @param InputInterface $input The user input object. @return string|null The application name, or null if it could not be found.
[ "Find", "the", "name", "of", "the", "app", "the", "user", "wants", "to", "use", "for", "an", "SSH", "command", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L819-L856
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.offerProjectChoice
protected final function offerProjectChoice(array $projects, $text = 'Enter a number to choose a project:') { if (!isset($this->input) || !isset($this->output) || !$this->input->isInteractive()) { throw new \BadMethodCallException('Not interactive: a project choice cannot be offered.'); } // Build and sort a list of project options. $projectList = []; foreach ($projects as $project) { $projectList[$project->id] = $this->api()->getProjectLabel($project, false); } asort($projectList, SORT_NATURAL | SORT_FLAG_CASE); /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $id = $questionHelper->choose($projectList, $text, null, false); return $id; }
php
protected final function offerProjectChoice(array $projects, $text = 'Enter a number to choose a project:') { if (!isset($this->input) || !isset($this->output) || !$this->input->isInteractive()) { throw new \BadMethodCallException('Not interactive: a project choice cannot be offered.'); } // Build and sort a list of project options. $projectList = []; foreach ($projects as $project) { $projectList[$project->id] = $this->api()->getProjectLabel($project, false); } asort($projectList, SORT_NATURAL | SORT_FLAG_CASE); /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $id = $questionHelper->choose($projectList, $text, null, false); return $id; }
[ "protected", "final", "function", "offerProjectChoice", "(", "array", "$", "projects", ",", "$", "text", "=", "'Enter a number to choose a project:'", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "input", ")", "||", "!", "isset", "(", "$", "t...
Offer the user an interactive choice of projects. @param Project[] $projects @param string $text @return string The chosen project ID.
[ "Offer", "the", "user", "an", "interactive", "choice", "of", "projects", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L867-L886
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.offerEnvironmentChoice
protected final function offerEnvironmentChoice(array $environments) { if (!isset($this->input) || !isset($this->output) || !$this->input->isInteractive()) { throw new \BadMethodCallException('Not interactive: an environment choice cannot be offered.'); } /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $default = $this->api()->getDefaultEnvironmentId($environments); // Build and sort a list of options (environment IDs). $ids = array_keys($environments); sort($ids, SORT_NATURAL | SORT_FLAG_CASE); $id = $questionHelper->askInput('Environment ID', $default, array_keys($environments), function ($value) use ($environments) { if (!isset($environments[$value])) { throw new \RuntimeException('Environment not found: ' . $value); } return $value; }); $this->stdErr->writeln(''); return $environments[$id]; }
php
protected final function offerEnvironmentChoice(array $environments) { if (!isset($this->input) || !isset($this->output) || !$this->input->isInteractive()) { throw new \BadMethodCallException('Not interactive: an environment choice cannot be offered.'); } /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $default = $this->api()->getDefaultEnvironmentId($environments); // Build and sort a list of options (environment IDs). $ids = array_keys($environments); sort($ids, SORT_NATURAL | SORT_FLAG_CASE); $id = $questionHelper->askInput('Environment ID', $default, array_keys($environments), function ($value) use ($environments) { if (!isset($environments[$value])) { throw new \RuntimeException('Environment not found: ' . $value); } return $value; }); $this->stdErr->writeln(''); return $environments[$id]; }
[ "protected", "final", "function", "offerEnvironmentChoice", "(", "array", "$", "environments", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "input", ")", "||", "!", "isset", "(", "$", "this", "->", "output", ")", "||", "!", "$", "this", ...
Offers a choice of environments. @param Environment[] $environments @return Environment
[ "Offers", "a", "choice", "of", "environments", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L895-L920
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.runOtherCommand
protected function runOtherCommand($name, array $arguments = [], OutputInterface $output = null) { /** @var \Platformsh\Cli\Application $application */ $application = $this->getApplication(); $command = $application->find($name); // Pass on interactivity arguments to the other command. if (isset($this->input)) { $arguments += [ '--yes' => $this->input->getOption('yes'), '--no' => $this->input->getOption('no'), ]; } $cmdInput = new ArrayInput(['command' => $name] + $arguments); if (!empty($arguments['--yes']) || !empty($arguments['--no'])) { $cmdInput->setInteractive(false); } elseif (isset($this->input)) { $cmdInput->setInteractive($this->input->isInteractive()); } $this->debug('Running command: ' . $name); // Give the other command an entirely new service container, because the // "input" and "output" parameters, and all their dependents, need to // change. $container = self::$container; self::$container = null; $application->setCurrentCommand($command); $result = $command->run($cmdInput, $output ?: $this->output); $application->setCurrentCommand($this); // Restore the old service container. self::$container = $container; return $result; }
php
protected function runOtherCommand($name, array $arguments = [], OutputInterface $output = null) { /** @var \Platformsh\Cli\Application $application */ $application = $this->getApplication(); $command = $application->find($name); // Pass on interactivity arguments to the other command. if (isset($this->input)) { $arguments += [ '--yes' => $this->input->getOption('yes'), '--no' => $this->input->getOption('no'), ]; } $cmdInput = new ArrayInput(['command' => $name] + $arguments); if (!empty($arguments['--yes']) || !empty($arguments['--no'])) { $cmdInput->setInteractive(false); } elseif (isset($this->input)) { $cmdInput->setInteractive($this->input->isInteractive()); } $this->debug('Running command: ' . $name); // Give the other command an entirely new service container, because the // "input" and "output" parameters, and all their dependents, need to // change. $container = self::$container; self::$container = null; $application->setCurrentCommand($command); $result = $command->run($cmdInput, $output ?: $this->output); $application->setCurrentCommand($this); // Restore the old service container. self::$container = $container; return $result; }
[ "protected", "function", "runOtherCommand", "(", "$", "name", ",", "array", "$", "arguments", "=", "[", "]", ",", "OutputInterface", "$", "output", "=", "null", ")", "{", "/** @var \\Platformsh\\Cli\\Application $application */", "$", "application", "=", "$", "thi...
Run another CLI command. @param string $name The name of the other command. @param array $arguments Arguments for the other command. @param OutputInterface $output The output for the other command. Defaults to the current output. @return int
[ "Run", "another", "CLI", "command", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L1076-L1113
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.setHiddenAliases
protected function setHiddenAliases(array $hiddenAliases) { $this->hiddenAliases = $hiddenAliases; $this->setAliases(array_merge($this->getAliases(), $hiddenAliases)); return $this; }
php
protected function setHiddenAliases(array $hiddenAliases) { $this->hiddenAliases = $hiddenAliases; $this->setAliases(array_merge($this->getAliases(), $hiddenAliases)); return $this; }
[ "protected", "function", "setHiddenAliases", "(", "array", "$", "hiddenAliases", ")", "{", "$", "this", "->", "hiddenAliases", "=", "$", "hiddenAliases", ";", "$", "this", "->", "setAliases", "(", "array_merge", "(", "$", "this", "->", "getAliases", "(", ")"...
Add aliases that should be hidden from help. @see parent::setAliases() @param array $hiddenAliases @return CommandBase
[ "Add", "aliases", "that", "should", "be", "hidden", "from", "help", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L1124-L1130
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.getProcessedHelp
public function getProcessedHelp() { $help = $this->getHelp(); if ($help === '') { return $help; } $name = $this->getName(); $placeholders = ['%command.name%', '%command.full_name%']; $replacements = [$name, $this->config()->get('application.executable') . ' ' . $name]; return str_replace($placeholders, $replacements, $help); }
php
public function getProcessedHelp() { $help = $this->getHelp(); if ($help === '') { return $help; } $name = $this->getName(); $placeholders = ['%command.name%', '%command.full_name%']; $replacements = [$name, $this->config()->get('application.executable') . ' ' . $name]; return str_replace($placeholders, $replacements, $help); }
[ "public", "function", "getProcessedHelp", "(", ")", "{", "$", "help", "=", "$", "this", "->", "getHelp", "(", ")", ";", "if", "(", "$", "help", "===", "''", ")", "{", "return", "$", "help", ";", "}", "$", "name", "=", "$", "this", "->", "getName"...
{@inheritdoc} Overrides the default method so that the description is not repeated twice.
[ "{", "@inheritdoc", "}" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L1148-L1160
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.warnAboutDeprecatedOptions
protected function warnAboutDeprecatedOptions(array $options, $template = null) { if (!isset($this->input)) { return; } if ($template === null) { $template = 'The option --%s is deprecated and no longer used. It will be removed in a future version.'; } foreach ($options as $option) { if ($this->input->hasOption($option) && $this->input->getOption($option)) { $this->labeledMessage( 'DEPRECATED', sprintf($template, $option) ); } } }
php
protected function warnAboutDeprecatedOptions(array $options, $template = null) { if (!isset($this->input)) { return; } if ($template === null) { $template = 'The option --%s is deprecated and no longer used. It will be removed in a future version.'; } foreach ($options as $option) { if ($this->input->hasOption($option) && $this->input->getOption($option)) { $this->labeledMessage( 'DEPRECATED', sprintf($template, $option) ); } } }
[ "protected", "function", "warnAboutDeprecatedOptions", "(", "array", "$", "options", ",", "$", "template", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "input", ")", ")", "{", "return", ";", "}", "if", "(", "$", "template", ...
Print a warning about deprecated option(s). @param string[] $options A list of option names (without "--"). @param string|null $template The warning message template. "%s" is replaced by the option name.
[ "Print", "a", "warning", "about", "deprecated", "option", "(", "s", ")", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L1179-L1195
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.labeledMessage
private function labeledMessage($label, $message, $options = 0) { if (isset($this->stdErr)) { $this->stdErr->writeln('<options=reverse>' . strtoupper($label) . '</> ' . $message, $options); } }
php
private function labeledMessage($label, $message, $options = 0) { if (isset($this->stdErr)) { $this->stdErr->writeln('<options=reverse>' . strtoupper($label) . '</> ' . $message, $options); } }
[ "private", "function", "labeledMessage", "(", "$", "label", ",", "$", "message", ",", "$", "options", "=", "0", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "stdErr", ")", ")", "{", "$", "this", "->", "stdErr", "->", "writeln", "(", "'<opt...
Print a message with a label. @param string $label @param string $message @param int $options
[ "Print", "a", "message", "with", "a", "label", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L1204-L1209
platformsh/platformsh-cli
src/Command/CommandBase.php
CommandBase.getSynopsis
public function getSynopsis($short = false) { $key = $short ? 'short' : 'long'; if (!isset($this->synopsis[$key])) { $aliases = $this->getVisibleAliases(); $name = $this->getName(); $shortName = count($aliases) === 1 ? reset($aliases) : $name; $this->synopsis[$key] = trim(sprintf( '%s %s %s', $this->config()->get('application.executable'), $shortName, $this->getDefinition()->getSynopsis($short) )); } return $this->synopsis[$key]; }
php
public function getSynopsis($short = false) { $key = $short ? 'short' : 'long'; if (!isset($this->synopsis[$key])) { $aliases = $this->getVisibleAliases(); $name = $this->getName(); $shortName = count($aliases) === 1 ? reset($aliases) : $name; $this->synopsis[$key] = trim(sprintf( '%s %s %s', $this->config()->get('application.executable'), $shortName, $this->getDefinition()->getSynopsis($short) )); } return $this->synopsis[$key]; }
[ "public", "function", "getSynopsis", "(", "$", "short", "=", "false", ")", "{", "$", "key", "=", "$", "short", "?", "'short'", ":", "'long'", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "synopsis", "[", "$", "key", "]", ")", ")", "{", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/CommandBase.php#L1283-L1300
platformsh/platformsh-cli
src/Command/Domain/DomainListCommand.php
DomainListCommand.configure
protected function configure() { $this ->setName('domain:list') ->setAliases(['domains']) ->setDescription('Get a list of all domains'); Table::configureInput($this->getDefinition()); $this->addProjectOption(); }
php
protected function configure() { $this ->setName('domain:list') ->setAliases(['domains']) ->setDescription('Get a list of all domains'); Table::configureInput($this->getDefinition()); $this->addProjectOption(); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'domain:list'", ")", "->", "setAliases", "(", "[", "'domains'", "]", ")", "->", "setDescription", "(", "'Get a list of all domains'", ")", ";", "Table", "::", "configureIn...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Domain/DomainListCommand.php#L15-L23
platformsh/platformsh-cli
src/Command/Domain/DomainListCommand.php
DomainListCommand.buildDomainRows
protected function buildDomainRows(array $tree) { $rows = []; /** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */ $formatter = $this->getService('property_formatter'); foreach ($tree as $domain) { $rows[] = [ 'name' => $domain->id, 'ssl' => $formatter->format((bool) $domain['ssl']['has_certificate']), 'created_at' => $formatter->format($domain['created_at'], 'created_at'), 'updated_at' => $formatter->format($domain['updated_at'], 'updated_at'), ]; } return $rows; }
php
protected function buildDomainRows(array $tree) { $rows = []; /** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */ $formatter = $this->getService('property_formatter'); foreach ($tree as $domain) { $rows[] = [ 'name' => $domain->id, 'ssl' => $formatter->format((bool) $domain['ssl']['has_certificate']), 'created_at' => $formatter->format($domain['created_at'], 'created_at'), 'updated_at' => $formatter->format($domain['updated_at'], 'updated_at'), ]; } return $rows; }
[ "protected", "function", "buildDomainRows", "(", "array", "$", "tree", ")", "{", "$", "rows", "=", "[", "]", ";", "/** @var \\Platformsh\\Cli\\Service\\PropertyFormatter $formatter */", "$", "formatter", "=", "$", "this", "->", "getService", "(", "'property_formatter'...
Recursively build rows of the domain table. @param Domain[] $tree @return array
[ "Recursively", "build", "rows", "of", "the", "domain", "table", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Domain/DomainListCommand.php#L32-L49
platformsh/platformsh-cli
src/Command/Domain/DomainListCommand.php
DomainListCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $project = $this->getSelectedProject(); $executable = $this->config()->get('application.executable'); try { $domains = $project->getDomains(); } catch (ClientException $e) { $this->handleApiException($e, $project); return 1; } if (empty($domains)) { $this->stdErr->writeln('No domains found for ' . $this->api()->getProjectLabel($project) . '.'); $this->stdErr->writeln(''); $this->stdErr->writeln( 'Add a domain to the project by running <info>' . $executable . ' domain:add [domain-name]</info>' ); return 1; } /** @var \Platformsh\Cli\Service\Table $table */ $table = $this->getService('table'); $header = ['name' => 'Name', 'ssl' => 'SSL enabled', 'created_at' => 'Creation date', 'updated_at' => 'Updated date']; $defaultColumns = ['name', 'ssl', 'created_at']; $rows = $this->buildDomainRows($domains); if ($table->formatIsMachineReadable()) { $table->render($rows, $header, $defaultColumns); return 0; } if (!$table->formatIsMachineReadable()) { $this->stdErr->writeln(sprintf( 'Domains on the project %s:', $this->api()->getProjectLabel($project) )); } $table->render($rows, $header, $defaultColumns); if (!$table->formatIsMachineReadable()) { $this->stdErr->writeln(''); $this->stdErr->writeln([ 'To add a new domain, run: <info>' . $executable . ' domain:add [domain-name]</info>', 'To view a domain, run: <info>' . $executable . ' domain:get [domain-name]</info>', 'To delete a domain, run: <info>' . $executable . ' domain:delete [domain-name]</info>', ]); } return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $project = $this->getSelectedProject(); $executable = $this->config()->get('application.executable'); try { $domains = $project->getDomains(); } catch (ClientException $e) { $this->handleApiException($e, $project); return 1; } if (empty($domains)) { $this->stdErr->writeln('No domains found for ' . $this->api()->getProjectLabel($project) . '.'); $this->stdErr->writeln(''); $this->stdErr->writeln( 'Add a domain to the project by running <info>' . $executable . ' domain:add [domain-name]</info>' ); return 1; } /** @var \Platformsh\Cli\Service\Table $table */ $table = $this->getService('table'); $header = ['name' => 'Name', 'ssl' => 'SSL enabled', 'created_at' => 'Creation date', 'updated_at' => 'Updated date']; $defaultColumns = ['name', 'ssl', 'created_at']; $rows = $this->buildDomainRows($domains); if ($table->formatIsMachineReadable()) { $table->render($rows, $header, $defaultColumns); return 0; } if (!$table->formatIsMachineReadable()) { $this->stdErr->writeln(sprintf( 'Domains on the project %s:', $this->api()->getProjectLabel($project) )); } $table->render($rows, $header, $defaultColumns); if (!$table->formatIsMachineReadable()) { $this->stdErr->writeln(''); $this->stdErr->writeln([ 'To add a new domain, run: <info>' . $executable . ' domain:add [domain-name]</info>', 'To view a domain, run: <info>' . $executable . ' domain:get [domain-name]</info>', 'To delete a domain, run: <info>' . $executable . ' domain:delete [domain-name]</info>', ]); } return 0; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "validateInput", "(", "$", "input", ")", ";", "$", "project", "=", "$", "this", "->", "getSelectedProject", "(", ")...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Domain/DomainListCommand.php#L54-L108
platformsh/platformsh-cli
src/Command/Project/ProjectCreateCommand.php
ProjectCreateCommand.configure
protected function configure() { $this ->setName('project:create') ->setAliases(['create']) ->setDescription('Create a new project'); $this->form = Form::fromArray($this->getFields()); $this->form->configureInputDefinition($this->getDefinition()); $this->addOption('check-timeout', null, InputOption::VALUE_REQUIRED, 'The API timeout while checking the project status', 30) ->addOption('timeout', null, InputOption::VALUE_REQUIRED, 'The total timeout for all API checks (0 to disable the timeout)', 900); $this->setHelp(<<<EOF Use this command to create a new project. An interactive form will be presented with the available options. But if the command is run non-interactively (with --yes), the form will not be displayed, and the --region option will be required. A project subscription will be requested, and then checked periodically (every 3 seconds) until the project has been activated, or until the process times out (after 15 minutes by default). If known, the project ID will be output to STDOUT. All other output will be sent to STDERR. EOF ); }
php
protected function configure() { $this ->setName('project:create') ->setAliases(['create']) ->setDescription('Create a new project'); $this->form = Form::fromArray($this->getFields()); $this->form->configureInputDefinition($this->getDefinition()); $this->addOption('check-timeout', null, InputOption::VALUE_REQUIRED, 'The API timeout while checking the project status', 30) ->addOption('timeout', null, InputOption::VALUE_REQUIRED, 'The total timeout for all API checks (0 to disable the timeout)', 900); $this->setHelp(<<<EOF Use this command to create a new project. An interactive form will be presented with the available options. But if the command is run non-interactively (with --yes), the form will not be displayed, and the --region option will be required. A project subscription will be requested, and then checked periodically (every 3 seconds) until the project has been activated, or until the process times out (after 15 minutes by default). If known, the project ID will be output to STDOUT. All other output will be sent to STDERR. EOF ); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'project:create'", ")", "->", "setAliases", "(", "[", "'create'", "]", ")", "->", "setDescription", "(", "'Create a new project'", ")", ";", "$", "this", "->", "form", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Project/ProjectCreateCommand.php#L23-L51
platformsh/platformsh-cli
src/Command/Project/ProjectCreateCommand.php
ProjectCreateCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $options = $this->form->resolveOptions($input, $output, $questionHelper); $estimate = $this->api() ->getClient() ->getSubscriptionEstimate($options['plan'], $options['storage'], $options['environments'], 1); $costConfirm = sprintf( 'The estimated monthly cost of this project is: <comment>%s</comment>', $estimate['total'] ); if ($this->config()->has('service.pricing_url')) { $costConfirm .= sprintf( "\nPricing information: <comment>%s</comment>", $this->config()->get('service.pricing_url') ); } $costConfirm .= "\n\nAre you sure you want to continue?"; if (!$questionHelper->confirm($costConfirm)) { return 1; } $subscription = $this->api()->getClient() ->createSubscription( $options['region'], $options['plan'], $options['title'], $options['storage'] * 1024, $options['environments'] ); $this->api()->clearProjectsCache(); $this->stdErr->writeln(sprintf( 'Your %s project has been requested (subscription ID: <comment>%s</comment>)', $this->config()->get('service.name'), $subscription->id )); $this->stdErr->writeln(sprintf( "\nThe %s Bot is activating your project\n", $this->config()->get('service.name') )); $bot = new Bot($this->stdErr); $timedOut = false; $start = $lastCheck = time(); $checkInterval = 3; $checkTimeout = $this->getTimeOption($input, 'check-timeout', 1, 3600); $totalTimeout = $this->getTimeOption($input, 'timeout', 0, 3600); while ($subscription->isPending() && !$timedOut) { $bot->render(); // Attempt to check the subscription every $checkInterval seconds. // This also waits $checkInterval seconds before the first check, // which allows the server a little more leeway to act on the // initial request. if (time() - $lastCheck >= $checkInterval) { $lastCheck = time(); try { // The API call will timeout after $checkTimeout seconds. $subscription->refresh(['timeout' => $checkTimeout, 'exceptions' => false]); } catch (ConnectException $e) { if (strpos($e->getMessage(), 'timed out') !== false) { $this->debug($e->getMessage()); } else { throw $e; } } } // Check the total timeout. $timedOut = $totalTimeout ? time() - $start > $totalTimeout : false; } $this->stdErr->writeln(''); if (!$subscription->isActive()) { if ($timedOut) { $this->stdErr->writeln('<error>The project failed to activate on time</error>'); } else { $this->stdErr->writeln('<error>The project failed to activate</error>'); } if (!empty($subscription->project_id)) { $output->writeln($subscription->project_id); } $this->stdErr->writeln(sprintf('View your active projects with: <info>%s project:list</info>', $this->config()->get('application.executable'))); return 1; } $this->stdErr->writeln("The project is now ready!"); $output->writeln($subscription->project_id); $this->stdErr->writeln(''); $this->stdErr->writeln(" Region: <info>{$subscription->project_region}</info>"); $this->stdErr->writeln(" Project ID: <info>{$subscription->project_id}</info>"); $this->stdErr->writeln(" Project title: <info>{$subscription->project_title}</info>"); $this->stdErr->writeln(" URL: <info>{$subscription->project_ui}</info>"); return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); $options = $this->form->resolveOptions($input, $output, $questionHelper); $estimate = $this->api() ->getClient() ->getSubscriptionEstimate($options['plan'], $options['storage'], $options['environments'], 1); $costConfirm = sprintf( 'The estimated monthly cost of this project is: <comment>%s</comment>', $estimate['total'] ); if ($this->config()->has('service.pricing_url')) { $costConfirm .= sprintf( "\nPricing information: <comment>%s</comment>", $this->config()->get('service.pricing_url') ); } $costConfirm .= "\n\nAre you sure you want to continue?"; if (!$questionHelper->confirm($costConfirm)) { return 1; } $subscription = $this->api()->getClient() ->createSubscription( $options['region'], $options['plan'], $options['title'], $options['storage'] * 1024, $options['environments'] ); $this->api()->clearProjectsCache(); $this->stdErr->writeln(sprintf( 'Your %s project has been requested (subscription ID: <comment>%s</comment>)', $this->config()->get('service.name'), $subscription->id )); $this->stdErr->writeln(sprintf( "\nThe %s Bot is activating your project\n", $this->config()->get('service.name') )); $bot = new Bot($this->stdErr); $timedOut = false; $start = $lastCheck = time(); $checkInterval = 3; $checkTimeout = $this->getTimeOption($input, 'check-timeout', 1, 3600); $totalTimeout = $this->getTimeOption($input, 'timeout', 0, 3600); while ($subscription->isPending() && !$timedOut) { $bot->render(); // Attempt to check the subscription every $checkInterval seconds. // This also waits $checkInterval seconds before the first check, // which allows the server a little more leeway to act on the // initial request. if (time() - $lastCheck >= $checkInterval) { $lastCheck = time(); try { // The API call will timeout after $checkTimeout seconds. $subscription->refresh(['timeout' => $checkTimeout, 'exceptions' => false]); } catch (ConnectException $e) { if (strpos($e->getMessage(), 'timed out') !== false) { $this->debug($e->getMessage()); } else { throw $e; } } } // Check the total timeout. $timedOut = $totalTimeout ? time() - $start > $totalTimeout : false; } $this->stdErr->writeln(''); if (!$subscription->isActive()) { if ($timedOut) { $this->stdErr->writeln('<error>The project failed to activate on time</error>'); } else { $this->stdErr->writeln('<error>The project failed to activate</error>'); } if (!empty($subscription->project_id)) { $output->writeln($subscription->project_id); } $this->stdErr->writeln(sprintf('View your active projects with: <info>%s project:list</info>', $this->config()->get('application.executable'))); return 1; } $this->stdErr->writeln("The project is now ready!"); $output->writeln($subscription->project_id); $this->stdErr->writeln(''); $this->stdErr->writeln(" Region: <info>{$subscription->project_region}</info>"); $this->stdErr->writeln(" Project ID: <info>{$subscription->project_id}</info>"); $this->stdErr->writeln(" Project title: <info>{$subscription->project_title}</info>"); $this->stdErr->writeln(" URL: <info>{$subscription->project_ui}</info>"); return 0; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "/** @var \\Platformsh\\Cli\\Service\\QuestionHelper $questionHelper */", "$", "questionHelper", "=", "$", "this", "->", "getService", "(", "'question...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Project/ProjectCreateCommand.php#L56-L158
platformsh/platformsh-cli
src/Command/Project/ProjectCreateCommand.php
ProjectCreateCommand.getAvailablePlans
protected function getAvailablePlans() { $config = $this->config(); if ($config->has('experimental.available_plans')) { return $config->get('experimental.available_plans'); } return $config->get('service.available_plans'); }
php
protected function getAvailablePlans() { $config = $this->config(); if ($config->has('experimental.available_plans')) { return $config->get('experimental.available_plans'); } return $config->get('service.available_plans'); }
[ "protected", "function", "getAvailablePlans", "(", ")", "{", "$", "config", "=", "$", "this", "->", "config", "(", ")", ";", "if", "(", "$", "config", "->", "has", "(", "'experimental.available_plans'", ")", ")", "{", "return", "$", "config", "->", "get"...
Return a list of plans. The default list is in the config `service.available_plans`. This can be overridden by the user config `experimental.available_plans`. @return string[]
[ "Return", "a", "list", "of", "plans", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Project/ProjectCreateCommand.php#L168-L176
platformsh/platformsh-cli
src/Command/Project/ProjectCreateCommand.php
ProjectCreateCommand.getAvailableRegions
protected function getAvailableRegions($runtime = false) { if ($runtime) { $regions = []; foreach ($this->api()->getClient()->getRegions() as $region) { if ($region->available) { $regions[$region->id] = $region->label; } } } else { $regions = (array) $this->config()->get('service.available_regions'); } return $regions; }
php
protected function getAvailableRegions($runtime = false) { if ($runtime) { $regions = []; foreach ($this->api()->getClient()->getRegions() as $region) { if ($region->available) { $regions[$region->id] = $region->label; } } } else { $regions = (array) $this->config()->get('service.available_regions'); } return $regions; }
[ "protected", "function", "getAvailableRegions", "(", "$", "runtime", "=", "false", ")", "{", "if", "(", "$", "runtime", ")", "{", "$", "regions", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "api", "(", ")", "->", "getClient", "(", ")", "...
Return a list of regions. The default list is in the config `service.available_regions`. This is replaced at runtime by an API call. @param bool $runtime @return array
[ "Return", "a", "list", "of", "regions", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Project/ProjectCreateCommand.php#L188-L202
platformsh/platformsh-cli
src/Command/Project/ProjectCreateCommand.php
ProjectCreateCommand.getFields
protected function getFields() { return [ 'title' => new Field('Project title', [ 'optionName' => 'title', 'description' => 'The initial project title', 'questionLine' => '', 'default' => 'Untitled Project', ]), 'region' => new OptionsField('Region', [ 'optionName' => 'region', 'description' => 'The region where the project will be hosted', 'options' => $this->getAvailableRegions(), 'optionsCallback' => function () { return $this->getAvailableRegions(true); }, ]), 'plan' => new OptionsField('Plan', [ 'optionName' => 'plan', 'description' => 'The subscription plan', 'options' => $this->getAvailablePlans(), 'default' => in_array('development', $this->getAvailablePlans()) ? 'development' : null, 'allowOther' => true, ]), 'environments' => new Field('Environments', [ 'optionName' => 'environments', 'description' => 'The number of environments', 'default' => 3, 'validator' => function ($value) { return is_numeric($value) && $value > 0 && $value < 50; }, ]), 'storage' => new Field('Storage', [ 'description' => 'The amount of storage per environment, in GiB', 'default' => 5, 'validator' => function ($value) { return is_numeric($value) && $value > 0 && $value < 1024; }, ]), ]; }
php
protected function getFields() { return [ 'title' => new Field('Project title', [ 'optionName' => 'title', 'description' => 'The initial project title', 'questionLine' => '', 'default' => 'Untitled Project', ]), 'region' => new OptionsField('Region', [ 'optionName' => 'region', 'description' => 'The region where the project will be hosted', 'options' => $this->getAvailableRegions(), 'optionsCallback' => function () { return $this->getAvailableRegions(true); }, ]), 'plan' => new OptionsField('Plan', [ 'optionName' => 'plan', 'description' => 'The subscription plan', 'options' => $this->getAvailablePlans(), 'default' => in_array('development', $this->getAvailablePlans()) ? 'development' : null, 'allowOther' => true, ]), 'environments' => new Field('Environments', [ 'optionName' => 'environments', 'description' => 'The number of environments', 'default' => 3, 'validator' => function ($value) { return is_numeric($value) && $value > 0 && $value < 50; }, ]), 'storage' => new Field('Storage', [ 'description' => 'The amount of storage per environment, in GiB', 'default' => 5, 'validator' => function ($value) { return is_numeric($value) && $value > 0 && $value < 1024; }, ]), ]; }
[ "protected", "function", "getFields", "(", ")", "{", "return", "[", "'title'", "=>", "new", "Field", "(", "'Project title'", ",", "[", "'optionName'", "=>", "'title'", ",", "'description'", "=>", "'The initial project title'", ",", "'questionLine'", "=>", "''", ...
Returns a list of ConsoleForm form fields for this command. @return Field[]
[ "Returns", "a", "list", "of", "ConsoleForm", "form", "fields", "for", "this", "command", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Project/ProjectCreateCommand.php#L209-L249
platformsh/platformsh-cli
src/Command/Project/ProjectCreateCommand.php
ProjectCreateCommand.getTimeOption
private function getTimeOption(InputInterface $input, $optionName, $min = 0, $max = 3600) { $value = $input->getOption($optionName); if ($value <= $min) { $value = $min; } elseif ($value > $max) { $value = $max; } return $value; }
php
private function getTimeOption(InputInterface $input, $optionName, $min = 0, $max = 3600) { $value = $input->getOption($optionName); if ($value <= $min) { $value = $min; } elseif ($value > $max) { $value = $max; } return $value; }
[ "private", "function", "getTimeOption", "(", "InputInterface", "$", "input", ",", "$", "optionName", ",", "$", "min", "=", "0", ",", "$", "max", "=", "3600", ")", "{", "$", "value", "=", "$", "input", "->", "getOption", "(", "$", "optionName", ")", "...
Get a numeric option value while ensuring it's a reasonable number. @param \Symfony\Component\Console\Input\InputInterface $input @param string $optionName @param int $min @param int $max @return float|int
[ "Get", "a", "numeric", "option", "value", "while", "ensuring", "it", "s", "a", "reasonable", "number", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Project/ProjectCreateCommand.php#L261-L271
platformsh/platformsh-cli
src/Command/Repo/CatCommand.php
CatCommand.configure
protected function configure() { $this ->setName('repo:cat') // 🐱 ->setDescription('Read a file in the project repository') ->addArgument('path', InputArgument::REQUIRED, 'The path to the file') ->addOption('commit', 'c', InputOption::VALUE_REQUIRED, 'The commit SHA. ' . GitDataApi::COMMIT_SYNTAX_HELP); $this->addProjectOption(); $this->addEnvironmentOption(); $this->addExample( 'Read the services configuration file', $this->config()->get('service.project_config_dir') . '/services.yaml' ); }
php
protected function configure() { $this ->setName('repo:cat') // 🐱 ->setDescription('Read a file in the project repository') ->addArgument('path', InputArgument::REQUIRED, 'The path to the file') ->addOption('commit', 'c', InputOption::VALUE_REQUIRED, 'The commit SHA. ' . GitDataApi::COMMIT_SYNTAX_HELP); $this->addProjectOption(); $this->addEnvironmentOption(); $this->addExample( 'Read the services configuration file', $this->config()->get('service.project_config_dir') . '/services.yaml' ); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "'repo:cat'", ")", "// 🐱", "->", "setDescription", "(", "'Read a file in the project repository'", ")", "->", "addArgument", "(", "'path'", ",", "InputArgument", "::", "REQUIR...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Repo/CatCommand.php#L18-L31
platformsh/platformsh-cli
src/Command/Repo/CatCommand.php
CatCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input, false, true); $environment = $this->getSelectedEnvironment(); $path = $input->getArgument('path'); try { /** @var \Platformsh\Cli\Service\GitDataApi $gitData */ $gitData = $this->getService('git_data_api'); $content = $gitData->readFile($path, $environment, $input->getOption('commit')); } catch (GitObjectTypeException $e) { $this->stdErr->writeln(sprintf( '%s: <error>%s</error>', $e->getMessage(), $e->getPath() )); $this->stdErr->writeln(sprintf('To list directory contents, run: <comment>%s repo:ls [path]</comment>', $this->config()->get('application.executable'))); return 3; } if ($content === false) { $this->stdErr->writeln(sprintf('File not found: <error>%s</error>', $path)); return 2; } $output->write($content, false, OutputInterface::OUTPUT_RAW); return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input, false, true); $environment = $this->getSelectedEnvironment(); $path = $input->getArgument('path'); try { /** @var \Platformsh\Cli\Service\GitDataApi $gitData */ $gitData = $this->getService('git_data_api'); $content = $gitData->readFile($path, $environment, $input->getOption('commit')); } catch (GitObjectTypeException $e) { $this->stdErr->writeln(sprintf( '%s: <error>%s</error>', $e->getMessage(), $e->getPath() )); $this->stdErr->writeln(sprintf('To list directory contents, run: <comment>%s repo:ls [path]</comment>', $this->config()->get('application.executable'))); return 3; } if ($content === false) { $this->stdErr->writeln(sprintf('File not found: <error>%s</error>', $path)); return 2; } $output->write($content, false, OutputInterface::OUTPUT_RAW); 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/CatCommand.php#L36-L65
platformsh/platformsh-cli
src/Service/ActivityMonitor.php
ActivityMonitor.waitAndLog
public function waitAndLog(Activity $activity, $success = null, $failure = null) { $stdErr = $this->getStdErr(); $stdErr->writeln(sprintf( 'Waiting for the activity <info>%s</info> (%s):', $activity->id, self::getFormattedDescription($activity) )); // The progress bar will show elapsed time and the activity's state. $bar = $this->newProgressBar($stdErr); $bar->setPlaceholderFormatterDefinition('state', function () use ($activity) { return $this->formatState($activity->state); }); $bar->setFormat(' [%bar%] %elapsed:6s% (%state%)'); $bar->start(); // Wait for the activity to complete. $activity->wait( // Advance the progress bar whenever the activity is polled. function () use ($bar) { $bar->advance(); }, // Display new log output when it is available. function ($log) use ($stdErr, $bar) { // Clear the progress bar and ensure the current line is flushed. $bar->clear(); $stdErr->write($stdErr->isDecorated() ? "\n\033[1A" : "\n"); // Display the new log output. $stdErr->write($this->indent($log)); // Display the progress bar again. $bar->advance(); } ); $bar->finish(); $stdErr->writeln(''); // Display the success or failure messages. switch ($activity['result']) { case Activity::RESULT_SUCCESS: $stdErr->writeln($success ?: "Activity <info>{$activity->id}</info> succeeded"); return true; case Activity::RESULT_FAILURE: $stdErr->writeln($failure ?: "Activity <error>{$activity->id}</error> failed"); return false; } return false; }
php
public function waitAndLog(Activity $activity, $success = null, $failure = null) { $stdErr = $this->getStdErr(); $stdErr->writeln(sprintf( 'Waiting for the activity <info>%s</info> (%s):', $activity->id, self::getFormattedDescription($activity) )); // The progress bar will show elapsed time and the activity's state. $bar = $this->newProgressBar($stdErr); $bar->setPlaceholderFormatterDefinition('state', function () use ($activity) { return $this->formatState($activity->state); }); $bar->setFormat(' [%bar%] %elapsed:6s% (%state%)'); $bar->start(); // Wait for the activity to complete. $activity->wait( // Advance the progress bar whenever the activity is polled. function () use ($bar) { $bar->advance(); }, // Display new log output when it is available. function ($log) use ($stdErr, $bar) { // Clear the progress bar and ensure the current line is flushed. $bar->clear(); $stdErr->write($stdErr->isDecorated() ? "\n\033[1A" : "\n"); // Display the new log output. $stdErr->write($this->indent($log)); // Display the progress bar again. $bar->advance(); } ); $bar->finish(); $stdErr->writeln(''); // Display the success or failure messages. switch ($activity['result']) { case Activity::RESULT_SUCCESS: $stdErr->writeln($success ?: "Activity <info>{$activity->id}</info> succeeded"); return true; case Activity::RESULT_FAILURE: $stdErr->writeln($failure ?: "Activity <error>{$activity->id}</error> failed"); return false; } return false; }
[ "public", "function", "waitAndLog", "(", "Activity", "$", "activity", ",", "$", "success", "=", "null", ",", "$", "failure", "=", "null", ")", "{", "$", "stdErr", "=", "$", "this", "->", "getStdErr", "(", ")", ";", "$", "stdErr", "->", "writeln", "("...
Wait for a single activity to complete, and display the log continuously. @param Activity $activity The activity. @param string|null $success A message to show on success. @param string|null $failure A message to show on failure. @return bool True if the activity succeeded, false otherwise.
[ "Wait", "for", "a", "single", "activity", "to", "complete", "and", "display", "the", "log", "continuously", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/ActivityMonitor.php#L66-L118
platformsh/platformsh-cli
src/Service/ActivityMonitor.php
ActivityMonitor.waitMultiple
public function waitMultiple(array $activities, Project $project) { $stdErr = $this->getStdErr(); $count = count($activities); if ($count == 0) { return true; } elseif ($count === 1) { return $this->waitAndLog(reset($activities)); } $stdErr->writeln(sprintf('Waiting for %d activities...', $count)); // The progress bar will show elapsed time and all of the activities' // states. $bar = $this->newProgressBar($stdErr); $states = []; foreach ($activities as $activity) { $state = $activity->state; $states[$state] = isset($states[$state]) ? $states[$state] + 1 : 1; } $bar->setPlaceholderFormatterDefinition('states', function () use (&$states) { $format = ''; foreach ($states as $state => $count) { $format .= $count . ' ' . $this->formatState($state) . ', '; } return rtrim($format, ', '); }); $bar->setFormat(' [%bar%] %elapsed:6s% (%states%)'); $bar->start(); // Get the most recent created date of each of the activities, as a Unix // timestamp, so that they can be more efficiently refreshed. $mostRecentTimestamp = 0; foreach ($activities as $activity) { $created = strtotime($activity->created_at); $mostRecentTimestamp = $created > $mostRecentTimestamp ? $created : $mostRecentTimestamp; } // Wait for the activities to complete, polling (refreshing) all of them // with a 1 second delay. $complete = 0; while ($complete < $count) { sleep(1); $states = []; $complete = 0; // Get a list of activities on the project. Any of our activities // which are not contained in this list must be refreshed // individually. $projectActivities = $project->getActivities(0, null, $mostRecentTimestamp ?: null); foreach ($activities as $activity) { $refreshed = false; foreach ($projectActivities as $projectActivity) { if ($projectActivity->id === $activity->id) { $activity = $projectActivity; $refreshed = true; break; } } if (!$refreshed && !$activity->isComplete()) { $activity->refresh(); } if ($activity->isComplete()) { $complete++; } $state = $activity->state; $states[$state] = isset($states[$state]) ? $states[$state] + 1 : 1; } $bar->advance(); } $bar->finish(); $stdErr->writeln(''); // Display success or failure messages for each activity. $success = true; foreach ($activities as $activity) { $description = self::getFormattedDescription($activity); switch ($activity['result']) { case Activity::RESULT_SUCCESS: $stdErr->writeln(sprintf('Activity <info>%s</info> succeeded: %s', $activity->id, $description)); break; case Activity::RESULT_FAILURE: $success = false; $stdErr->writeln(sprintf('Activity <error>%s</error> failed', $activity->id)); // If the activity failed, show the complete log. $stdErr->writeln(' Description: ' . $description); $stdErr->writeln(' Log:'); $stdErr->writeln($this->indent($activity->log)); break; } } return $success; }
php
public function waitMultiple(array $activities, Project $project) { $stdErr = $this->getStdErr(); $count = count($activities); if ($count == 0) { return true; } elseif ($count === 1) { return $this->waitAndLog(reset($activities)); } $stdErr->writeln(sprintf('Waiting for %d activities...', $count)); // The progress bar will show elapsed time and all of the activities' // states. $bar = $this->newProgressBar($stdErr); $states = []; foreach ($activities as $activity) { $state = $activity->state; $states[$state] = isset($states[$state]) ? $states[$state] + 1 : 1; } $bar->setPlaceholderFormatterDefinition('states', function () use (&$states) { $format = ''; foreach ($states as $state => $count) { $format .= $count . ' ' . $this->formatState($state) . ', '; } return rtrim($format, ', '); }); $bar->setFormat(' [%bar%] %elapsed:6s% (%states%)'); $bar->start(); // Get the most recent created date of each of the activities, as a Unix // timestamp, so that they can be more efficiently refreshed. $mostRecentTimestamp = 0; foreach ($activities as $activity) { $created = strtotime($activity->created_at); $mostRecentTimestamp = $created > $mostRecentTimestamp ? $created : $mostRecentTimestamp; } // Wait for the activities to complete, polling (refreshing) all of them // with a 1 second delay. $complete = 0; while ($complete < $count) { sleep(1); $states = []; $complete = 0; // Get a list of activities on the project. Any of our activities // which are not contained in this list must be refreshed // individually. $projectActivities = $project->getActivities(0, null, $mostRecentTimestamp ?: null); foreach ($activities as $activity) { $refreshed = false; foreach ($projectActivities as $projectActivity) { if ($projectActivity->id === $activity->id) { $activity = $projectActivity; $refreshed = true; break; } } if (!$refreshed && !$activity->isComplete()) { $activity->refresh(); } if ($activity->isComplete()) { $complete++; } $state = $activity->state; $states[$state] = isset($states[$state]) ? $states[$state] + 1 : 1; } $bar->advance(); } $bar->finish(); $stdErr->writeln(''); // Display success or failure messages for each activity. $success = true; foreach ($activities as $activity) { $description = self::getFormattedDescription($activity); switch ($activity['result']) { case Activity::RESULT_SUCCESS: $stdErr->writeln(sprintf('Activity <info>%s</info> succeeded: %s', $activity->id, $description)); break; case Activity::RESULT_FAILURE: $success = false; $stdErr->writeln(sprintf('Activity <error>%s</error> failed', $activity->id)); // If the activity failed, show the complete log. $stdErr->writeln(' Description: ' . $description); $stdErr->writeln(' Log:'); $stdErr->writeln($this->indent($activity->log)); break; } } return $success; }
[ "public", "function", "waitMultiple", "(", "array", "$", "activities", ",", "Project", "$", "project", ")", "{", "$", "stdErr", "=", "$", "this", "->", "getStdErr", "(", ")", ";", "$", "count", "=", "count", "(", "$", "activities", ")", ";", "if", "(...
Wait for multiple activities to complete. A progress bar tracks the state of each activity. The activity log is only displayed at the end, if an activity failed. @param Activity[] $activities @param Project $project @return bool True if all activities succeed, false otherwise.
[ "Wait", "for", "multiple", "activities", "to", "complete", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/ActivityMonitor.php#L132-L228
platformsh/platformsh-cli
src/Service/ActivityMonitor.php
ActivityMonitor.formatState
public static function formatState($state) { return isset(self::$stateNames[$state]) ? self::$stateNames[$state] : $state; }
php
public static function formatState($state) { return isset(self::$stateNames[$state]) ? self::$stateNames[$state] : $state; }
[ "public", "static", "function", "formatState", "(", "$", "state", ")", "{", "return", "isset", "(", "self", "::", "$", "stateNames", "[", "$", "state", "]", ")", "?", "self", "::", "$", "stateNames", "[", "$", "state", "]", ":", "$", "state", ";", ...
Format a state name. @param string $state @return string
[ "Format", "a", "state", "name", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/ActivityMonitor.php#L237-L240
platformsh/platformsh-cli
src/Service/ActivityMonitor.php
ActivityMonitor.formatResult
public static function formatResult($result, $decorate = true) { $name = isset(self::$stateNames[$result]) ? self::$stateNames[$result] : $result; return $decorate && $result === Activity::RESULT_FAILURE ? '<error>' . $name . '</error>' : $name; }
php
public static function formatResult($result, $decorate = true) { $name = isset(self::$stateNames[$result]) ? self::$stateNames[$result] : $result; return $decorate && $result === Activity::RESULT_FAILURE ? '<error>' . $name . '</error>' : $name; }
[ "public", "static", "function", "formatResult", "(", "$", "result", ",", "$", "decorate", "=", "true", ")", "{", "$", "name", "=", "isset", "(", "self", "::", "$", "stateNames", "[", "$", "result", "]", ")", "?", "self", "::", "$", "stateNames", "[",...
Format a result. @param string $result @param bool $decorate @return string
[ "Format", "a", "result", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/ActivityMonitor.php#L250-L257
platformsh/platformsh-cli
src/Service/ActivityMonitor.php
ActivityMonitor.newProgressBar
protected function newProgressBar(OutputInterface $output) { // If the console output is not decorated (i.e. it does not support // ANSI), use NullOutput to suppress the progress bar entirely. $progressOutput = $output->isDecorated() ? $output : new NullOutput(); return new ProgressBar($progressOutput); }
php
protected function newProgressBar(OutputInterface $output) { // If the console output is not decorated (i.e. it does not support // ANSI), use NullOutput to suppress the progress bar entirely. $progressOutput = $output->isDecorated() ? $output : new NullOutput(); return new ProgressBar($progressOutput); }
[ "protected", "function", "newProgressBar", "(", "OutputInterface", "$", "output", ")", "{", "// If the console output is not decorated (i.e. it does not support", "// ANSI), use NullOutput to suppress the progress bar entirely.", "$", "progressOutput", "=", "$", "output", "->", "is...
Initialize a new progress bar. @param OutputInterface $output @return ProgressBar
[ "Initialize", "a", "new", "progress", "bar", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/ActivityMonitor.php#L266-L273
platformsh/platformsh-cli
src/Service/ActivityMonitor.php
ActivityMonitor.getFormattedDescription
public static function getFormattedDescription(Activity $activity, $withDecoration = true) { if (!$withDecoration) { return $activity->getDescription(false); } $value = $activity->getDescription(true); // Replace description HTML elements with Symfony Console decoration // tags. $value = preg_replace('@<[^/][^>]+>@', '<options=underscore>', $value); $value = preg_replace('@</[^>]+>@', '</>', $value); // Replace literal tags like "&lt;info&;gt;" with escaped tags like // "\<info>". $value = preg_replace('@&lt;(/?[a-z][a-z0-9,_=;-]*+)&gt;@i', '\\\<$1>', $value); // Decode other HTML entities. $value = html_entity_decode($value, ENT_QUOTES, 'utf-8'); return $value; }
php
public static function getFormattedDescription(Activity $activity, $withDecoration = true) { if (!$withDecoration) { return $activity->getDescription(false); } $value = $activity->getDescription(true); // Replace description HTML elements with Symfony Console decoration // tags. $value = preg_replace('@<[^/][^>]+>@', '<options=underscore>', $value); $value = preg_replace('@</[^>]+>@', '</>', $value); // Replace literal tags like "&lt;info&;gt;" with escaped tags like // "\<info>". $value = preg_replace('@&lt;(/?[a-z][a-z0-9,_=;-]*+)&gt;@i', '\\\<$1>', $value); // Decode other HTML entities. $value = html_entity_decode($value, ENT_QUOTES, 'utf-8'); return $value; }
[ "public", "static", "function", "getFormattedDescription", "(", "Activity", "$", "activity", ",", "$", "withDecoration", "=", "true", ")", "{", "if", "(", "!", "$", "withDecoration", ")", "{", "return", "$", "activity", "->", "getDescription", "(", "false", ...
Get the formatted description of an activity. @param \Platformsh\Client\Model\Activity $activity @param bool $withDecoration @return string
[ "Get", "the", "formatted", "description", "of", "an", "activity", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/ActivityMonitor.php#L283-L303
platformsh/platformsh-cli
src/Local/BuildFlavor/BuildFlavorBase.php
BuildFlavorBase.processSpecialDestinations
protected function processSpecialDestinations() { foreach ($this->specialDestinations as $sourcePattern => $relDestination) { $matched = glob($this->appRoot . '/' . $sourcePattern, GLOB_NOSORT); if (!$matched) { continue; } if ($relDestination === '{webroot}' && $this->buildInPlace) { continue; } // On Platform.sh these replacements would be a bit different. $absDestination = str_replace( ['{webroot}', '{approot}'], [$this->getWebRoot(), $this->buildDir], $relDestination ); foreach ($matched as $source) { // Ignore the source if it's in ignoredFiles. $relSource = str_replace($this->appRoot . '/', '', $source); if (in_array($relSource, $this->ignoredFiles)) { continue; } $destination = $absDestination; // Do not overwrite directories with files. if (!is_dir($source) && is_dir($destination)) { $destination = $destination . '/' . basename($source); } // Ignore if source and destination are the same. if ($destination === $source) { continue; } if ($this->copy) { $this->stdErr->writeln("Copying $relSource to $relDestination"); } else { $this->stdErr->writeln("Symlinking $relSource to $relDestination"); } // Delete existing files, emitting a warning. if (file_exists($destination)) { $this->stdErr->writeln( sprintf( "Overriding existing path '%s' in destination", str_replace($this->buildDir . '/', '', $destination) ) ); $this->fsHelper->remove($destination); } if ($this->copy) { $this->fsHelper->copy($source, $destination); } else { $this->fsHelper->symlink($source, $destination); } } } }
php
protected function processSpecialDestinations() { foreach ($this->specialDestinations as $sourcePattern => $relDestination) { $matched = glob($this->appRoot . '/' . $sourcePattern, GLOB_NOSORT); if (!$matched) { continue; } if ($relDestination === '{webroot}' && $this->buildInPlace) { continue; } // On Platform.sh these replacements would be a bit different. $absDestination = str_replace( ['{webroot}', '{approot}'], [$this->getWebRoot(), $this->buildDir], $relDestination ); foreach ($matched as $source) { // Ignore the source if it's in ignoredFiles. $relSource = str_replace($this->appRoot . '/', '', $source); if (in_array($relSource, $this->ignoredFiles)) { continue; } $destination = $absDestination; // Do not overwrite directories with files. if (!is_dir($source) && is_dir($destination)) { $destination = $destination . '/' . basename($source); } // Ignore if source and destination are the same. if ($destination === $source) { continue; } if ($this->copy) { $this->stdErr->writeln("Copying $relSource to $relDestination"); } else { $this->stdErr->writeln("Symlinking $relSource to $relDestination"); } // Delete existing files, emitting a warning. if (file_exists($destination)) { $this->stdErr->writeln( sprintf( "Overriding existing path '%s' in destination", str_replace($this->buildDir . '/', '', $destination) ) ); $this->fsHelper->remove($destination); } if ($this->copy) { $this->fsHelper->copy($source, $destination); } else { $this->fsHelper->symlink($source, $destination); } } } }
[ "protected", "function", "processSpecialDestinations", "(", ")", "{", "foreach", "(", "$", "this", "->", "specialDestinations", "as", "$", "sourcePattern", "=>", "$", "relDestination", ")", "{", "$", "matched", "=", "glob", "(", "$", "this", "->", "appRoot", ...
Process the defined special destinations.
[ "Process", "the", "defined", "special", "destinations", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/BuildFlavorBase.php#L156-L211
platformsh/platformsh-cli
src/Local/BuildFlavor/BuildFlavorBase.php
BuildFlavorBase.getSharedDir
protected function getSharedDir() { $shared = $this->app->getSourceDir() . '/' . $this->config->get('local.shared_dir'); if (!$this->app->isSingle()) { $shared .= '/' . preg_replace('/[^a-z0-9\-_]+/i', '-', $this->app->getName()); } $this->fsHelper->mkdir($shared); return $shared; }
php
protected function getSharedDir() { $shared = $this->app->getSourceDir() . '/' . $this->config->get('local.shared_dir'); if (!$this->app->isSingle()) { $shared .= '/' . preg_replace('/[^a-z0-9\-_]+/i', '-', $this->app->getName()); } $this->fsHelper->mkdir($shared); return $shared; }
[ "protected", "function", "getSharedDir", "(", ")", "{", "$", "shared", "=", "$", "this", "->", "app", "->", "getSourceDir", "(", ")", ".", "'/'", ".", "$", "this", "->", "config", "->", "get", "(", "'local.shared_dir'", ")", ";", "if", "(", "!", "$",...
Get the directory containing files shared between builds. This will be 'shared' for a single-application project, or 'shared/<appName>' when there are multiple applications. @return string|false
[ "Get", "the", "directory", "containing", "files", "shared", "between", "builds", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/BuildFlavorBase.php#L221-L230
platformsh/platformsh-cli
src/Local/BuildFlavor/BuildFlavorBase.php
BuildFlavorBase.copyToBuildDir
protected function copyToBuildDir() { $this->buildInPlace = true; $buildDir = $this->buildDir; if ($this->app->shouldMoveToRoot()) { $buildDir .= '/' . $this->documentRoot; } if (!empty($this->settings['clone'])) { $this->cloneToBuildDir($buildDir); } elseif ($this->copy) { $this->fsHelper->copyAll($this->appRoot, $buildDir, $this->ignoredFiles, true); } else { $this->fsHelper->symlink($this->appRoot, $buildDir); } return $buildDir; }
php
protected function copyToBuildDir() { $this->buildInPlace = true; $buildDir = $this->buildDir; if ($this->app->shouldMoveToRoot()) { $buildDir .= '/' . $this->documentRoot; } if (!empty($this->settings['clone'])) { $this->cloneToBuildDir($buildDir); } elseif ($this->copy) { $this->fsHelper->copyAll($this->appRoot, $buildDir, $this->ignoredFiles, true); } else { $this->fsHelper->symlink($this->appRoot, $buildDir); } return $buildDir; }
[ "protected", "function", "copyToBuildDir", "(", ")", "{", "$", "this", "->", "buildInPlace", "=", "true", ";", "$", "buildDir", "=", "$", "this", "->", "buildDir", ";", "if", "(", "$", "this", "->", "app", "->", "shouldMoveToRoot", "(", ")", ")", "{", ...
Copy, or symlink, files from the app root to the build directory. @return string The absolute path to the build directory where files have been copied.
[ "Copy", "or", "symlink", "files", "from", "the", "app", "root", "to", "the", "build", "directory", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/BuildFlavorBase.php#L254-L270
platformsh/platformsh-cli
src/Local/BuildFlavor/BuildFlavorBase.php
BuildFlavorBase.cloneToBuildDir
private function cloneToBuildDir($buildDir) { $gitRoot = $this->gitHelper->getRoot($this->appRoot, true); $ref = $this->gitHelper->execute(['rev-parse', 'HEAD'], $gitRoot, true); $cloneArgs = ['--recursive', '--shared']; $tmpRepo = $buildDir . '-repo'; if (file_exists($tmpRepo)) { $this->fsHelper->remove($tmpRepo, true); } $this->gitHelper->cloneRepo($gitRoot, $tmpRepo, $cloneArgs, true); $this->gitHelper->checkOut($ref, $tmpRepo, true, true); $this->fsHelper->remove($tmpRepo . '/.git'); $appDir = $tmpRepo . '/' . substr($this->appRoot, strlen($gitRoot)); if (!rename($appDir, $buildDir)) { throw new \RuntimeException(sprintf('Failed to move app from %s to %s', $appDir, $buildDir)); } $this->fsHelper->remove($tmpRepo); }
php
private function cloneToBuildDir($buildDir) { $gitRoot = $this->gitHelper->getRoot($this->appRoot, true); $ref = $this->gitHelper->execute(['rev-parse', 'HEAD'], $gitRoot, true); $cloneArgs = ['--recursive', '--shared']; $tmpRepo = $buildDir . '-repo'; if (file_exists($tmpRepo)) { $this->fsHelper->remove($tmpRepo, true); } $this->gitHelper->cloneRepo($gitRoot, $tmpRepo, $cloneArgs, true); $this->gitHelper->checkOut($ref, $tmpRepo, true, true); $this->fsHelper->remove($tmpRepo . '/.git'); $appDir = $tmpRepo . '/' . substr($this->appRoot, strlen($gitRoot)); if (!rename($appDir, $buildDir)) { throw new \RuntimeException(sprintf('Failed to move app from %s to %s', $appDir, $buildDir)); } $this->fsHelper->remove($tmpRepo); }
[ "private", "function", "cloneToBuildDir", "(", "$", "buildDir", ")", "{", "$", "gitRoot", "=", "$", "this", "->", "gitHelper", "->", "getRoot", "(", "$", "this", "->", "appRoot", ",", "true", ")", ";", "$", "ref", "=", "$", "this", "->", "gitHelper", ...
Clone the app to the build directory via Git. @param string $buildDir
[ "Clone", "the", "app", "to", "the", "build", "directory", "via", "Git", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/BuildFlavorBase.php#L277-L296
platformsh/platformsh-cli
src/Local/BuildFlavor/BuildFlavorBase.php
BuildFlavorBase.processSharedFileMounts
protected function processSharedFileMounts() { $sharedDir = $this->getSharedDir(); if ($sharedDir === false) { return; } // If the build directory is a symlink, then skip, so that we don't risk // modifying the user's repository. if (is_link($this->buildDir)) { return; } $sharedFileMounts = $this->app->getSharedFileMounts(); if (empty($sharedFileMounts)) { return; } $sharedDirRelative = $this->config->get('local.shared_dir'); $this->stdErr->writeln('Creating symbolic links to mimic shared file mounts'); foreach ($sharedFileMounts as $appPath => $sharedPath) { $target = $sharedDir . '/' . $sharedPath; $targetRelative = $sharedDirRelative . '/' . $sharedPath; $link = $this->buildDir . '/' . $appPath; if (file_exists($link) && !is_link($link)) { $this->stdErr->writeln(' Removing existing file <comment>' . $appPath . '</comment>'); $this->fsHelper->remove($link); } if (!file_exists($target)) { $this->fsHelper->mkdir($target, 0775); } $this->stdErr->writeln( ' Symlinking <info>' . $appPath . '</info> to <info>' . $targetRelative . '</info>' ); $this->fsHelper->symlink($target, $link); } }
php
protected function processSharedFileMounts() { $sharedDir = $this->getSharedDir(); if ($sharedDir === false) { return; } // If the build directory is a symlink, then skip, so that we don't risk // modifying the user's repository. if (is_link($this->buildDir)) { return; } $sharedFileMounts = $this->app->getSharedFileMounts(); if (empty($sharedFileMounts)) { return; } $sharedDirRelative = $this->config->get('local.shared_dir'); $this->stdErr->writeln('Creating symbolic links to mimic shared file mounts'); foreach ($sharedFileMounts as $appPath => $sharedPath) { $target = $sharedDir . '/' . $sharedPath; $targetRelative = $sharedDirRelative . '/' . $sharedPath; $link = $this->buildDir . '/' . $appPath; if (file_exists($link) && !is_link($link)) { $this->stdErr->writeln(' Removing existing file <comment>' . $appPath . '</comment>'); $this->fsHelper->remove($link); } if (!file_exists($target)) { $this->fsHelper->mkdir($target, 0775); } $this->stdErr->writeln( ' Symlinking <info>' . $appPath . '</info> to <info>' . $targetRelative . '</info>' ); $this->fsHelper->symlink($target, $link); } }
[ "protected", "function", "processSharedFileMounts", "(", ")", "{", "$", "sharedDir", "=", "$", "this", "->", "getSharedDir", "(", ")", ";", "if", "(", "$", "sharedDir", "===", "false", ")", "{", "return", ";", "}", "// If the build directory is a symlink, then s...
Process shared file mounts in the application. For each "mount", this creates a corresponding directory in the project's shared files directory, and symlinks it into the appropriate path in the build.
[ "Process", "shared", "file", "mounts", "in", "the", "application", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/BuildFlavorBase.php#L313-L349
platformsh/platformsh-cli
src/Local/BuildFlavor/BuildFlavorBase.php
BuildFlavorBase.installDrupalSettingsLocal
protected function installDrupalSettingsLocal() { $sitesDefault = $this->getWebRoot() . '/sites/default'; $shared = $this->getSharedDir(); $settingsLocal = $sitesDefault . '/settings.local.php'; if ($shared !== false && is_dir($sitesDefault) && !file_exists($settingsLocal)) { $sharedSettingsLocal = $shared . '/settings.local.php'; $relative = $this->config->get('local.shared_dir') . '/settings.local.php'; if (!file_exists($sharedSettingsLocal)) { $this->stdErr->writeln("Creating file: <info>$relative</info>"); $this->fsHelper->copy(CLI_ROOT . '/resources/drupal/settings.local.php.dist', $sharedSettingsLocal); $this->stdErr->writeln( 'Edit this file to add your database credentials and other Drupal configuration.' ); } else { $this->stdErr->writeln("Symlinking <info>$relative</info> into sites/default"); } $this->fsHelper->symlink($sharedSettingsLocal, $settingsLocal); } }
php
protected function installDrupalSettingsLocal() { $sitesDefault = $this->getWebRoot() . '/sites/default'; $shared = $this->getSharedDir(); $settingsLocal = $sitesDefault . '/settings.local.php'; if ($shared !== false && is_dir($sitesDefault) && !file_exists($settingsLocal)) { $sharedSettingsLocal = $shared . '/settings.local.php'; $relative = $this->config->get('local.shared_dir') . '/settings.local.php'; if (!file_exists($sharedSettingsLocal)) { $this->stdErr->writeln("Creating file: <info>$relative</info>"); $this->fsHelper->copy(CLI_ROOT . '/resources/drupal/settings.local.php.dist', $sharedSettingsLocal); $this->stdErr->writeln( 'Edit this file to add your database credentials and other Drupal configuration.' ); } else { $this->stdErr->writeln("Symlinking <info>$relative</info> into sites/default"); } $this->fsHelper->symlink($sharedSettingsLocal, $settingsLocal); } }
[ "protected", "function", "installDrupalSettingsLocal", "(", ")", "{", "$", "sitesDefault", "=", "$", "this", "->", "getWebRoot", "(", ")", ".", "'/sites/default'", ";", "$", "shared", "=", "$", "this", "->", "getSharedDir", "(", ")", ";", "$", "settingsLocal...
Create a settings.local.php for a Drupal site. This helps with database setup, etc.
[ "Create", "a", "settings", ".", "local", ".", "php", "for", "a", "Drupal", "site", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/BuildFlavorBase.php#L356-L376
platformsh/platformsh-cli
src/Local/BuildFlavor/BuildFlavorBase.php
BuildFlavorBase.copyGitIgnore
protected function copyGitIgnore($source) { $source = CLI_ROOT . '/resources/' . $source; $gitRoot = $this->gitHelper->getRoot($this->appRoot); if (!$gitRoot) { return; } $appGitIgnore = $this->appRoot . '/.gitignore'; if (!file_exists($appGitIgnore) && !file_exists($gitRoot . '/.gitignore')) { $this->stdErr->writeln("Creating a .gitignore file"); copy($source, $appGitIgnore); } }
php
protected function copyGitIgnore($source) { $source = CLI_ROOT . '/resources/' . $source; $gitRoot = $this->gitHelper->getRoot($this->appRoot); if (!$gitRoot) { return; } $appGitIgnore = $this->appRoot . '/.gitignore'; if (!file_exists($appGitIgnore) && !file_exists($gitRoot . '/.gitignore')) { $this->stdErr->writeln("Creating a .gitignore file"); copy($source, $appGitIgnore); } }
[ "protected", "function", "copyGitIgnore", "(", "$", "source", ")", "{", "$", "source", "=", "CLI_ROOT", ".", "'/resources/'", ".", "$", "source", ";", "$", "gitRoot", "=", "$", "this", "->", "gitHelper", "->", "getRoot", "(", "$", "this", "->", "appRoot"...
Create a default .gitignore file for the app. @param string $source The path to a default .gitignore file, relative to the 'resources' directory.
[ "Create", "a", "default", ".", "gitignore", "file", "for", "the", "app", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/BuildFlavor/BuildFlavorBase.php#L400-L412
platformsh/platformsh-cli
src/Util/TimezoneUtil.php
TimezoneUtil.getTimezone
public static function getTimezone() { // Suppress the PHP warning, "It is not safe to rely on the system's // timezone settings". $currentTz = @date_default_timezone_get(); if ($currentTz !== 'UTC') { return $currentTz; } if (ini_get('date.timezone')) { return ini_get('date.timezone'); } if (getenv('TZ')) { return (string) getenv('TZ'); } if ($systemTz = self::detectSystemTimezone()) { return $systemTz; } return $currentTz; }
php
public static function getTimezone() { // Suppress the PHP warning, "It is not safe to rely on the system's // timezone settings". $currentTz = @date_default_timezone_get(); if ($currentTz !== 'UTC') { return $currentTz; } if (ini_get('date.timezone')) { return ini_get('date.timezone'); } if (getenv('TZ')) { return (string) getenv('TZ'); } if ($systemTz = self::detectSystemTimezone()) { return $systemTz; } return $currentTz; }
[ "public", "static", "function", "getTimezone", "(", ")", "{", "// Suppress the PHP warning, \"It is not safe to rely on the system's", "// timezone settings\".", "$", "currentTz", "=", "@", "date_default_timezone_get", "(", ")", ";", "if", "(", "$", "currentTz", "!==", "'...
Get the timezone intended by the user. The timezone is detected with the following priorities: 1. A value previously set via date_default_timezone_set(), which can only be known if it is not the default, UTC. 2. The value of the ini setting 'date.timezone'. 3. The value of the TZ environment variable, if set. 4. A best guess at the system timezone: see self::detectSystemTimezone(). 5. Default to the value of date_default_timezone_get(), which at this stage will almost definitely be UTC. @return string
[ "Get", "the", "timezone", "intended", "by", "the", "user", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/TimezoneUtil.php#L22-L44
platformsh/platformsh-cli
src/Util/TimezoneUtil.php
TimezoneUtil.detectSystemTimezone
private static function detectSystemTimezone() { // Mac OS X (and older Linuxes): /etc/localtime is a symlink to the // timezone in /usr/share/zoneinfo or /var/db/timezone/zoneinfo. if (is_link('/etc/localtime')) { $filename = readlink('/etc/localtime'); $prefixes = [ '/usr/share/zoneinfo/', '/var/db/timezone/zoneinfo/', ]; foreach ($prefixes as $prefix) { if (strpos($filename, $prefix) === 0) { return substr($filename, strlen($prefix)); } } } // Ubuntu and Debian. if (file_exists('/etc/timezone')) { $data = file_get_contents('/etc/timezone'); if ($data !== false) { return trim($data); } } // RHEL and CentOS. if (file_exists('/etc/sysconfig/clock')) { $data = parse_ini_file('/etc/sysconfig/clock'); if (!empty($data['ZONE'])) { return trim($data['ZONE']); } } return false; }
php
private static function detectSystemTimezone() { // Mac OS X (and older Linuxes): /etc/localtime is a symlink to the // timezone in /usr/share/zoneinfo or /var/db/timezone/zoneinfo. if (is_link('/etc/localtime')) { $filename = readlink('/etc/localtime'); $prefixes = [ '/usr/share/zoneinfo/', '/var/db/timezone/zoneinfo/', ]; foreach ($prefixes as $prefix) { if (strpos($filename, $prefix) === 0) { return substr($filename, strlen($prefix)); } } } // Ubuntu and Debian. if (file_exists('/etc/timezone')) { $data = file_get_contents('/etc/timezone'); if ($data !== false) { return trim($data); } } // RHEL and CentOS. if (file_exists('/etc/sysconfig/clock')) { $data = parse_ini_file('/etc/sysconfig/clock'); if (!empty($data['ZONE'])) { return trim($data['ZONE']); } } return false; }
[ "private", "static", "function", "detectSystemTimezone", "(", ")", "{", "// Mac OS X (and older Linuxes): /etc/localtime is a symlink to the", "// timezone in /usr/share/zoneinfo or /var/db/timezone/zoneinfo.", "if", "(", "is_link", "(", "'/etc/localtime'", ")", ")", "{", "$", "f...
Detect the system timezone, restoring functionality from PHP < 5.4. @return string|false
[ "Detect", "the", "system", "timezone", "restoring", "functionality", "from", "PHP", "<", "5", ".", "4", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/TimezoneUtil.php#L51-L85
platformsh/platformsh-cli
src/Command/Domain/DomainCommandBase.php
DomainCommandBase.validateDomainInput
protected function validateDomainInput(InputInterface $input) { $this->domainName = $input->getArgument('name'); if (!$this->validDomain($this->domainName)) { $this->stdErr->writeln("You must specify a <error>valid domain name</error>"); return false; } $certPath = $input->getOption('cert'); $keyPath = $input->getOption('key'); $chainPaths = $input->getOption('chain'); if ($certPath || $keyPath || $chainPaths) { if (!isset($certPath, $keyPath)) { $this->stdErr->writeln("Both the --cert and the --key are required for SSL certificates"); return false; } try { $this->sslOptions = (new SslUtil())->validate($certPath, $keyPath, $chainPaths); } catch (\InvalidArgumentException $e) { $this->stdErr->writeln($e->getMessage()); return false; } return true; } return true; }
php
protected function validateDomainInput(InputInterface $input) { $this->domainName = $input->getArgument('name'); if (!$this->validDomain($this->domainName)) { $this->stdErr->writeln("You must specify a <error>valid domain name</error>"); return false; } $certPath = $input->getOption('cert'); $keyPath = $input->getOption('key'); $chainPaths = $input->getOption('chain'); if ($certPath || $keyPath || $chainPaths) { if (!isset($certPath, $keyPath)) { $this->stdErr->writeln("Both the --cert and the --key are required for SSL certificates"); return false; } try { $this->sslOptions = (new SslUtil())->validate($certPath, $keyPath, $chainPaths); } catch (\InvalidArgumentException $e) { $this->stdErr->writeln($e->getMessage()); return false; } return true; } return true; }
[ "protected", "function", "validateDomainInput", "(", "InputInterface", "$", "input", ")", "{", "$", "this", "->", "domainName", "=", "$", "input", "->", "getArgument", "(", "'name'", ")", ";", "if", "(", "!", "$", "this", "->", "validDomain", "(", "$", "...
@param InputInterface $input @return bool
[ "@param", "InputInterface", "$input" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Domain/DomainCommandBase.php#L25-L53
platformsh/platformsh-cli
src/Command/Domain/DomainCommandBase.php
DomainCommandBase.handleApiException
protected function handleApiException(ClientException $e, Project $project) { $response = $e->getResponse(); if ($response !== null && $response->getStatusCode() === 403) { $project->ensureFull(); $data = $project->getData(); if (!$project->hasLink('#manage-domains') && !empty($data['subscription']['plan']) && $data['subscription']['plan'] === 'development') { $this->stdErr->writeln('This project is on a Development plan. Upgrade the plan to add domains.'); } } else { throw $e; } }
php
protected function handleApiException(ClientException $e, Project $project) { $response = $e->getResponse(); if ($response !== null && $response->getStatusCode() === 403) { $project->ensureFull(); $data = $project->getData(); if (!$project->hasLink('#manage-domains') && !empty($data['subscription']['plan']) && $data['subscription']['plan'] === 'development') { $this->stdErr->writeln('This project is on a Development plan. Upgrade the plan to add domains.'); } } else { throw $e; } }
[ "protected", "function", "handleApiException", "(", "ClientException", "$", "e", ",", "Project", "$", "project", ")", "{", "$", "response", "=", "$", "e", "->", "getResponse", "(", ")", ";", "if", "(", "$", "response", "!==", "null", "&&", "$", "response...
Output a clear explanation for domains API errors. @param ClientException $e @param Project $project @throws ClientException If it can't be explained.
[ "Output", "a", "clear", "explanation", "for", "domains", "API", "errors", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Domain/DomainCommandBase.php#L84-L98
platformsh/platformsh-cli
src/Command/Commit/CommitGetCommand.php
CommitGetCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input, false, true); $commitSha = $input->getArgument('commit'); /** @var \Platformsh\Cli\Service\GitDataApi $gitData */ $gitData = $this->getService('git_data_api'); $commit = $gitData->getCommit($this->getSelectedEnvironment(), $commitSha); if (!$commit) { if ($commitSha) { $this->stdErr->writeln('Commit not found: <error>' . $commitSha . '</error>'); } else { $this->stdErr->writeln('Commit not found.'); } return 1; } /** @var PropertyFormatter $formatter */ $formatter = $this->getService('property_formatter'); $formatter->displayData($output, $commit->getProperties(), $input->getOption('property')); return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input, false, true); $commitSha = $input->getArgument('commit'); /** @var \Platformsh\Cli\Service\GitDataApi $gitData */ $gitData = $this->getService('git_data_api'); $commit = $gitData->getCommit($this->getSelectedEnvironment(), $commitSha); if (!$commit) { if ($commitSha) { $this->stdErr->writeln('Commit not found: <error>' . $commitSha . '</error>'); } else { $this->stdErr->writeln('Commit not found.'); } return 1; } /** @var PropertyFormatter $formatter */ $formatter = $this->getService('property_formatter'); $formatter->displayData($output, $commit->getProperties(), $input->getOption('property')); return 0; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "validateInput", "(", "$", "input", ",", "false", ",", "true", ")", ";", "$", "commitSha", "=", "$", "input", "->...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Commit/CommitGetCommand.php#L43-L66
platformsh/platformsh-cli
src/Command/Environment/EnvironmentDeleteCommand.php
EnvironmentDeleteCommand.getMergedEnvironments
protected function getMergedEnvironments($base) { $projectRoot = $this->getProjectRoot(); if (!$projectRoot) { throw new RootNotFoundException(); } /** @var \Platformsh\Cli\Service\Git $git */ $git = $this->getService('git'); $git->setDefaultRepositoryDir($projectRoot); /** @var \Platformsh\Cli\Local\LocalProject $localProject */ $localProject = $this->getService('local.project'); $localProject->ensureGitRemote($projectRoot, $this->getSelectedProject()->getGitUrl()); $remoteName = $this->config()->get('detection.git_remote_name'); // Find a list of branches merged on the remote. $git->fetch($remoteName); $mergedBranches = $git->getMergedBranches($remoteName . '/' . $base, true); $mergedBranches = array_filter($mergedBranches, function ($mergedBranch) use ($remoteName, $base) { return strpos($mergedBranch, $remoteName) === 0; }); $stripLength = strlen($remoteName . '/'); $mergedBranches = array_map(function ($mergedBranch) use ($stripLength) { return substr($mergedBranch, $stripLength); }, $mergedBranches); if (empty($mergedBranches)) { return []; } // Reconcile this with the list of environments from the API. $environments = $this->api()->getEnvironments($this->getSelectedProject(), true); $mergedEnvironments = array_intersect_key($environments, array_flip($mergedBranches)); unset($mergedEnvironments[$base], $mergedEnvironments['master']); $parent = $environments[$base]['parent']; if ($parent) { unset($mergedEnvironments[$parent]); } return $mergedEnvironments; }
php
protected function getMergedEnvironments($base) { $projectRoot = $this->getProjectRoot(); if (!$projectRoot) { throw new RootNotFoundException(); } /** @var \Platformsh\Cli\Service\Git $git */ $git = $this->getService('git'); $git->setDefaultRepositoryDir($projectRoot); /** @var \Platformsh\Cli\Local\LocalProject $localProject */ $localProject = $this->getService('local.project'); $localProject->ensureGitRemote($projectRoot, $this->getSelectedProject()->getGitUrl()); $remoteName = $this->config()->get('detection.git_remote_name'); // Find a list of branches merged on the remote. $git->fetch($remoteName); $mergedBranches = $git->getMergedBranches($remoteName . '/' . $base, true); $mergedBranches = array_filter($mergedBranches, function ($mergedBranch) use ($remoteName, $base) { return strpos($mergedBranch, $remoteName) === 0; }); $stripLength = strlen($remoteName . '/'); $mergedBranches = array_map(function ($mergedBranch) use ($stripLength) { return substr($mergedBranch, $stripLength); }, $mergedBranches); if (empty($mergedBranches)) { return []; } // Reconcile this with the list of environments from the API. $environments = $this->api()->getEnvironments($this->getSelectedProject(), true); $mergedEnvironments = array_intersect_key($environments, array_flip($mergedBranches)); unset($mergedEnvironments[$base], $mergedEnvironments['master']); $parent = $environments[$base]['parent']; if ($parent) { unset($mergedEnvironments[$parent]); } return $mergedEnvironments; }
[ "protected", "function", "getMergedEnvironments", "(", "$", "base", ")", "{", "$", "projectRoot", "=", "$", "this", "->", "getProjectRoot", "(", ")", ";", "if", "(", "!", "$", "projectRoot", ")", "{", "throw", "new", "RootNotFoundException", "(", ")", ";",...
@param string $base @return array
[ "@param", "string", "$base" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentDeleteCommand.php#L121-L163
platformsh/platformsh-cli
src/Command/Environment/EnvironmentDeleteCommand.php
EnvironmentDeleteCommand.deleteMultiple
protected function deleteMultiple(array $environments, InputInterface $input, OutputInterface $output) { // Confirm which environments the user wishes to be deleted. $delete = []; $deactivate = []; $error = false; /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); foreach ($environments as $environment) { $environmentId = $environment->id; if ($environmentId == 'master') { $output->writeln("The <error>master</error> environment cannot be deleted."); $error = true; continue; } // Check that the environment does not have children. // @todo remove this check when Platform's behavior is fixed foreach ($this->api()->getEnvironments($this->getSelectedProject()) as $potentialChild) { if ($potentialChild->parent == $environment->id) { $output->writeln( "The environment <error>$environmentId</error> has children and therefore can't be deleted." ); $output->writeln("Please delete the environment's children first."); $error = true; continue 2; } } if ($environment->isActive()) { $output->writeln("The environment <comment>$environmentId</comment> is currently active: deleting it will delete all associated data."); if ($questionHelper->confirm("Are you sure you want to delete the environment <comment>$environmentId</comment>?")) { $deactivate[$environmentId] = $environment; if (!$input->getOption('no-delete-branch') && $this->shouldWait($input) && ($input->getOption('delete-branch') || ( $input->isInteractive() && $questionHelper->confirm("Delete the remote Git branch too?") ) )) { $delete[$environmentId] = $environment; } } } elseif ($environment->status === 'inactive') { if ($questionHelper->confirm("Are you sure you want to delete the remote Git branch <comment>$environmentId</comment>?")) { $delete[$environmentId] = $environment; } } elseif ($environment->status === 'dirty') { $output->writeln("The environment <error>$environmentId</error> is currently building, and therefore can't be deleted. Please wait."); $error = true; continue; } } $deactivateActivities = []; $deactivated = 0; /** @var Environment $environment */ foreach ($deactivate as $environmentId => $environment) { try { $output->writeln("Deleting environment <info>$environmentId</info>"); $deactivateActivities[] = $environment->deactivate(); $deactivated++; } catch (\Exception $e) { $output->writeln($e->getMessage()); } } if ($this->shouldWait($input)) { /** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */ $activityMonitor = $this->getService('activity_monitor'); if (!$activityMonitor->waitMultiple($deactivateActivities, $this->getSelectedProject())) { $error = true; } } $deleted = 0; foreach ($delete as $environmentId => $environment) { try { if ($environment->status !== 'inactive') { $environment->refresh(); if ($environment->status !== 'inactive') { $output->writeln("Cannot delete branch <error>$environmentId</error>: it is not (yet) inactive."); continue; } } $environment->delete(); $output->writeln("Deleted remote Git branch <info>$environmentId</info>"); $deleted++; } catch (\Exception $e) { $output->writeln($e->getMessage()); } } if ($deleted > 0) { $output->writeln("Run <info>git fetch --prune</info> to remove deleted branches from your local cache."); } if ($deleted < count($delete) || $deactivated < count($deactivate)) { $error = true; } if (($deleted || $deactivated || $error) && isset($environment)) { $this->api()->clearEnvironmentsCache($environment->project); } return !$error; }
php
protected function deleteMultiple(array $environments, InputInterface $input, OutputInterface $output) { // Confirm which environments the user wishes to be deleted. $delete = []; $deactivate = []; $error = false; /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */ $questionHelper = $this->getService('question_helper'); foreach ($environments as $environment) { $environmentId = $environment->id; if ($environmentId == 'master') { $output->writeln("The <error>master</error> environment cannot be deleted."); $error = true; continue; } // Check that the environment does not have children. // @todo remove this check when Platform's behavior is fixed foreach ($this->api()->getEnvironments($this->getSelectedProject()) as $potentialChild) { if ($potentialChild->parent == $environment->id) { $output->writeln( "The environment <error>$environmentId</error> has children and therefore can't be deleted." ); $output->writeln("Please delete the environment's children first."); $error = true; continue 2; } } if ($environment->isActive()) { $output->writeln("The environment <comment>$environmentId</comment> is currently active: deleting it will delete all associated data."); if ($questionHelper->confirm("Are you sure you want to delete the environment <comment>$environmentId</comment>?")) { $deactivate[$environmentId] = $environment; if (!$input->getOption('no-delete-branch') && $this->shouldWait($input) && ($input->getOption('delete-branch') || ( $input->isInteractive() && $questionHelper->confirm("Delete the remote Git branch too?") ) )) { $delete[$environmentId] = $environment; } } } elseif ($environment->status === 'inactive') { if ($questionHelper->confirm("Are you sure you want to delete the remote Git branch <comment>$environmentId</comment>?")) { $delete[$environmentId] = $environment; } } elseif ($environment->status === 'dirty') { $output->writeln("The environment <error>$environmentId</error> is currently building, and therefore can't be deleted. Please wait."); $error = true; continue; } } $deactivateActivities = []; $deactivated = 0; /** @var Environment $environment */ foreach ($deactivate as $environmentId => $environment) { try { $output->writeln("Deleting environment <info>$environmentId</info>"); $deactivateActivities[] = $environment->deactivate(); $deactivated++; } catch (\Exception $e) { $output->writeln($e->getMessage()); } } if ($this->shouldWait($input)) { /** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */ $activityMonitor = $this->getService('activity_monitor'); if (!$activityMonitor->waitMultiple($deactivateActivities, $this->getSelectedProject())) { $error = true; } } $deleted = 0; foreach ($delete as $environmentId => $environment) { try { if ($environment->status !== 'inactive') { $environment->refresh(); if ($environment->status !== 'inactive') { $output->writeln("Cannot delete branch <error>$environmentId</error>: it is not (yet) inactive."); continue; } } $environment->delete(); $output->writeln("Deleted remote Git branch <info>$environmentId</info>"); $deleted++; } catch (\Exception $e) { $output->writeln($e->getMessage()); } } if ($deleted > 0) { $output->writeln("Run <info>git fetch --prune</info> to remove deleted branches from your local cache."); } if ($deleted < count($delete) || $deactivated < count($deactivate)) { $error = true; } if (($deleted || $deactivated || $error) && isset($environment)) { $this->api()->clearEnvironmentsCache($environment->project); } return !$error; }
[ "protected", "function", "deleteMultiple", "(", "array", "$", "environments", ",", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "// Confirm which environments the user wishes to be deleted.", "$", "delete", "=", "[", "]", ";", "$", ...
@param Environment[] $environments @param InputInterface $input @param OutputInterface $output @return bool
[ "@param", "Environment", "[]", "$environments", "@param", "InputInterface", "$input", "@param", "OutputInterface", "$output" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentDeleteCommand.php#L172-L277
platformsh/platformsh-cli
src/Service/Drush.php
Drush.getCachedAppRoot
public function getCachedAppRoot($sshUrl) { return isset($this->cachedAppRoots[$sshUrl]) ? $this->cachedAppRoots[$sshUrl] : false; }
php
public function getCachedAppRoot($sshUrl) { return isset($this->cachedAppRoots[$sshUrl]) ? $this->cachedAppRoots[$sshUrl] : false; }
[ "public", "function", "getCachedAppRoot", "(", "$", "sshUrl", ")", "{", "return", "isset", "(", "$", "this", "->", "cachedAppRoots", "[", "$", "sshUrl", "]", ")", "?", "$", "this", "->", "cachedAppRoots", "[", "$", "sshUrl", "]", ":", "false", ";", "}"...
@param string $sshUrl @return string
[ "@param", "string", "$sshUrl" ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Drush.php#L81-L84
platformsh/platformsh-cli
src/Service/Drush.php
Drush.getSiteAliasDir
public function getSiteAliasDir() { $aliasDir = $this->getDrushDir() . '/site-aliases'; if (!file_exists($aliasDir) && $this->getLegacyAliasFiles()) { $aliasDir = $this->getDrushDir(); } return $aliasDir; }
php
public function getSiteAliasDir() { $aliasDir = $this->getDrushDir() . '/site-aliases'; if (!file_exists($aliasDir) && $this->getLegacyAliasFiles()) { $aliasDir = $this->getDrushDir(); } return $aliasDir; }
[ "public", "function", "getSiteAliasDir", "(", ")", "{", "$", "aliasDir", "=", "$", "this", "->", "getDrushDir", "(", ")", ".", "'/site-aliases'", ";", "if", "(", "!", "file_exists", "(", "$", "aliasDir", ")", "&&", "$", "this", "->", "getLegacyAliasFiles",...
Find the directory where global Drush site aliases should be stored. @return string
[ "Find", "the", "directory", "where", "global", "Drush", "site", "aliases", "should", "be", "stored", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Drush.php#L101-L109
platformsh/platformsh-cli
src/Service/Drush.php
Drush.getVersion
public function getVersion($reset = false) { if ($reset || !isset($this->version)) { $this->version = $this->shellHelper->execute( [$this->getDrushExecutable(), 'version', '--format=string'] ); } return $this->version; }
php
public function getVersion($reset = false) { if ($reset || !isset($this->version)) { $this->version = $this->shellHelper->execute( [$this->getDrushExecutable(), 'version', '--format=string'] ); } return $this->version; }
[ "public", "function", "getVersion", "(", "$", "reset", "=", "false", ")", "{", "if", "(", "$", "reset", "||", "!", "isset", "(", "$", "this", "->", "version", ")", ")", "{", "$", "this", "->", "version", "=", "$", "this", "->", "shellHelper", "->",...
Get the installed Drush version. @param bool $reset @return string|false The Drush version, or false if it cannot be determined.
[ "Get", "the", "installed", "Drush", "version", "." ]
train
https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Drush.php#L129-L139