/** * Main * * @param string[] args */ public static function main(array $args) { $way = array_shift($args); $argc = sizeof($args); // Read sourcecode from STDIN if no further argument is given if (0 === $argc) { $code = new Code(file_get_contents('php://stdin')); } else { if ('--' === $args[0]) { $code = new Code(file_get_contents('php://stdin')); } else { $code = new Code($args[0]); } } // Perform $argv = [XPClass::nameOf(self::class)] + $args; $return = eval($code->head() . $code->expression()); switch ($way) { case '-w': Console::writeLine($return); break; case '-d': var_dump($return); break; } }
/** * Start server * * @param string[] args */ public static function main(array $args) { $stor = new TestingStorage(); $stor->add(new TestingCollection('/', $stor)); $stor->add(new TestingCollection('/.trash', $stor)); $stor->add(new TestingElement('/.trash/do-not-remove.txt', $stor)); $stor->add(new TestingCollection('/htdocs', $stor)); $stor->add(new TestingElement('/htdocs/file with whitespaces.html', $stor)); $stor->add(new TestingElement('/htdocs/index.html', $stor, "<html/>\n")); $stor->add(new TestingCollection('/outer', $stor)); $stor->add(new TestingCollection('/outer/inner', $stor)); $stor->add(new TestingElement('/outer/inner/index.html', $stor)); $auth = newinstance('lang.Object', array(), '{ public function authenticate($user, $password) { return ("testtest" == $user.$password); } }'); $protocol = newinstance('peer.ftp.server.FtpProtocol', array($stor, $auth), '{ public function onShutdown($socket, $params) { $this->answer($socket, 200, "Shutting down"); $this->server->terminate= TRUE; } }'); isset($args[0]) && $protocol->setTrace(Logger::getInstance()->getCategory()->withAppender(new FileAppender($args[0]))); $s = new Server('127.0.0.1', 0); try { $s->setProtocol($protocol); $s->init(); Console::writeLinef('+ Service %s:%d', $s->socket->host, $s->socket->port); $s->service(); Console::writeLine('+ Done'); } catch (\lang\Throwable $e) { Console::writeLine('- ', $e->getMessage()); } }
/** * Performs measurement * * @param util.profiling.Measurement $m */ public function run($m) { $m->perform(newinstance('util.profiling.Run', [], ['before' => function ($iteration) { Console::write($iteration->name(), ': '); }, 'after' => function ($result) { Console::writeLinef('%d iteration(s), %.3f seconds, result= %s', $result->iteration()->times(), $result->elapsed(), Objects::stringOf($result->result())); }])); }
/** * Main * * @param string[] args * @return int */ public static function main(array $args) { Console::writeLinef('XP %s { PHP %s & ZE %s } @ %s', \xp::version(), phpversion(), zend_version(), php_uname()); Console::writeLine('Copyright (c) 2001-2015 the XP group'); foreach (\lang\ClassLoader::getLoaders() as $delegate) { Console::writeLine($delegate->toString()); } return 1; }
/** * Display some information * * Annotate this method w/ @test to retrieve debug information. */ public function classLoaderInformation() { with($p = \lang\reflect\Package::forName('net.xp_framework.unittest.reflection.classes')); \util\cmd\Console::writeLine('Object : ', \lang\XPClass::forName('lang.Object')->getClassLoader()); \util\cmd\Console::writeLine('This : ', $this->getClass()->getClassLoader()); \util\cmd\Console::writeLine('ClassOne : ', $p->loadClass('ClassOne')->getClassLoader()); \util\cmd\Console::writeLine('ClassTwo : ', $p->loadClass('ClassTwo')->getClassLoader()); \util\cmd\Console::writeLine('ClassThree : ', $p->loadClass('ClassThree')->getClassLoader()); \util\cmd\Console::writeLine('ClassFour : ', $p->loadClass('ClassFour')->getClassLoader()); \util\cmd\Console::writeLine('ClassFive : ', $p->loadClass('ClassFive')->getClassLoader()); }
/** * Start server * * @param string[] args */ public static function main(array $args) { $s = new Server('127.0.0.1', 0); try { $s->setProtocol(\lang\XPClass::forName($args[0])->newInstance()); $s->init(); Console::writeLinef('+ Service %s:%d', $s->socket->host, $s->socket->port); $s->service(); Console::writeLine('+ Done'); } catch (\lang\Throwable $e) { Console::writeLine('- ', $e->getMessage()); } }
/** * Entry point method. Receives the following arguments from xpws: * * - The web root - defaults to $CWD * - The configuration directory - defaults to "etc" * - The server profile - default to "dev" * - The server address - default to "localhost:8080" * - The mode - default to "serve" * * @param string[] args * @return int */ public static function main(array $args) { $webroot = isset($args[0]) ? realpath($args[0]) : getcwd(); $configd = isset($args[1]) ? $args[1] : 'etc'; $profile = isset($args[2]) ? $args[2] : 'dev'; $address = isset($args[3]) ? $args[3] : 'localhost:8080'; if (!($class = @self::$modes[isset($args[4]) ? $args[4] : 'serve'])) { Console::writeLine('*** Unkown server mode "', $args[4], '", supported: ', self::$modes); return 2; } $expand = function ($in) use($webroot, $profile) { return strtr($in, array('{WEBROOT}' => $webroot, '{PROFILE}' => $profile, '{DOCUMENT_ROOT}' => getenv('DOCUMENT_ROOT'))); }; Console::writeLine('---> Startup ', $class, '(', $address, ')'); sscanf($address, '%[^:]:%d', $host, $port); $server = XPClass::forName($class)->newInstance($host, $port); with($pm = PropertyManager::getInstance(), $protocol = $server->setProtocol(new HttpProtocol())); $conf = new WebConfiguration(new \util\Properties($configd . DIRECTORY_SEPARATOR . 'web.ini')); $resources = $conf->staticResources($args[2]); if (null === $resources) { $protocol->setUrlHandler('default', '#^/#', new FileHandler($expand('{DOCUMENT_ROOT}'), $notFound = function () { return HttpConstants::STATUS_CONTINUE; })); } else { foreach ($conf->staticResources($args[2]) as $pattern => $location) { $protocol->setUrlHandler('default', '#' . strtr($pattern, array('#' => '\\#')) . '#', new FileHandler($expand($location))); } } foreach ($conf->mappedApplications($args[2]) as $url => $application) { foreach (explode('|', $application->getConfig()) as $element) { $expanded = $expand($element); if (0 == strncmp('res://', $expanded, 6)) { $pm->appendSource(new ResourcePropertySource(substr($expanded, 6))); } else { $pm->appendSource(new FilesystemPropertySource($expanded)); } } $protocol->setUrlHandler('default', '/' == $url ? '##' : '#^(' . preg_quote($url, '#') . ')($|/.+)#', new ScriptletHandler($application->getScriptlet(), array_map($expand, $application->getArguments()), array_map($expand, array_merge($application->getEnvironment(), array('DOCUMENT_ROOT' => getenv('DOCUMENT_ROOT')))))); } $l = Logger::getInstance(); $pm->hasProperties('log') && $l->configure($pm->getProperties('log')); $cm = ConnectionManager::getInstance(); $pm->hasProperties('database') && $cm->configure($pm->getProperties('database')); Console::writeLine($protocol); $server->init(); Console::writeLine('===> Server started'); $server->service(); $server->shutdown(); return 0; }
/** * Entry point method. Gets passed the following arguments from "xpws -i": * <ol> * <li>The web root - defaults to $CWD</li> * <li>The configuration directory - defaults to "etc"</li> * <li>The server profile - default to "dev"</li> * <li>The server address - default to "localhost:8080"</li> * </ol> * * @param string[] args */ public static function main(array $args) { $webroot = isset($args[0]) ? realpath($args[0]) : getcwd(); $configd = isset($args[1]) ? $args[1] : 'etc'; $profile = isset($args[2]) ? $args[2] : 'dev'; $address = isset($args[3]) ? $args[3] : 'localhost:8080'; Console::writeLine('xpws-', $profile, ' @ ', $address, ', ', $webroot, ' {'); // Dump configured applications $conf = new WebConfiguration(new Properties($configd . DIRECTORY_SEPARATOR . 'web.ini')); foreach ($conf->mappedApplications($profile) as $url => $app) { Console::writeLine(' Route<', $url, '*> => ', \xp::stringOf($app, ' ')); } Console::writeLine('}'); }
/** * Execute this action * * @param string[] $args command line args * @return int exit code */ public function perform($args) { $request = create(new RestRequest('/search'))->withParameter('q', $args[0]); $total = 0; Console::writeLine('@', $this->api->getBase()->getURL()); $results = $this->api->execute($request)->data(); foreach ($results as $result) { Console::writeLine(new Module($result['vendor'], $result['module']), ': ', $result['info']); $total++; } Console::writeLine(); Console::writeLine($total, ' modules(s) found.'); return 0; }
/** * Entry point method. Gets passed the following arguments from "xpws -i": * * 1. The web root - a directory * 2. The application source - either a directory or ":" + f.q.c.Name * 3. The server profile - any name, really, defaulting to "dev" * 4. The server address - default to "localhost:8080" * * @param string[] args */ public static function main(array $args) { $webroot = isset($args[0]) ? realpath($args[0]) : getcwd(); $source = isset($args[1]) ? $args[1] : 'etc'; $profile = isset($args[2]) ? $args[2] : 'dev'; $address = isset($args[3]) ? $args[3] : 'localhost:8080'; Console::writeLine('@Path<', $webroot, '>'); Console::writeLine('xpws-', $profile, ' @ ', $address, ' {'); $layout = (new Source($source))->layout(); foreach ($layout->staticResources($profile) as $pattern => $path) { Console::writeLine(' route(', $pattern, ') -> xp.scriptlet.StaticContent(', $path, '/$1)'); } foreach ($layout->mappedApplications($profile) as $url => $app) { Console::writeLine(' route(', '/' === $url ? '' : '^' . $url, '*) -> ', \xp::stringOf($app, ' ')); } Console::writeLine('}'); }
/** * Start server * * @param string[] args */ public static function main(array $args) { // Add shutdown message handler \remote\server\message\EascMessageFactory::setHandler(61, newinstance('remote.server.message.EascMessage', array(), '{ public function getType() { return 61; } public function handle($protocol, $data) { Logger::getInstance()->getCategory()->debug("Shutting down"); $protocol->server->terminate= TRUE; } }')->getClass()); $s = new Server('127.0.0.1', 0); try { $protocol = new EascProtocol(newinstance('remote.server.deploy.scan.DeploymentScanner', array(), '{ private $changed= TRUE; public function scanDeployments() { $changed= $this->changed; $this->changed= FALSE; return $changed; } public function getDeployments() { $res= "net/xp_framework/unittest/remote/deploy/beans.test.CalculatorBean.xar"; with ($d= new Deployment($res)); { $d->setClassLoader(new \\lang\\archive\\ArchiveClassLoader(new \\lang\\archive\\Archive(\\lang\\ClassLoader::getDefault()->getResourceAsStream($res)))); $d->setImplementation("beans.test.CalculatorBeanImpl"); $d->setInterface("beans.test.Calculator"); $d->setDirectoryName("xp/test/Calculator"); return array($d); } } }')); $protocol->initialize(); $s->setProtocol($protocol); $s->init(); Console::writeLinef('+ Service %s:%d', $s->socket->host, $s->socket->port); $s->service(); Console::writeLine('+ Done'); } catch (\lang\Throwable $e) { Console::writeLine('- ', $e->getMessage()); } }
/** * Serve requests * * @param string $source * @param string $profile * @param io.Path $webroot * @param io.Path $docroot * @param string[] $config */ public function serve($source, $profile, $webroot, $docroot, $config) { $runtime = Runtime::getInstance(); $startup = $runtime->startupOptions(); $backing = typeof($startup)->getField('backing')->setAccessible(true)->get($startup); // PHP doesn't start with a nonexistant document root if (!$docroot->exists()) { $docroot = getcwd(); } // Start `php -S`, the development webserver $arguments = ['-S', $this->host . ':' . $this->port, '-t', $docroot]; $options = newinstance(RuntimeOptions::class, [$backing], ['asArguments' => function () use($arguments) { return array_merge($arguments, parent::asArguments()); }]); $options->withSetting('user_dir', $source . PATH_SEPARATOR . implode(PATH_SEPARATOR, $config)); // Pass classpath (TODO: This is fixed in XP 7.6.0, remove once // this becomes minimum dependency) $cp = []; foreach (ClassLoader::getLoaders() as $delegate) { if ($delegate instanceof FileSystemClassLoader || $delegate instanceof ArchiveClassLoader) { $cp[] = $delegate->path; } } set_include_path(''); $options->withClassPath($cp); // Export environment putenv('DOCUMENT_ROOT=' . $docroot); putenv('WEB_ROOT=' . $webroot); putenv('SERVER_PROFILE=' . $profile); Console::writeLine("[33m@", $this, "[0m"); Console::writeLine("[1mServing ", (new Source($source, new Config($config)))->layout()); Console::writeLine("[36m", str_repeat('═', 72), "[0m"); Console::writeLine(); with($runtime->newInstance($options, 'web', '', []), function ($proc) { $proc->in->close(); Console::writeLine("[33;1m>[0m Server started: [35;4m", $this->url, "[0m (", date('r'), ')'); Console::writeLine(' PID ', $proc->getProcessId(), '; press Ctrl+C to exit'); Console::writeLine(); while (is_string($line = $proc->err->readLine())) { Console::writeLine(" [36m", $line, "[0m"); } }); }
/** * Serve requests * * @param string $source * @param string $profile * @param io.Path $webroot * @param io.Path $docroot * @param string[] $config */ public function serve($source, $profile, $webroot, $docroot, $config) { $this->server->init(); $protocol = $this->server->setProtocol(new HttpProtocol(function ($host, $method, $query, $status, $error) { Console::writeLinef(" [33m[%s %d %.3fkB][0m %d %s %s", date('Y-m-d H:i:s'), getmypid(), memory_get_usage() / 1024, $status, $method, $query, $error); })); $pm = PropertyManager::getInstance(); $expand = function ($in) use($webroot, $profile, $docroot) { return is_string($in) ? strtr($in, ['{WEBROOT}' => $webroot, '{PROFILE}' => $profile, '{DOCUMENT_ROOT}' => $docroot]) : $in; }; $layout = (new Source($source, new Config($config, $expand)))->layout(); Console::writeLine("[33m@", $this, "[0m"); Console::writeLine("[1mServing ", $layout); Console::writeLine("[36m", str_repeat('═', 72), "[0m"); Console::writeLine(); $resources = $layout->staticResources($profile); if (null === $resources) { $protocol->setUrlHandler('default', '#^/#', new FileHandler($docroot, $notFound = function () { return null; })); } else { foreach ($resources as $pattern => $location) { $protocol->setUrlHandler('default', '#' . strtr($pattern, ['#' => '\\#']) . '#', new FileHandler($expand($location))); } } foreach ($layout->mappedApplications($profile) as $url => $application) { $protocol->setUrlHandler('default', '/' === $url ? '##' : '#^(' . preg_quote($url, '#') . ')($|/.+)#', new ScriptletHandler($application->scriptlet(), array_map($expand, $application->arguments()), array_map($expand, array_merge($application->environment(), ['DOCUMENT_ROOT' => $docroot])), $application->filters())); foreach ($application->config()->sources() as $s) { $pm->appendSource($s); } } $l = Logger::getInstance(); $pm->hasProperties('log') && $l->configure($pm->getProperties('log')); $cm = ConnectionManager::getInstance(); $pm->hasProperties('database') && $cm->configure($pm->getProperties('database')); Console::writeLine("[33;1m>[0m Server started: [35;4m", $this->url, "[0m (", date('r'), ')'); Console::writeLine(' PID ', getmypid(), '; press Ctrl+C to exit'); Console::writeLine(); $this->server->service(); $this->server->shutdown(); }
/** * Main * * @param string[] $args * @return int */ public static function main(array $args) { if (empty($args)) { Console::writeLinef('XP %s { PHP %s & ZE %s } @ %s', \xp::version(), phpversion(), zend_version(), php_uname()); Console::writeLine('Copyright (c) 2001-2016 the XP group'); foreach (\lang\ClassLoader::getLoaders() as $delegate) { Console::writeLine($delegate->toString()); } return 1; } else { foreach ($args as $arg) { $method = $arg . 'Version'; if (is_callable(['self', $method])) { Console::writeLine(self::$method()); } else { Console::$err->writeLinef('Unkown version argument `%s\'', $arg); } } return 0; } }
/** * Execute this action * * @param string[] $args command line args * @return int exit code */ public function perform($args) { $cwd = new FileCollection('.'); $isModule = new ExtensionEqualsFilter('.json'); // If an argument is given, search only that vendor if (isset($args[0])) { $find = $cwd->getCollection($args[0]); } else { $find = $cwd; } $total = 0; Console::writeLine('@', $cwd->getURI()); foreach (new FilteredIOCollectionIterator($find, $isModule, true) as $module) { $result = self::$json->decodeFrom($module->getInputStream()); Console::writeLine(new Module($result['vendor'], $result['module']), ': ', $result['info']); $total++; } Console::writeLine(); Console::writeLine($total, ' module(s) installed'); return 0; }
/** * Main * * @param string[] $args * @return int */ public static function main($args) { $name = array_shift($args); if (null === $name) { Console::$err->writeLine('*** No class or package name given'); return 1; } // Check whether a file, class or a package directory or name is given $cl = ClassLoader::getDefault(); try { if (strstr($name, \xp::CLASS_FILE_EXT)) { $info = new TypeInformation($cl->loadUri(realpath($name))); } else { if (is_dir($name)) { $info = new DirectoryInformation($name); } else { if ($cl->providesClass($name)) { $info = new TypeInformation($cl->loadClass($name)); } else { if ($cl->providesPackage($name)) { $info = new PackageInformation($name); } else { Console::$err->writeLine('*** No classloader provides ' . $name); return 2; } } } } } catch (IllegalArgumentException $e) { Console::$err->writeLine('*** ' . $e->getMessage()); return 2; } foreach ($info->sources() as $source) { Console::writeLine("[33m@", $source, "[0m"); } $info->display(new Highlighting(Console::$out, ['/(class|enum|trait|interface|package|directory) (.+)/' => "[1;35m\$1[0m \$2", '/(extends|implements) (.+)/' => "[1;35m\$1[0m \$2", '/(public|private|protected|abstract|final|static)/' => "[1;35m\$1[0m", '/(\\$[a-zA-Z0-9_]+)/' => "[1;31m\$1[0m"])); return 0; }
/** * Main * * @param string[] args */ public static function main(array $args) { $way = array_shift($args); // Read sourcecode from STDIN if no further argument is given if (0 === sizeof($args)) { $src = file_get_contents('php://stdin'); } else { $src = $args[0]; } $src = trim($src, ' ;') . ';'; // Extract uses() and load classes if (0 === strncmp($src, 'uses', 4)) { $p = strpos($src, ');'); $uses = substr($src, 5, $p - 5); // "uses(" $src = substr($src, $p + 2); // ");" foreach (explode(',', $uses) as $class) { uses(trim($class, '" ')); } } // Allow missing return strstr($src, 'return ') || strstr($src, 'return;') || ($src = 'return ' . $src); // Rewrite argc, argv $argv = array(\xp::nameOf(__CLASS__)) + $args; $argc = sizeof($argv); // Perform $return = eval($src); switch ($way) { case '-w': Console::writeLine($return); break; case '-d': var_dump($return); break; } }
/** * Fetches this origin into a given target folder * * @param io.Folder $target */ public function fetchInto(Folder $target) { $r = $this->client->execute($this->release); if (200 !== $r->status()) { throw new \lang\IllegalArgumentException($r->message() . ': ' . $this->release->toString()); } $release = $r->data(); Console::writeLine('Release ', $release['version']['number'], ' published ', $release['published']); // Download files $pth = create(new File($target, 'class.pth'))->getOutputStream(); foreach ($release['files'] as $file) { $d = $this->client->execute(new RestRequest($file['link'])); $f = new File($target, $file['name']); Console::writeLine('>> ', $file['name']); $tran = new StreamTransfer($d->stream(), $f->getOutputStream()); $tran->transferAll(); $tran->close(); $ext = substr($file['name'], strrpos($file['name'], '.')); if ('.php' === $ext || '.xar' === $ext) { $pth->write($file['name'] . "\n"); } } $pth->close(); }
/** * Execute this action * * @param string[] $args command line args * @return int exit code */ public function perform($args) { if (empty($args)) { Console::$err->writeLine('*** Missing argument #1: Module name'); return 2; } sscanf($args[0], '%[^@]@%s', $name, $version); $module = Module::valueOf($name); $cwd = new Folder('.'); $base = new Folder($cwd, $module->vendor); // No version supplied -> check installation. If the module is already // installed, this is "xpi upgrade"'s job. If we have a version, the user // wants to install in parallel, so pass. if (null === $version) { $f = new File($base, $module->name . '.json'); if ($f->exists()) { Console::$err->writeLine('*** Not changing existing ', $module, '. Use "xpi upgrade"'); return 1; } } // Search for module $request = create(new RestRequest('/vendors/{vendor}/modules/{module}'))->withSegment('vendor', $module->vendor)->withSegment('module', $module->name); try { $info = $this->api->execute($request)->data(); uksort($info['releases'], function ($a, $b) { return version_compare($a, $b, '<'); }); } catch (RestException $e) { Console::$err->writeLine('*** Cannot find module ', $module, ': ', $e->getMessage()); return 3; } // Check newest version if (null === $version) { if (empty($info['releases'])) { Console::$err->writeLine('*** No releases yet for ', $module); return 1; } $version = key($info['releases']); $this->cat && $this->cat->info('Using latest release', $version); } else { if (':' === $version[0]) { $this->cat && $this->cat->info('Using development version', $version); } else { if (!isset($info['releases'][$version])) { Console::$err->writeLine('*** No such release ', $version, ' for ', $module, ', have ', $info['releases']); return 1; } $this->cat && $this->cat->info('Using version', $version); } } // Determine origin and target if (':' === $version[0]) { $branch = substr($version, 1); $target = new Folder($base, $module->name . '@' . $branch); $origin = new GitHubArchive($module->vendor, $module->name, $branch); } else { $target = new Folder($base, $module->name . '@' . $version); $origin = new XarRelease($this->api, $module->vendor, $module->name, $version); } if ($target->exists()) { Console::writeLine($module, ' already exists in ', $target); } else { Console::writeLine($module, ' -> ', $target); try { // Create and fetch into $target->create(0755); $origin->fetchInto($target); // Save module meta data unset($info['releases']); self::$json->encodeTo($info, create(new File($base, $module->name . '.json'))->getOutputStream()); } catch (\lang\Throwable $e) { Console::writeLine('*** ', $e); $target->unlink(); return 2; } } // Deselect any previously selected version foreach (new FilteredIOCollectionIterator(new FileCollection($cwd), new NameMatchesFilter('#^\\.' . $module->vendor . '\\.' . $module->name . '.*\\.pth#')) as $found) { $pth = new File($found->getURI()); Console::writeLine('Deselect ', $pth); $pth->unlink(); } // Rebuild paths based on .pth files found in newly selected $pth = new File('.' . $module->vendor . '.' . strtr($target->dirname, DIRECTORY_SEPARATOR, '.') . '.pth'); $out = $pth->getOutputStream(); $base = strtr(substr($target->getURI(), strlen($cwd->getURI())), DIRECTORY_SEPARATOR, '/'); Console::writeLine('Select ', $pth); foreach (new FilteredIOCollectionIterator(new FileCollection($target), new ExtensionEqualsFilter('.pth')) as $found) { $r = new StringReader($found->getInputStream()); while (null !== ($line = $r->readLine())) { if ('' === $line || '#' === $line[0]) { continue; } else { if ('!' === $line[0]) { $out->write('!' . $base . substr($line, 1) . "\n"); } else { $out->write($base . $line . "\n"); } } } } $out->close(); Console::writeLine('Done'); return 0; }
public function writeLinef_argument_with_end_tag() { $this->assertWritten("[31;1m</>[22;39m\n", function () { Console::writeLinef('<red>%s</>', '</>'); }); }
/** * Start server * * @param string[] args */ public static function main(array $args) { $protocol = newinstance('peer.server.ServerProtocol', array(), '{ public function initialize() { } public function handleDisconnect($socket) { } public function handleError($socket, $e) { } public function handleConnect($socket) { } public function handleData($socket) { $cmd= $socket->readLine(); switch (substr($cmd, 0, 4)) { case "ECHO": { $socket->write("+ECHO ".substr($cmd, 5)."\\n"); break; } case "LINE": { sscanf(substr($cmd, 5), "%d %s", $l, $sep); for ($i= 0, $sbytes= urldecode($sep); $i < $l; $i++) { $socket->write("+LINE ".$i.$sbytes); } $socket->write("+LINE .\\n"); break; } case "CLOS": { $socket->close(); break; } case "HALT": { $socket->write("+HALT\\n"); $this->server->terminate= TRUE; break; } } } }'); $s = new Server('127.0.0.1', 0); try { $s->setProtocol($protocol); $s->init(); Console::writeLinef('+ Service %s:%d', $s->socket->host, $s->socket->port); $s->service(); Console::writeLine('+ Done'); } catch (\lang\Throwable $e) { Console::writeLine('- ', $e->getMessage()); } }
public function select_userdefined_emitter() { ClassLoader::defineClass('xp.compiler.emit.test.Emitter', 'xp.compiler.emit.php.V54Emitter', [], ['emit' => function (ParseTree $tree, Scope $scope) { Console::writeLine('Test emitter emitting...'); return parent::emit($tree, $scope); }]); $this->assertEquals("Test emitter emitting...\nTest\n", $this->run(['-E', 'test', '-w', 'xp', '"Test"'])['out']); }
/** * Main runner method * * @param string[] args */ public static function main(array $args) { if (!$args) { self::usage(); } // Parse arguments $output = '-'; for ($i = 0, $s = sizeof($args); $i < $s; $i++) { if ('-O' == $args[$i]) { $output = $args[++$i]; } else { if ('-?' == $args[$i] || '--help' == $args[$i]) { self::usage(); } else { $package = $args[$i]; break; } } } // Load generator class try { $class = \lang\reflect\Package::forName('xp.codegen')->getPackage($package)->loadClass('Generator'); } catch (\lang\ElementNotFoundException $e) { Console::$err->writeLine('*** No generator named "' . $package . '"'); exit(2); } $params = new ParamString(array_slice($args, $i + 1)); if ($params->exists('help', '?')) { Console::$err->writeLine(self::textOf($class->getComment())); exit(1); } // Instantiate generator $generator = $class->newInstance($params); $generator->storage = new FileSystemStorage(System::tempDir()); // Output if ('-' === $output) { $generator->output = new ConsoleOutput(Console::$err); } else { if (strstr($output, '.xar')) { $generator->output = new ArchiveOutput($output); } else { $generator->output = new FileSystemOutput($output); } } $generator->output->addObserver(newinstance('util.Observer', array(), '{ public function update($obs, $arg= NULL) { Console::writeLine(" >> ", $arg); } }')); Console::writeLine('===> Starting ', $generator); // Compile target chain $empty = new \lang\types\ArrayList(); $targets = create('new util.collections.HashTable<lang.reflect.Method, util.collections.HashTable<string, lang.Generic>>()'); foreach ($class->getMethods() as $method) { if (!$method->hasAnnotation('target')) { continue; } $target = create('new util.collections.HashTable<string, lang.Generic>()'); // Fetch dependencies if ($method->hasAnnotation('target', 'depends')) { $depends = create('new util.collections.Vector<lang.reflect.Method>()'); foreach ((array) $method->getAnnotation('target', 'depends') as $dependency) { $depends[] = $class->getMethod($dependency); } $target['depends'] = $depends; } // Fetch input if ($method->hasAnnotation('target', 'input')) { $arguments = create('new util.collections.Vector<lang.reflect.Method>()'); foreach ((array) $method->getAnnotation('target', 'input') as $input) { $arguments[] = $class->getMethod($input); } $target['arguments'] = $arguments; } $targets->put($method, $target); } // Invoke try { foreach ($targets->keys() as $method) { self::invoke($generator, $method, $targets); } } catch (\lang\reflect\TargetInvocationException $e) { Console::$err->writeLine('*** ', $e->getCause()); exit(3); } $generator->output->commit(); Console::writeLine('===> Done'); }
/** * Entry point method * * @param string[] args */ public static function main(array $args) { if (empty($args)) { self::showUsage(); return 2; } foreach (ClassLoader::getLoaders() as $loader) { if ($loader instanceof JitClassLoader) { ClassLoader::removeLoader($loader); } } // Set up compiler $compiler = new Compiler(); $manager = new FileManager(); $manager->setSourcePaths(\xp::$classpath); // Handle arguments $profiles = ['default']; $emitter = 'php5.5'; $result = function ($success) { return $success ? 0 : 1; }; $files = []; $listener = new DefaultDiagnosticListener(Console::$out); for ($i = 0, $s = sizeof($args); $i < $s; $i++) { if ('-?' == $args[$i] || '--help' == $args[$i]) { self::showUsage(); return 2; } else { if ('-cp' == $args[$i]) { \lang\ClassLoader::registerPath($args[++$i]); } else { if ('-sp' == $args[$i]) { $manager->addSourcePath($args[++$i]); } else { if ('-v' == $args[$i]) { $listener = new VerboseDiagnosticListener(Console::$out); } else { if ('-q' == $args[$i]) { $listener = new QuietDiagnosticListener(Console::$out); } else { if ('-t' == $args[$i]) { $levels = LogLevel::NONE; foreach (explode(',', $args[++$i]) as $level) { $levels |= LogLevel::named($level); } $compiler->setTrace(create(new LogCategory('xcc'))->withAppender(new ConsoleAppender(), $levels)); } else { if ('-E' == $args[$i]) { $emitter = $args[++$i]; } else { if ('-p' == $args[$i]) { $profiles = explode(',', $args[++$i]); } else { if ('-o' == $args[$i]) { $output = $args[++$i]; $folder = new Folder($output); $folder->exists() || $folder->create(); $manager->setOutput($folder); } else { if ('-N' == $args[$i]) { $files = array_merge($files, self::fromFolder($args[++$i], false)); } else { if (is_dir($args[$i])) { $files = array_merge($files, self::fromFolder($args[$i], true)); } else { if ('-e' == $args[$i]) { $listener = new QuietDiagnosticListener(Console::$out); $files[] = new CommandLineSource($args[++$i], $args[++$i], false); $manager = self::declaringFileManager(); $result = function ($success, $argv) use($manager) { if (!$success) { return 1; } return (int) $manager->declared[0]->getMethod('main')->invoke(null, [$argv]); }; break; } else { if ('-w' == $args[$i]) { $listener = new QuietDiagnosticListener(Console::$out); $files[] = new CommandLineSource($args[++$i], $args[++$i], true); $manager = self::declaringFileManager(); $result = function ($success, $argv) use($manager) { if (!$success) { return 1; } Console::writeLine($manager->declared[0]->getMethod('main')->invoke(null, [$argv])); return 0; }; break; } else { $files[] = new FileSource(new File($args[$i])); } } } } } } } } } } } } } } // Check if (empty($files)) { Console::$err->writeLine('*** No files given (-? will show usage)'); return 2; } // Setup emitter sscanf($emitter, '%[^0-9]%d.%d', $language, $major, $minor); try { $emit = \lang\XPClass::forName('xp.compiler.emit.Emitter')->cast(Package::forName('xp.compiler.emit')->getPackage($language)->loadClass(($major ? 'V' . $major . $minor : '') . 'Emitter')->newInstance()); } catch (\lang\ClassCastException $e) { Console::$err->writeLine('*** Not an emitter implementation: ', $e->compoundMessage()); return 4; } catch (\lang\IllegalAccessException $e) { Console::$err->writeLine('*** Cannot use emitter named "', $emitter, '": ', $e->compoundMessage()); return 4; } catch (\lang\Throwable $e) { Console::$err->writeLine('*** No emitter named "', $emitter, '": ', $e->compoundMessage()); return 4; } // Load compiler profile configurations try { $reader = new CompilationProfileReader(); foreach ($profiles as $configuration) { $reader->addSource(new Properties('res://xp/compiler/' . $configuration . '.xcp.ini')); } $emit->setProfile($reader->getProfile()); } catch (\lang\Throwable $e) { Console::$err->writeLine('*** Cannot load profile configuration(s) ' . implode(',', $profiles) . ': ' . $e->getMessage()); return 3; } // Compile files and pass return value to result handler return $result($compiler->compile($files, $listener, $manager, $emit), array_slice($args, $i + 1)); }
/** * Execute this action * * @param string[] $args command line args * @return int exit code */ public function perform($args) { if (empty($args)) { Console::$err->writeLine('*** Missing argument #1: Module name'); return 2; } sscanf($args[0], '%[^@]@%s', $name, $version); $module = Module::valueOf($name); $cwd = new Folder('.'); $vendor = new FileCollection(new Folder($cwd, $module->vendor)); $versions = new FilteredIOCollectionIterator($vendor, new NameMatchesFilter('#^' . $module->name . '@.+#')); if (null === $version) { // No version given: Remove all installed modules, and the module reference if (!$vendor->findElement($module->name . '.json')) { Console::writeLine($module, ' not installed'); return 1; } $this->removeAll($cwd, $versions); Console::writeLine('Removing module reference'); $vendor->removeElement($module->name . '.json'); } else { // Specific version given: Remove this version, if it's the last one, the // module reference, if not, select next possible one. if (!($coll = $vendor->findCollection($module->name . '@' . $version))) { Console::writeLine($module, ' not installed in version ', $version); return 1; } $active = $this->remove($cwd, $coll); if ($versions->hasNext()) { if ($active) { $next = $versions->next(); $pth = new File('.' . $module->vendor . '.' . basename($next->getURI()) . '.pth'); $out = $pth->getOutputStream(); $base = strtr(substr($next->getURI(), strlen($cwd->getURI())), DIRECTORY_SEPARATOR, '/'); Console::writeLine('Select ', $pth); foreach (new FilteredIOCollectionIterator($next, new ExtensionEqualsFilter('.pth')) as $found) { $r = new StringReader($found->getInputStream()); while (null !== ($line = $r->readLine())) { if ('' === $line || '#' === $line[0]) { continue; } else { if ('!' === $line[0]) { $out->write('!' . $base . substr($line, 1) . "\n"); } else { $out->write($base . $line . "\n"); } } } } } } else { Console::writeLine('Removing module reference'); $vendor->removeElement($module->name . '.json'); } } Console::writeLine('Done'); return 0; }
/** * Execute this action * * @param string[] $args command line args * @return int exit code */ public function perform($args) { $cwd = new FileCollection('.'); // Parse args $i = 1; if ('-r' === $args[0]) { $remote = true; array_shift($args); $i++; } else { if ('-i' === $args[0]) { $remote = false; array_shift($args); $i++; $installed = new File($args[0] . '.json'); } else { $installed = new File($args[0] . '.json'); $remote = !$installed->exists(); } } if (empty($args)) { Console::$err->writeLine('*** Missing argument #', $i, ': Module name'); return 2; } sscanf(rtrim($args[0], '/'), '%[^@]@%s', $name, $version); $module = Module::valueOf($name); // Search for module if ($remote) { Console::writeLine('@', $this->api->getBase()->getURL()); $request = create(new RestRequest('/vendors/{vendor}/modules/{module}'))->withSegment('vendor', $module->vendor)->withSegment('module', $module->name); try { $result = $this->api->execute($request)->data(); } catch (RestException $e) { Console::$err->writeLine('*** Cannot find remote module ', $module, ': ', $e->getMessage()); return 3; } $releases = $result['releases']; } else { Console::writeLine('@', $cwd->getURI()); try { $result = self::$json->decodeFrom($installed->getInputStream()); } catch (IOException $e) { Console::$err->writeLine('*** Cannot find installed module ', $module, ': ', $e->getMessage()); return 3; } $releases = $this->installedReleases($cwd, $module); } Console::writeLine(new Module($result['vendor'], $result['module']), ': ', $result['info']); Console::writeLine($result['link']['url']); uksort($releases, function ($a, $b) { return version_compare($a, $b, '<'); }); Console::writeLine('Releases: ', sizeof($releases), ', list {'); foreach ($releases as $version => $release) { $s = ''; foreach ($release as $key => $value) { $s .= ', ' . $key . '= ' . \xp::stringOf($value); } Console::writeLine(' ', $version, ' (', substr($s, 2), ')'); } Console::writeLine('}'); // List active releases for local queries if (!$remote) { foreach (new FilteredIOCollectionIterator($cwd, new NameMatchesFilter('#^\\.' . $module->vendor . '\\.' . $module->name . '.*\\.pth#')) as $found) { $r = new StringReader($found->getInputStream()); Console::writeLine('Selected: ', basename($found->getURI()), ', class path {'); while (null !== ($line = $r->readLine())) { $resolved = realpath($cwd->getURI() . ltrim($line, '!')); if (is_dir($resolved)) { $cl = \lang\FileSystemClassLoader::instanceFor($resolved, false); } else { if (is_file($resolved)) { $cl = \lang\archive\ArchiveClassLoader::instanceFor($resolved, false); } } Console::writeLine(' ', $cl); } Console::writeLine('}'); } return 0; } }
/** * Main * * @param string[] args */ public static function main(array $args) { if (sizeof($args) < 1 || '' == $args[0]) { Console::$err->writeLine('*** No class or package name given'); return 2; } // Check whether a file, class or a package directory or name is given $cl = \lang\ClassLoader::getDefault(); if (strstr($args[0], \xp::CLASS_FILE_EXT)) { $class = $cl->loadUri(realpath($args[0])); } else { if ($cl->providesClass($args[0])) { $class = XPClass::forName($args[0], $cl); } else { if (strcspn($args[0], '\\/') < strlen($args[0])) { $package = self::findPackageBy(new Folder($args[0])); } else { $package = $args[0]; } $provided = false; foreach (\lang\ClassLoader::getLoaders() as $loader) { if (!$loader->providesPackage($package)) { continue; } Console::writeLine('@', $loader); $provided = true; } if ($provided) { self::printPackage(\lang\reflect\Package::forName($package)); return 0; } // Not found Console::$err->writeLine('*** Failed to locate either a class or a package named "', $args[0], '", tried all of {'); foreach (\lang\ClassLoader::getLoaders() as $loader) { Console::$err->writeLine(' ', $loader); } Console::$err->writeLine('}'); return 1; } } Console::writeLine('@', $class->getClassLoader()); if ($class->isInterface()) { self::printInterface($class); } else { if ($class->isEnum()) { self::printEnum($class); } else { self::printClass($class); } } return 0; }
/** * Main method * * @param string[] args */ public static function main($args) { $sorted = ArrayList::newInstance($args)->sorted(); Console::writeLine('(new ArrayList([', implode(', ', $args), ']))->sorted()= ', $sorted); }
/** * Test initialization * * @param bool console * @param var assertions */ protected function initialize($console, $assertions) { $in = Console::$in; $out = Console::$out; $err = Console::$err; Console::initialize($console); try { $assertions(); } finally { Console::$in = $in; Console::$out = $out; Console::$err = $err; } }
/** * Fetches this origin into a given target folder * * @param io.Folder $target */ public function fetchInto(Folder $target) { $zip = $this->zipBallOf($this->url); $i = 0; with($iter = $zip->iterator()); $base = rtrim($iter->next()->getName() . '/', '/'); Console::write('Extracting (', $base, ') ['); while ($iter->hasNext()) { $entry = $iter->next(); $relative = str_replace($base, '', $entry->getName()); if ($entry->isDirectory()) { $folder = new Folder($target, $relative); $folder->exists() || $folder->create(0755); } else { $file = new File($target, $relative); $tran = new StreamTransfer($entry->getInputStream(), $file->getOutputStream()); $tran->transferAll(); $tran->close(); } $i++ % 10 || Console::write('.'); } $zip->close(); Console::writeLine(']'); }