Created
September 22, 2013 08:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
exec xp xp.runtime.Sh "$0" "$@" | |
<?php | |
class HelloWorld extends \lang\Object { | |
public static function main($args) { | |
Console::writeLine("Hello, world!"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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