/** * Returns a function to use for listing * * @return function(string): string[] */ protected function entries() { return function ($package) { if ('' === $package) { $folder = $this->base; $prefix = ''; } else { $folder = new Folder($this->base, strtr($package, '/', DIRECTORY_SEPARATOR)); $prefix = $package . '/'; } $r = []; foreach ($folder->entries() as $entry) { $name = $entry->name(); if (is_dir($entry)) { $r[] = $prefix . $name . '/'; } else { foreach ($this->extensions as $extension) { $offset = -strlen($extension); if (0 === substr_compare($name, $extension, $offset)) { $r[] = $prefix . substr($name, 0, $offset); } } } } return $r; }; }
/** * Constructor * * @param io.Folder folder * @throws lang.IllegalArgumentException if the given folder does not exist */ public function __construct(Folder $folder) { if (!$folder->exists()) { throw new IllegalArgumentException('Folder "' . $folder->getURI() . '" does not exist!'); } $this->folder = $folder; }
public static function cleanupSessionSavePath() { $f = new Folder(session_save_path()); while ($e = $f->getEntry()) { if (0 === strncmp('sess_', $e, 5)) { unlink($f->getURI() . $e); } } }
public static function createFiles() { self::$temp = new Folder(System::tempDir(), uniqid(microtime(true))); self::$temp->create(); $partials = new Folder(self::$temp, 'partials'); $partials->create(); FileUtil::setContents(new File(self::$temp, 'test.mustache'), 'Mustache template {{id}}'); FileUtil::setContents(new File($partials, 'navigation.mustache'), '{{#if nav}}nav{{/if}}'); }
/** * Constructor * * @param io.Folder $folder * @throws lang.IllegalArgumentException if the given folder does not exist or isn't in class path */ public function __construct(Folder $folder) { $path = $folder->getURI(); foreach (ClassLoader::getLoaders() as $cl) { if ($cl instanceof FileSystemClassLoader && 0 === strncmp($cl->path, $path, strlen($cl->path))) { $this->loader = $cl; return; } } throw new IllegalArgumentException($folder->toString() . ($folder->exists() ? ' is not in class path' : ' does not exist')); }
/** * Gets base folder * * @param io.Folder */ public function setBase(Folder $base) { $this->base = new Folder($base, '..'); // Scan base path. FIXME: Refactor this to use lang.ClassLoader // instead of duplication its sourcecode here foreach (array_filter(explode(PATH_SEPARATOR, scanpath(array($base->getURI()), getenv('HOME')))) as $element) { $resolved = realpath($element); if (is_dir($resolved)) { $this->cl[] = \lang\FileSystemClassLoader::instanceFor($resolved, false); } else { if (is_file($resolved)) { $this->cl[] = \lang\archive\ArchiveClassLoader::instanceFor($resolved, false); } } } }
/** * Removes a given module version * * @param io.Folder $cwd The working directory * @param io.collections.FileCollection $version The version * @return bool whether the module was active */ protected function remove($cwd, FileCollection $version) { $versioned = basename($version->getURI()); $vendor = basename($version->getOrigin()->getURI()); Console::writeLine('Removing ', $vendor, '/', $versioned, ' -> ', $version); // Remove corresponding .pth file $pth = new File($cwd, '.' . $vendor . '.' . $versioned . '.pth'); if ($pth->exists()) { $active = true; $pth->unlink(); } else { $active = false; } // Remove folder $fld = new Folder($version->getURI()); $fld->unlink(); return $active; }
/** * Execute action * * @return int */ public function perform() { $this->archive->open(Archive::READ); $args = $this->getArguments(); while ($entry = $this->archive->getEntry()) { if (!$this->_filter($entry, $args)) { continue; } $f = new File($entry); $data = $this->archive->extract($entry); if (!($this->options & Options::SIMULATE)) { // Create folder on demand. Note that inside a XAR, the directory // separator is *ALWAYS* a forward slash, so we need to change // it to whatever the OS we're currently running on uses. $dir = new Folder(str_replace('/', DIRECTORY_SEPARATOR, dirname($entry))); if (!$dir->exists()) { $dir->create(); } FileUtil::setContents($f, $data); } $this->options & Options::VERBOSE && $this->out->writeLinef('%10s %s', number_format(strlen($data), 0, false, '.'), $entry); } $this->archive->close(); }
public function rooted_folder() { $rooted = new Folder('/rooted'); $this->assertEquals(substr($rooted->getURI(), 0, -1), (new Path($rooted))->toString()); }
/** * Entry point method * * @param string[] args */ public static function main(array $args) { if (empty($args)) { return self::usage(); } 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]) { return self::usage(); } 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]) { $dir = $args[++$i]; $manager->addSourcePath($dir); $files = array_merge($files, self::fromFolder($dir, false)); } else { if (is_dir($args[$i])) { $dir = $args[$i]; $manager->addSourcePath($dir); $files = array_merge($files, self::fromFolder($dir, true)); } 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('.'); if (null === $version) { // No version given: Search for newest version. $releases = $this->installedReleasesOf($cwd, $module); if (empty($releases)) { Console::$err->writeLine('*** Cannot find installed module ', $module); return 3; } uksort($releases, function ($a, $b) { return version_compare($a, $b, '<'); }); $version = key($releases); $installed = $releases[$version]; Console::writeLine('Using newest installed version ', $version, ' -> ', $installed); } else { // Version given, select this for upgrading. $folder = new Folder($cwd, $module->vendor, $module->name . '@' . $version); if (!$folder->exists()) { Console::$err->writeLine('*** Cannot find installed module ', $module, ' in version ', $version); return 3; } $installed = new FileCollection($folder); Console::writeLine('Using specified version ', $version, ' -> ', $installed); } if (isset($args[1])) { // Target version given, check it exists $request = create(new RestRequest('/vendors/{vendor}/modules/{module}/releases/{release}'))->withSegment('vendor', $module->vendor)->withSegment('module', $module->name)->withSegment('release', $args[1]); try { $release = $this->api->execute($request)->data(); } catch (RestException $e) { Console::$err->writeLine('*** Cannot find module ', $module, '@', $args[1], ': ', $e->getMessage()); return 3; } $target = $release['version']['number']; if (version_compare($version, $target, '>')) { Console::writeLine('>> Local ', $version, ' newer than ', $target, ', doing a downgrade'); } else { if (version_compare($version, $target, '=')) { Console::writeLine('>> Local ', $version, ' same as ', $target, ', performing reinstall'); } else { Console::writeLine('>> Local ', $version, ' older than ', $target, ', upgrading'); } } } else { // No target version given: Check for module online, and upgrade to newest $request = create(new RestRequest('/vendors/{vendor}/modules/{module}/releases'))->withSegment('vendor', $module->vendor)->withSegment('module', $module->name); try { $releases = $this->api->execute($request)->data(); usort($releases, function ($a, $b) { return version_compare($a['version']['number'], $b['version']['number'], '<'); }); } catch (RestException $e) { Console::$err->writeLine('*** Cannot find module ', $module, ': ', $e->getMessage()); return 3; } // Verify we actually need an upgrade $target = $releases[0]['version']['number']; if (version_compare($version, $target, '>=')) { Console::writeLine('*** Already at newest version, no upgrade required: ', $releases[0]); return 1; } Console::writeLine('>> Upgrading to ', $target); } // Remove old one first, then add newer version $args = array($module->vendor . '/' . $module->name . '@' . $version); $r = $this->spawn(new RemoveAction())->perform($args); if (0 !== $r) { return $r; } $args = array($module->vendor . '/' . $module->name . '@' . $target); $r = $this->spawn(new AddAction())->perform($args); if (0 !== $r) { return $r; } return 0; }
public function parentDirectory() { $f = new Folder('..'); $this->assertEquals($this->normalize(realpath('..')), $f->getURI()); }
/** * 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(']'); }
/** * Gets the count of messages with speciefied attribute * or all messages when no attribute was specified * * @param peer.mail.Mailfolder f * @param int attr default 0xFFFF * @return int count */ public function getMessageCount($f, $attr = 0xffff) { $this->openFolder($f); $f = new Folder($f->name . DIRECTORY_SEPARATOR . 'cur'); if (!$f->exists()) { return 0; } $cnt = 0; $f->open(); while ($e = $f->getEntry()) { if ($attr & $this->_getMailFlags($e)) { $cnt++; } } $f->close(); return $cnt; }
/** * Perform this action * * @param string[] args */ public function perform(array $args) { with($target = new Folder($args[1])); $target->exists() || $target->create(); $this->extract(self::BASE_URL, $args[0], $target); }
public function pathClassCanBeUsedAsArg() { $f = new Folder(new Path($this->temp)); $this->assertEquals($this->temp, $f->getURI()); }
/** * 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; }
/** * Write compilation result to a given target * * @param xp.compiler.emit.EmitterResult r * @param io.File target * @throws io.IOException */ public function write($r, File $target) { $folder = new Folder($target->getPath()); $folder->exists() || $folder->create(); $r->writeTo(new \io\streams\FileOutputStream($target)); }