innmind/file-watch

Library to execute code when a file changes

4.0.0 2024-03-10 10:42 UTC

This package is auto-updated.

Last update: 2024-04-10 10:48:51 UTC


README

Build Status codecov Type Coverage

Small tool to execute code every time a file (or folder) is modified.

Installation

composer require innmind/file-watch

Usage

use Innmind\FileWatch\{
    Factory,
    Stop,
};
use Innmind\Server\Control\ServerFactory;
use Innmind\TimeWarp\Halt\Usleep;
use Innmind\TimeContinuum\Earth\Clock;
use Innmind\Stream\Streams;
use Innmind\Url\Path;
use Innmind\Immutable\Either;

$watch = Factory::build(
    ServerFactory::build(
        new Clock,
        Streams::fromAmbientAuthority(),
        new Usleep,
    )->processes(),
    new Usleep,
);

$count = $watch(Path::of('/to/some/file/or/folder'))(0, function(int $count, Continuation $continuation): Continuation {
    // this function is called every time the file is modified
    ++$count;

    if ($count === 42) {
        // This will stop watching the folder for changes and return the count
        return $continuation->stop($count);
    }

    // This will instruct to continue watching for changes and the value will be
    // passed to this callable the next time it's called
    return $continuation->continue($count);
})->match(
    static fn(int $count) => $count, // always 42 as it's the stopping value
    static fn() => throw new \RuntimeException('Failed to watch for changes'),
);

Warning

The function may be called multiple times for an single change due to the way tail and stat works.