Skip to content

Instantly share code, notes, and snippets.

@thekid
Created September 22, 2013 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thekid/6657999 to your computer and use it in GitHub Desktop.
Save thekid/6657999 to your computer and use it in GitHub Desktop.
Script it! for XP Framework - inspired by http://scala-lang.org/documentation/getting-started.html#script_it
#!/bin/sh
exec xp xp.runtime.Sh "$0" "$@"
<?php
class HelloWorld extends \lang\Object {
public static function main($args) {
Console::writeLine("Hello, world!");
}
}
<?php namespace xp\runtime;
/**
* Runs classes embedded in shell scripts
*
* Example:
*
* ```sh
* #!/bin/sh
* exec xp xp.runtime.Sh "$0" "$@"
* <?php
* class HelloWorld extends \lang\Object {
* public static function main($args) {
* Console::writeLine("Hello, world!");
* }
* }
* ```
*/
class Sh extends \lang\Object {
/**
* Main
*
* @param string[] args
*/
public static function main(array $args) {
// Parse file
$f= new \io\File(array_shift($args));
$f->open(FILE_MODE_READ);
$src= false;
$bytes= '';
$class= null;
while (!$f->eof()) {
$l= $f->readLine();
if ($src) {
if (0 === strncmp('class', $l, 5)) {
$class= substr($l, 6, strpos($l, ' ', 6) - 6);
}
$bytes.= $l;
} else if (0 === strncmp('<?php', $l, 5)) {
$src= true;
}
}
$f->close();
// Verify
if (null === $class) {
throw new \lang\ClassFormatException(sprintf(
'No %s found in %s',
$src ? 'class declaration' : 'source start',
$f->getURI()
));
}
// Execute
with ($cl= \lang\DynamicClassLoader::instanceFor($args[0])); {
$cl->setClassBytes($class, $bytes);
return $cl->loadClass($class)->getMethod('main')->invoke(null, $args);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment