php-spark/src/DevMode/DevMode.php

99 lines
2.4 KiB
PHP

<?php
namespace Spark\DevMode;
use Spark\Environment\Environment;
class DevMode
{
private Environment $env;
public function __construct(Environment $environment)
{
$this->env = $environment;
}
public function run()
{
$script = $this->env->getScriptRunner();
$conf = $this->getConfig();
$title = $conf['title'];
if ($title) {
passthru('xtitle '.escapeshellarg("starting: ".$title));
}
$startup = $conf['startup'];
if ($startup) {
$script->evaluate($startup);
}
if ($title) {
passthru('xtitle '.escapeshellarg($title));
}
$shell = $conf['shell'];
if (!$shell) {
$this->runDefaultShell();
} else {
passthru("exec ".$shell);
}
if ($title) {
passthru('xtitle '.escapeshellarg("stopping: ".$title));
}
$shutdown = $conf['shutdown'];
if ($shutdown) {
$script->evaluate($shutdown);
}
if ($title) {
passthru('xtitle');
}
}
private function runDefaultShell()
{
$init = $this->env->getProjectDirectory() . "/.devmoderc~";
$initrc = [
//"source \$HOME/.bashrc",
"test -f .spark/devmode.rc && source .spark/devmode.rc",
];
foreach ($_ENV as $e=>$v) {
$initrc[] = sprintf("export %s=%s", $e, escapeshellarg($v));
}
$proj = basename($this->env->getProjectDirectory());
$initrc[] = "function _dev_prompt {";
$initrc[] = " export PS1=\"\[\e[44;3m\] \[\e[1m\]dev\[\e[22;23m\] \[\e[36m\]{$proj}\[\e[39m\] \[\e[49m\] \w \$ \"";
$initrc[] = "}";
$initrc[] = "export PROMPT_COMMAND=_dev_prompt";
file_put_contents($init, join("\n", $initrc));
$cmdl = "exec bash --rcfile ".escapeshellarg($init);
passthru($cmdl);
unlink($init);
}
private function getConfig(): array
{
$defaults = [
'title'=> null,
'triggers' => [],
'startup' => null,
'shutdown' => null,
'shell' => null,
];
$conf = $this->env->readConfig("devmode.json");
if (!isset($conf['devmode'])) {
fprintf(STDERR, "Warning: Invalid devmode.json file\n");
return $defaults;
}
return array_merge($defaults, $conf['devmode']);
}
}