Christopher Vagnetoft
1125ccb82d
* com.noccy.watcher: Initial inotify support * ScriptRunner now accepts an array of local vars for expansion when evaluating scripts
60 lines
1.7 KiB
PHP
60 lines
1.7 KiB
PHP
<?php // "name":"Watch files and act when they are changed", "author":"Noccy"
|
|
|
|
namespace SparkPlug\Com\Noccy\Watcher;
|
|
|
|
use Spark\Environment\ScriptRunner;
|
|
use SparkPlug\Com\Noccy\Watcher\Monitor\MonitorInterface;
|
|
use SparkPlug\Com\Noccy\Watcher\Monitor\MtimeMonitor;
|
|
use SparkPlug\Com\Noccy\Watcher\Monitor\InotifyMonitor;
|
|
|
|
class FileWatcher {
|
|
|
|
private MonitorInterface $monitor;
|
|
|
|
private ScriptRunner $scriptRunner;
|
|
|
|
private array $rules = [];
|
|
|
|
public function __construct()
|
|
{
|
|
if (extension_loaded('inotify') && !getenv("SPARK_NO_INOTIFY")) {
|
|
//$this->monitor = new MtimeMonitor();
|
|
printf("Enabling inotify support, watching directories\n");
|
|
$this->monitor = new InotifyMonitor();
|
|
} else {
|
|
printf("No inotify support, watching file mtimes\n");
|
|
$this->monitor = new MtimeMonitor();
|
|
}
|
|
$this->scriptRunner = get_environment()->getScriptRunner();
|
|
}
|
|
|
|
public function addRule(Rule $rule)
|
|
{
|
|
if ($rule->getInitialTrigger()) {
|
|
$this->triggerRule($rule);
|
|
}
|
|
$this->rules[] = $rule;
|
|
$this->monitor->add($rule);
|
|
}
|
|
|
|
private function triggerRule(Rule $rule)
|
|
{
|
|
$actions = $rule->getActions();
|
|
$locals = [
|
|
'WATCHER_RULE' => $rule->getName(),
|
|
'WATCHER_FILES' => join(" ",$rule->getWatchedFiles()),
|
|
];
|
|
$this->scriptRunner->evaluate($actions, $locals);
|
|
}
|
|
|
|
public function loop()
|
|
{
|
|
$this->monitor->loop();
|
|
$modified = $this->monitor->getModified();
|
|
foreach ($modified as $rule) {
|
|
$this->triggerRule($rule);
|
|
}
|
|
}
|
|
}
|
|
|