Taskadvanced
Watch a file for changes
Also called file watcher, detect file changes, poll a file, inotify, FSEvents, kqueue, ReadDirectoryChangesW, WatchService, FileSystemWatcher, fs.watch, hot reload.
Tell when a file is created, changed or deleted, by polling its size and modification time or by an event API of the operating system, and act once for each burst of changes.
- Evidence
- Code in 10 languages
Task
Tell when a file changes, so that a program can read it again. A server reads its configuration again after an edit, a build tool builds again after a save, and a log reader shows the new lines. The entry is a watcher of one path. Each poll of the watcher returns created, modified, deleted or none, for the time since the last poll.
The solutions poll. A watcher keeps the signature of the file: its size and its modification time (mtime). A poll takes a new signature with stat and compares the two. Linux says that the mtime "is changed by file modifications, for example, by mknod(2) , truncate(2) , utime(2) , and write(2) (of more than zero bytes)."2 A change to the content changes the mtime, so a poll sees it. A change of the owner or the mode does not: "The mtime timestamp is not changed for changes in owner, group, hard link count, or mode."2
A watch loop calls the poll at an interval. A save often makes many changes in a short time, so the loop waits until the file is quiet for some time, and then calls its function once. A missing file is not an error: the watcher reports created when it comes. Report an error when the path is a directory. SQL, regular expressions, HTML and CSS do not apply, because they do not read files.
Solutions
Each solution has a FileWatcher with poll, and a watch loop that calls a function once for each burst of changes. The operating systems also have event APIs, which tell a program about a change when it occurs:
- Linux: inotify. A program adds a watch for a file or a directory, and reads events such as
IN_MODIFY("File was modified (e.g., write(2) , truncate(2) )"1) andIN_CLOSE_WRITE("File opened for writing was closed"1). Node.jsfs.watchuses it on Linux9. - BSD and macOS: kqueue. The filter
EVFILT_VNODE"Takes a file descriptor as the identifier and the events to watch for in fflags"3, such asNOTE_WRITE,NOTE_DELETEandNOTE_RENAME3. The program must keep the file open. - macOS: FSEvents. It watches a directory tree. It "coalesces multiple notifications on a given directory if they occur in a short period of time. You will always receive at least one notification after the last change is made."4
- Windows: ReadDirectoryChangesW. It watches a directory and fills a buffer with the changes5.
The languages:
- Python. The standard library has no watcher.
os.statgivesst_sizeandst_mtime_ns, the "Time of most recent content modification expressed in nanoseconds as an integer."10 Usest_mtime_ns, not the floatst_mtime: Python says that the float "cannot preserve all of it, and as such will be slightly inexact."10 - JavaScript and TypeScript (Node.js).
fs.statSync(path, { bigint: true })givesmtimeNs. Node.js also hasfs.watch: "On Linux systems, this uses inotify(7) . On BSD systems, this uses kqueue(2) . On macOS, this uses kqueue(2) for files and FSEvents for directories."9 Andfs.watchFilepolls: an option tells "how often the target should be polled in milliseconds"9, and its defaultintervalis 50079. - Java.
Files.readAttributesgivessize()andlastModifiedTime().WatchServicewatches a directory. It uses "the native file event notification facility where available, or to use a primitive mechanism, such as polling, when a native facility is not available."7 - C#.
FileInfo.LengthandFileInfo.LastWriteTimeUtc.FileSystemWatcherraises events for a directory8. - Go.
os.Stat"returns a FileInfo describing the named file"11, withSize()andModTime(). Compare times withEqual, not==. The standard library has no watcher. - Rust.
fs::metadata(path)?.modified(). The value "corresponds to the mtime field of stat on Unix platforms and the ftLastWriteTime field on Windows platforms."12 It can fail: "This field might not be available on all platforms"12. The standard library has no watcher. - C.
statgivesst_sizeandst_mtim, astruct timespecwith nanoseconds6. On macOS the field isst_mtimespec. For events, use inotify on Linux and kqueue on BSD and macOS. - C++.
std::filesystem::file_sizeandstd::filesystem::last_write_time. The standard library has no watcher. - Bash.
stat -c '%s %Y'with GNU, andstat -f '%z %m'with macOS and BSD. These give the mtime in whole seconds (see Pitfalls).
In Python, a watcher is a few lines. The example writes, appends and deletes a file, and polls after each change:
import os
import tempfile
class FileWatcher:
def __init__(self, path):
self.path = path
self.last = self.signature()
def signature(self):
try:
st = os.stat(self.path)
except FileNotFoundError:
return None
return (st.st_size, st.st_mtime_ns)
def poll(self):
now = self.signature()
before, self.last = self.last, now
if before is None and now is None:
return "none"
if before is None:
return "created"
if now is None:
return "deleted"
return "modified" if now != before else "none"
os.chdir(tempfile.mkdtemp())
watcher = FileWatcher("app.conf")
print("start:", watcher.poll())
with open("app.conf", "w") as f:
f.write("port = 8080\n")
print("after the write:", watcher.poll())
print("no change:", watcher.poll())
with open("app.conf", "a") as f:
f.write("debug = true\n")
print("after the append:", watcher.poll())
os.remove("app.conf")
print("after the delete:", watcher.poll())
start: none
after the write: created
no change: none
after the append: modified
after the delete: deleted
In Go, a watcher of the path sees a save that renames a new file onto the old name, also when the size stays the same:
package main
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"time"
)
type signature struct {
size int64
mtime time.Time
}
// stat gives the signature of the file, or ok false when it does not exist.
func stat(path string) (sig signature, ok bool) {
info, err := os.Stat(path)
if errors.Is(err, fs.ErrNotExist) {
return signature{}, false
}
if err != nil {
panic(err)
}
return signature{info.Size(), info.ModTime()}, true
}
func main() {
work, err := os.MkdirTemp("", "watch-")
if err != nil {
panic(err)
}
defer os.RemoveAll(work)
path := filepath.Join(work, "app.conf")
os.WriteFile(path, []byte("port = 8080\n"), 0o644)
old := time.Now().Add(-time.Hour)
os.Chtimes(path, old, old)
before, _ := stat(path)
// An editor saves: it writes a new file, then renames it onto the old name.
os.WriteFile(path+".tmp", []byte("port = 9090\n"), 0o644)
os.Rename(path+".tmp", path)
after, ok := stat(path)
fmt.Println("the file exists:", ok)
fmt.Println("same size:", after.size == before.size)
fmt.Println("modified:", after.size != before.size || !after.mtime.Equal(before.mtime))
}
the file exists: true
same size: true
modified: true
The watch loop of the solutions keeps the time of the last change that it did not report. When a poll sees no change and that time is older than the quiet time, the loop calls its function and clears the time. Five writes 20 ms apart, with a quiet time of 500 ms, give one call.
Edge cases
The cases are in cases/basic.jsonl, cases/edge.jsonl and cases/errors.jsonl. Each test runs in a new, empty directory, and the file is watched.txt. After each step except none, the entry sets the mtime of the file to a new second. So the cases do not depend on the clock of the file system.
create,create-then-write,create-then-deleteandappend: the usual changes.no-change: a poll with no change in between givesnone, also two times.same-size:abcbecomesxyz. The size is the same, but the mtime changes, so the poll givesmodified.touch-only: only the mtime changes. The poll givesmodified, because the watcher cannot see the content.replace-by-rename: a new file goes onto the name, as Write a file atomically does. A watcher of the path sees a modified file, not a delete and a create.delete-and-create: the file goes away and comes back between two polls. The poll givesmodified: a poll sees only the state at its time, not the steps in between.never-created: no file, no change.- Errors: when
watched.txtis a directory at a poll, the solution gives is-a-directory.
The native tests also check that a change that keeps the size and the mtime is not seen, and that the watch loop calls its function once for a burst of writes.
Pitfalls
- The clock resolution of the mtime. Two saves in the same tick of the clock give the same mtime. Python says: "on Windows systems using the FAT32 file systems, st_mtime has 2-second resolution"10. Linux says: "Nanosecond timestamps are not supported in ext2, ext3, and Reiserfs."2 POSIX lets an implementation keep only the resolution of the file system: "if the file system resolution is 1 microsecond, then a conforming stat () must always return an st_mtim.tv_nsec that is a multiple of 1000."6 A watcher that keeps the mtime in whole seconds does not see a second save of the same size in the same second:
This code runs but gives a wrong answer on purpose.
import os
import tempfile
os.chdir(tempfile.mkdtemp())
def signature(path):
st = os.stat(path)
return (st.st_size, int(st.st_mtime)) # the mtime in whole seconds
second = 1_700_000_000 * 1_000_000_000
with open("app.conf", "w") as f:
f.write("port = 8080\n")
os.utime("app.conf", ns=(second + 100_000_000, second + 100_000_000))
before = signature("app.conf")
# A second save, 0.5 s later, with a value of the same length.
with open("app.conf", "w") as f:
f.write("port = 9090\n")
os.utime("app.conf", ns=(second + 600_000_000, second + 600_000_000))
print("changed:", signature("app.conf") != before)
print("with st_mtime_ns it is seen:", os.stat("app.conf").st_mtime_ns != second + 100_000_000)
changed: False
with st_mtime_ns it is seen: True
Keep the mtime with all its digits, and also the size. When a change must not be lost, also compare a hash of the content, or read the file again after each event.
- A change is not the end of a save. A watcher can see a file in the middle of a write. Java says: "When an event is reported to indicate that a file in a watched directory has been modified then there is no guarantee that the program (or programs) that have modified the file have completed."7 Wait until the file is quiet, and read it then. A writer that renames a full file onto the name (see Write a file atomically) gives the reader no half file.
- One save gives many events. .NET says: "Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised."8 Java says that a change "may result in a single ENTRY_MODIFY event in some implementations but several events in other implementations."7 inotify joins identical events that are not yet read, so "an application can't use inotify to reliably count file events."1 Do not count events. Treat an event as a sign to look at the file again.
- A watch of a file follows the inode, not the name. "Inotify monitoring is inode-based"1. Node.js says that
fs.watch"resolves the path to an inode and watches the inode. If the watched path is deleted and recreated, it is assigned a new inode. The watch will emit an event for the delete but will continue watching the original inode. Events for the new inode will not be emitted."9 A program that saves with a rename makes a new inode, so a watch of the file stops after the first save. Watch the directory that holds the file, and filter by name, or add the watch again after a delete or a rename. - Event queues can overflow. In inotify, "Events in excess of this limit are dropped, but an IN_Q_OVERFLOW event is always generated."1 "The JDK's WatchService implementations buffer up to 512 pending events for each registered watchable object."7 On Windows,
ReadDirectoryChangesW"fails with ERROR_NOTIFY_ENUM_DIR when the system was unable to record all the changes to the directory. In this case, you should compute the changes by enumerating the directory or subtree."5 After an overflow, scan the directory again, as a poller does. - Network file systems and polls that are too slow. inotify does "not catch remote events that occur on network filesystems. (Applications must fall back to polling the filesystem to catch such events.)"1 Java says that "it is not required that changes to files carried out on remote systems be detected."7 A poller works there, but it misses a short life: "Short-lived files (meaning files that are deleted very quickly after they are created) may not be detected by primitive implementations that periodically poll the file system to detect changes."7 The
delete-and-createcase shows the same limit. - A watch of a directory is not recursive. In inotify, "to monitor subdirectories under a directory, additional watches must be created. This can take a significant amount time for large directory trees."1 Each watch also counts against a limit for each user (
/proc/sys/fs/inotify/max_user_watches)1. - The name in an event can be old. inotify says that "by the time an application processes an inotify event, the filename may already have been deleted or renamed."1 Node.js says that the file name argument "is not always guaranteed to be provided"9. Look at the file again after an event, and accept that it is gone.
Related tasks
- Get the modification time of a file
- Get the size of a file
- File metadata
- Write a file atomically
- Read a file line by line
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/watch-a-file-for-changes/.
"""Watch a file for changes: poll its size and modification time."""
import errno
import os
import stat
import time
BASE_MTIME = 1_700_000_000 # seconds; the cases set the mtime to BASE_MTIME + step
def signature(path):
"""Return (size, mtime in ns) of the file at path, or None when it does not exist."""
try:
st = os.stat(path)
except FileNotFoundError:
return None
if stat.S_ISDIR(st.st_mode):
raise IsADirectoryError(errno.EISDIR, os.strerror(errno.EISDIR), os.fspath(path))
return (st.st_size, st.st_mtime_ns)
class FileWatcher:
"""Remembers the last signature of a file and tells what changed since then."""
def __init__(self, path):
self.path = path
self.last = signature(path)
def poll(self):
"""Return created, deleted, modified or none, for the time since the last poll."""
now = signature(self.path)
before, self.last = self.last, now
if before is None and now is None:
return "none"
if before is None:
return "created"
if now is None:
return "deleted"
return "modified" if now != before else "none"
def watch(path, on_change, interval=0.5, quiet=0.2, stop=lambda: False):
"""Call on_change(path) once for each burst of changes, after the file is quiet."""
watcher = FileWatcher(path)
pending = None # the time of the last change that on_change has not seen
while not stop():
if watcher.poll() != "none":
pending = time.monotonic()
elif pending is not None and time.monotonic() - pending >= quiet:
pending = None
on_change(path)
time.sleep(interval)
def apply_step(path, step, number):
"""Make the change of one step of a case (the entry of the cases uses it)."""
kind, _, text = step.partition(":")
if kind in ("create", "write"):
with open(path, "w", encoding="utf-8", newline="") as f:
f.write(text)
elif kind == "append":
with open(path, "a", encoding="utf-8", newline="") as f:
f.write(text)
elif kind == "replace":
tmp = f"{path}.tmp"
with open(tmp, "w", encoding="utf-8", newline="") as f:
f.write(text)
os.replace(tmp, path)
elif kind == "recreate":
os.remove(path)
with open(path, "w", encoding="utf-8", newline="") as f:
f.write(text)
elif kind == "delete":
os.remove(path)
elif kind == "mkdir":
os.mkdir(path)
elif kind not in ("touch", "none"):
raise ValueError(f"unknown step {step!r}")
if kind != "none" and os.path.isfile(path):
t = (BASE_MTIME + number) * 1_000_000_000
os.utime(path, ns=(t, t))
def watch_changes(path, steps):
"""The entry of the cases: poll after each step and return the results."""
watcher = FileWatcher(path)
results = []
for number, step in enumerate(steps, start=1):
apply_step(path, step, number)
results.append(watcher.poll())
return results
test_watch_file.py 72 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/watch-a-file-for-changes/.
import os
import threading
import time
from pathlib import Path
import pytest
import watch_file as wf
CASES = {
"create": (["create:hello\n"], ["created"]),
"create-then-write": (["create:a\n", "write:a much longer line\n"], ["created", "modified"]),
"create-then-delete": (["create:a\n", "delete"], ["created", "deleted"]),
"append": (["create:a\n", "append:b\n", "append:c\n"], ["created", "modified", "modified"]),
"no-change": (["create:a\n", "none", "none"], ["created", "none", "none"]),
"same-size": (["create:abc\n", "write:xyz\n"], ["created", "modified"]),
"touch-only": (["create:a\n", "touch"], ["created", "modified"]),
"replace-by-rename": (["create:old\n", "replace:new\n"], ["created", "modified"]),
"delete-and-create": (["create:a\n", "recreate:b\n"], ["created", "modified"]),
"never-created": (["none"], ["none"]),
}
@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, name: str) -> None:
monkeypatch.chdir(tmp_path)
steps, expect = CASES[name]
assert wf.watch_changes("watched.txt", steps) == expect
def test_directory_is_an_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.chdir(tmp_path)
with pytest.raises(IsADirectoryError):
wf.watch_changes("watched.txt", ["mkdir"])
def test_size_and_time_together(tmp_path: Path) -> None:
path = tmp_path / "watched.txt"
path.write_text("abc\n")
os.utime(path, ns=(5_000_000_000, 5_000_000_000))
watcher = wf.FileWatcher(path)
# The same size and the same mtime: a poll cannot see the change.
path.write_text("xyz\n")
os.utime(path, ns=(5_000_000_000, 5_000_000_000))
assert watcher.poll() == "none"
path.write_text("xyz!\n")
assert watcher.poll() == "modified"
def test_watch_calls_once_for_a_burst(tmp_path: Path) -> None:
path = tmp_path / "watched.txt"
calls = []
done = threading.Event()
t = threading.Thread(
target=wf.watch,
args=(path, calls.append),
kwargs={"interval": 0.01, "quiet": 0.5, "stop": done.is_set},
)
t.start()
for i in range(5):
path.write_text("x" * (i + 1))
time.sleep(0.02)
deadline = time.monotonic() + 5
while not calls and time.monotonic() < deadline:
time.sleep(0.01)
time.sleep(0.6)
done.set()
t.join()
assert calls == [path]
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
#include "watch_file.hpp"
#include <fstream>
#include <thread>
namespace fs = std::filesystem;
namespace files {
namespace {
// The signature of the file, or nothing when it does not exist.
std::optional<Signature> signature(const fs::path& path, std::error_code& ec) {
fs::file_status st = fs::status(path, ec);
if (ec || !fs::exists(st)) {
if (st.type() == fs::file_type::not_found) ec.clear();
return std::nullopt;
}
if (fs::is_directory(st)) {
ec = std::make_error_code(std::errc::is_a_directory);
return std::nullopt;
}
Signature sig{fs::file_size(path, ec), {}};
if (ec) return std::nullopt;
sig.mtime = fs::last_write_time(path, ec);
if (ec) return std::nullopt;
return sig;
}
bool put(const fs::path& path, const std::string& text, std::ios::openmode mode) {
std::ofstream out(path, std::ios::binary | mode);
out << text;
out.close();
return static_cast<bool>(out);
}
// Makes the change of one step of a case (the entry of the cases uses it).
void apply_step(const fs::path& path, const std::string& step, std::int64_t number, std::error_code& ec) {
auto colon = step.find(':');
std::string kind = step.substr(0, colon);
std::string text = colon == std::string::npos ? "" : step.substr(colon + 1);
bool ok = true;
if (kind == "create" || kind == "write") {
ok = put(path, text, std::ios::trunc);
} else if (kind == "append") {
ok = fs::exists(path, ec) && put(path, text, std::ios::app);
} else if (kind == "replace") {
fs::path tmp = path;
tmp += ".tmp";
ok = put(tmp, text, std::ios::trunc);
if (ok) fs::rename(tmp, path, ec);
} else if (kind == "recreate") {
if (fs::remove(path, ec)) ok = put(path, text, std::ios::trunc);
} else if (kind == "delete") {
if (!fs::remove(path, ec) && !ec) ec = std::make_error_code(std::errc::no_such_file_or_directory);
} else if (kind == "mkdir") {
fs::create_directory(path, ec);
} else if (kind != "touch" && kind != "none") {
ec = std::make_error_code(std::errc::invalid_argument);
}
if (!ok && !ec) ec = std::make_error_code(std::errc::io_error);
if (ec) return;
std::error_code ignore;
if (kind != "none" && fs::is_regular_file(path, ignore)) {
// The clock of file_time_type has no fixed epoch, so the time goes
// through the system clock.
auto sys = std::chrono::system_clock::time_point{std::chrono::seconds{base_mtime + number}};
auto t = fs::file_time_type::clock::from_sys(sys);
fs::last_write_time(path, t, ec);
}
}
} // namespace
FileWatcher::FileWatcher(fs::path path, std::error_code& ec) : path_(std::move(path)), last_(signature(path_, ec)) {}
std::string FileWatcher::poll(std::error_code& ec) {
std::optional<Signature> now = signature(path_, ec);
if (ec) return "";
std::optional<Signature> before = last_;
last_ = now;
if (!before && !now) return "none";
if (!before) return "created";
if (!now) return "deleted";
return *before == *now ? "none" : "modified";
}
void watch(const fs::path& path, const std::function<void(const fs::path&)>& on_change,
std::chrono::milliseconds interval, std::chrono::milliseconds quiet, const std::function<bool()>& stop,
std::error_code& ec) {
FileWatcher watcher(path, ec);
if (ec) return;
std::optional<std::chrono::steady_clock::time_point> pending; // a change that on_change has not seen
while (!stop()) {
std::string change = watcher.poll(ec);
if (ec) return;
auto now = std::chrono::steady_clock::now();
if (change != "none") {
pending = now;
} else if (pending && now - *pending >= quiet) {
pending.reset();
on_change(path);
}
std::this_thread::sleep_for(interval);
}
}
std::vector<std::string> watch_changes(const fs::path& path, const std::vector<std::string>& steps,
std::error_code& ec) {
std::vector<std::string> results;
FileWatcher watcher(path, ec);
if (ec) return {};
for (std::size_t i = 0; i < steps.size(); ++i) {
apply_step(path, steps[i], static_cast<std::int64_t>(i) + 1, ec);
if (ec) return {};
results.push_back(watcher.poll(ec));
if (ec) return {};
}
return results;
}
} // namespace files
watch_file.hpp 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
#pragma once
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <optional>
#include <string>
#include <system_error>
#include <vector>
namespace files {
// The cases set the mtime to base_mtime + step, in seconds.
inline constexpr std::int64_t base_mtime = 1'700'000'000;
// The size and the mtime of a file.
struct Signature {
std::uintmax_t size;
std::filesystem::file_time_type mtime;
bool operator==(const Signature&) const = default;
};
// Remembers the last signature of a file and tells what changed since then.
class FileWatcher {
public:
// Takes the first signature; ec is set for a directory or an error of stat.
FileWatcher(std::filesystem::path path, std::error_code& ec);
// created, deleted, modified or none, for the time since the last poll.
std::string poll(std::error_code& ec);
private:
std::filesystem::path path_;
std::optional<Signature> last_;
};
// Calls on_change once for each burst of changes, after the file is quiet,
// until stop returns true.
void watch(const std::filesystem::path& path, const std::function<void(const std::filesystem::path&)>& on_change,
std::chrono::milliseconds interval, std::chrono::milliseconds quiet, const std::function<bool()>& stop,
std::error_code& ec);
// The entry of the cases: applies each step, polls after each, and returns the results.
std::vector<std::string> watch_changes(const std::filesystem::path& path, const std::vector<std::string>& steps,
std::error_code& ec);
} // namespace files
test_watch_file.cpp 119 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
#include <atomic>
#include <chrono>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <mutex>
#include <string>
#include <system_error>
#include <thread>
#include <vector>
#include "watch_file.hpp"
namespace fs = std::filesystem;
using namespace std::chrono_literals;
namespace {
const fs::path dir = "watch_tree";
const fs::path path = dir / "watched.txt";
int failures = 0;
void expect(bool ok, const std::string& what) {
if (!ok) {
std::fprintf(stderr, "%s\n", what.c_str());
++failures;
}
}
void fresh() {
fs::remove_all(dir);
fs::create_directory(dir);
}
struct Case {
std::string name;
std::vector<std::string> steps;
std::vector<std::string> expect;
};
void write_with_mtime(const std::string& text, fs::file_time_type t) {
std::ofstream(path, std::ios::binary) << text;
fs::last_write_time(path, t);
}
} // namespace
int main() {
const std::vector<Case> cases = {
{"create", {"create:hello\n"}, {"created"}},
{"create-then-write", {"create:a\n", "write:a much longer line\n"}, {"created", "modified"}},
{"create-then-delete", {"create:a\n", "delete"}, {"created", "deleted"}},
{"append", {"create:a\n", "append:b\n", "append:c\n"}, {"created", "modified", "modified"}},
{"no-change", {"create:a\n", "none", "none"}, {"created", "none", "none"}},
{"same-size", {"create:abc\n", "write:xyz\n"}, {"created", "modified"}},
{"touch-only", {"create:a\n", "touch"}, {"created", "modified"}},
{"replace-by-rename", {"create:old\n", "replace:new\n"}, {"created", "modified"}},
{"delete-and-create", {"create:a\n", "recreate:b\n"}, {"created", "modified"}},
{"never-created", {"none"}, {"none"}},
};
for (const auto& c : cases) {
fresh();
std::error_code ec;
auto got = files::watch_changes(path, c.steps, ec);
expect(!ec && got == c.expect, c.name);
}
fresh();
std::error_code ec;
files::watch_changes(path, {"mkdir"}, ec);
expect(ec == std::errc::is_a_directory, "directory");
// The same size and the same mtime hide a change.
fresh();
auto t = fs::file_time_type::clock::now() - 1h;
write_with_mtime("abc\n", t);
ec.clear();
files::FileWatcher watcher(path, ec);
write_with_mtime("xyz\n", t);
expect(watcher.poll(ec) == "none", "same size and time");
std::ofstream(path, std::ios::binary) << "xyz!\n";
expect(watcher.poll(ec) == "modified", "new size");
// One call for a burst of changes.
fresh();
std::mutex mu;
std::vector<fs::path> calls;
std::atomic<bool> done{false};
std::error_code wec;
std::thread th([&] {
files::watch(
path, [&](const fs::path& p) { std::lock_guard lock(mu); calls.push_back(p); }, 10ms, 500ms,
[&] { return done.load(); }, wec);
});
for (int i = 1; i <= 5; ++i) {
std::ofstream(path, std::ios::binary) << std::string(i, 'x');
std::this_thread::sleep_for(20ms);
}
auto deadline = std::chrono::steady_clock::now() + 5s;
while (std::chrono::steady_clock::now() < deadline) {
{
std::lock_guard lock(mu);
if (!calls.empty()) break;
}
std::this_thread::sleep_for(10ms);
}
std::this_thread::sleep_for(600ms);
done = true;
th.join();
expect(!wec && calls == std::vector<fs::path>{path}, "burst");
fs::remove_all(dir);
if (failures) return 1;
std::puts("all tests pass");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
/** Watch a file for changes: poll its size and modification time. */
public final class WatchFile {
/** Seconds; the cases set the mtime to BASE_MTIME + step. */
static final long BASE_MTIME = 1_700_000_000L;
private WatchFile() {}
/** The size and the mtime of a file. */
record Signature(long size, FileTime mtime) {}
/** The signature of the file, or null when it does not exist. */
static Signature signature(Path path) throws IOException {
BasicFileAttributes a;
try {
a = Files.readAttributes(path, BasicFileAttributes.class);
} catch (NoSuchFileException e) {
return null;
}
if (a.isDirectory()) {
throw new FileSystemException(path.toString(), null, "Is a directory");
}
return new Signature(a.size(), a.lastModifiedTime());
}
/** Remembers the last signature of a file and tells what changed since then. */
public static final class FileWatcher {
private final Path path;
private Signature last;
public FileWatcher(Path path) throws IOException {
this.path = path;
this.last = signature(path);
}
/** created, deleted, modified or none, for the time since the last poll. */
public String poll() throws IOException {
Signature now = signature(path);
Signature before = last;
last = now;
if (before == null && now == null) {
return "none";
}
if (before == null) {
return "created";
}
if (now == null) {
return "deleted";
}
return Objects.equals(before, now) ? "none" : "modified";
}
}
/** Calls onChange once for each burst of changes, after the file is quiet. */
public static void watch(
Path path, Consumer<Path> onChange, long intervalMillis, long quietMillis, BooleanSupplier stop)
throws IOException, InterruptedException {
FileWatcher watcher = new FileWatcher(path);
long pending = -1; // the time of the last change that onChange has not seen
while (!stop.getAsBoolean()) {
long now = System.nanoTime();
if (!watcher.poll().equals("none")) {
pending = now;
} else if (pending >= 0 && now - pending >= TimeUnit.MILLISECONDS.toNanos(quietMillis)) {
pending = -1;
onChange.accept(path);
}
Thread.sleep(intervalMillis);
}
}
/** Makes the change of one step of a case (the entry of the cases uses it). */
static void applyStep(Path path, String step, int number) throws IOException {
int colon = step.indexOf(':');
String kind = colon < 0 ? step : step.substring(0, colon);
byte[] text = (colon < 0 ? "" : step.substring(colon + 1)).getBytes(StandardCharsets.UTF_8);
switch (kind) {
case "create", "write" -> Files.write(path, text);
case "append" -> Files.write(path, text, StandardOpenOption.APPEND);
case "replace" -> {
Path tmp = path.resolveSibling(path.getFileName() + ".tmp");
Files.write(tmp, text);
Files.move(tmp, path, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
}
case "recreate" -> {
Files.delete(path);
Files.write(path, text);
}
case "delete" -> Files.delete(path);
case "mkdir" -> Files.createDirectory(path);
case "touch", "none" -> {}
default -> throw new IllegalArgumentException("unknown step " + step);
}
if (!kind.equals("none") && Files.isRegularFile(path)) {
Files.setLastModifiedTime(path, FileTime.from(BASE_MTIME + number, TimeUnit.SECONDS));
}
}
/** The entry of the cases: polls after each step and returns the results. */
public static List<String> watchChanges(Path path, List<String> steps) throws IOException {
FileWatcher watcher = new FileWatcher(path);
List<String> results = new ArrayList<>();
for (int i = 0; i < steps.size(); i++) {
applyStep(path, steps.get(i), i + 1);
results.add(watcher.poll());
}
return results;
}
}
WatchFileTest.java 109 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class WatchFileTest {
@TempDir Path dir;
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("create", List.of("create:hello\n"), List.of("created")),
Arguments.of(
"create-then-write",
List.of("create:a\n", "write:a much longer line\n"),
List.of("created", "modified")),
Arguments.of(
"create-then-delete", List.of("create:a\n", "delete"), List.of("created", "deleted")),
Arguments.of(
"append",
List.of("create:a\n", "append:b\n", "append:c\n"),
List.of("created", "modified", "modified")),
Arguments.of(
"no-change", List.of("create:a\n", "none", "none"), List.of("created", "none", "none")),
Arguments.of(
"same-size", List.of("create:abc\n", "write:xyz\n"), List.of("created", "modified")),
Arguments.of("touch-only", List.of("create:a\n", "touch"), List.of("created", "modified")),
Arguments.of(
"replace-by-rename",
List.of("create:old\n", "replace:new\n"),
List.of("created", "modified")),
Arguments.of(
"delete-and-create",
List.of("create:a\n", "recreate:b\n"),
List.of("created", "modified")),
Arguments.of("never-created", List.of("none"), List.of("none")));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void cases(String name, List<String> steps, List<String> expect) throws Exception {
assertEquals(expect, WatchFile.watchChanges(dir.resolve("watched.txt"), steps));
}
@Test
void directoryIsAnError() {
assertThrows(
FileSystemException.class,
() -> WatchFile.watchChanges(dir.resolve("watched.txt"), List.of("mkdir")));
}
@Test
void sameSizeAndSameTimeHideAChange() throws Exception {
Path p = dir.resolve("watched.txt");
FileTime t = FileTime.from(5, TimeUnit.SECONDS);
Files.writeString(p, "abc\n");
Files.setLastModifiedTime(p, t);
WatchFile.FileWatcher watcher = new WatchFile.FileWatcher(p);
Files.writeString(p, "xyz\n");
Files.setLastModifiedTime(p, t);
assertEquals("none", watcher.poll());
Files.writeString(p, "xyz!\n");
assertEquals("modified", watcher.poll());
}
@Test
void watchCallsOnceForABurst() throws Exception {
Path p = dir.resolve("watched.txt");
List<Path> calls = new CopyOnWriteArrayList<>();
AtomicBoolean done = new AtomicBoolean();
Thread t =
new Thread(
() -> {
try {
WatchFile.watch(p, calls::add, 10, 500, done::get);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
t.start();
for (int i = 1; i <= 5; i++) {
Files.writeString(p, "x".repeat(i));
Thread.sleep(20);
}
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (calls.isEmpty() && System.nanoTime() < deadline) {
Thread.sleep(10);
}
Thread.sleep(600);
done.set(true);
t.join();
assertEquals(List.of(p), calls);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
#define _POSIX_C_SOURCE 200809L
#ifdef __APPLE__
#define _DARWIN_C_SOURCE
#endif
#include "watch_file.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef __APPLE__
#define MTIME(st) ((st).st_mtimespec)
#else
#define MTIME(st) ((st).st_mtim)
#endif
// Reads the signature of path into w. A missing file is not an error.
static int take_signature(const char *path, bool *exists, off_t *size, struct timespec *mtime) {
struct stat st;
if (stat(path, &st) != 0) {
if (errno != ENOENT) return -1;
*exists = false;
*size = 0;
mtime->tv_sec = 0;
mtime->tv_nsec = 0;
return 0;
}
if (S_ISDIR(st.st_mode)) {
errno = EISDIR;
return -1;
}
*exists = true;
*size = st.st_size;
*mtime = MTIME(st);
return 0;
}
int watcher_init(struct file_watcher *w, const char *path) {
w->path = path;
return take_signature(path, &w->exists, &w->size, &w->mtime);
}
int watcher_poll(struct file_watcher *w, enum watch_change *change) {
bool exists;
off_t size;
struct timespec mtime;
if (take_signature(w->path, &exists, &size, &mtime) != 0) return -1;
if (!w->exists && !exists) {
*change = WATCH_NONE;
} else if (!w->exists) {
*change = WATCH_CREATED;
} else if (!exists) {
*change = WATCH_DELETED;
} else if (size != w->size || mtime.tv_sec != w->mtime.tv_sec || mtime.tv_nsec != w->mtime.tv_nsec) {
*change = WATCH_MODIFIED;
} else {
*change = WATCH_NONE;
}
w->exists = exists;
w->size = size;
w->mtime = mtime;
return 0;
}
const char *watch_change_name(enum watch_change change) {
switch (change) {
case WATCH_CREATED: return "created";
case WATCH_DELETED: return "deleted";
case WATCH_MODIFIED: return "modified";
default: return "none";
}
}
// Writes text to path with the flags of open. Returns 0, or -1 with errno.
static int put(const char *path, const char *text, int flags) {
int fd = open(path, flags, 0644);
if (fd < 0) return -1;
size_t len = strlen(text);
while (len > 0) {
ssize_t n = write(fd, text, len);
if (n < 0) {
if (errno == EINTR) continue;
int saved = errno;
close(fd);
errno = saved;
return -1;
}
text += n;
len -= (size_t)n;
}
return close(fd);
}
// Makes the change of one step of a case (the entry of the cases uses it).
static int apply_step(const char *path, const char *step, long number) {
const char *colon = strchr(step, ':');
size_t klen = colon ? (size_t)(colon - step) : strlen(step);
const char *text = colon ? colon + 1 : "";
char tmp[4096];
int rc;
#define IS(k) (klen == strlen(k) && strncmp(step, k, klen) == 0)
if (IS("create") || IS("write")) {
rc = put(path, text, O_WRONLY | O_CREAT | O_TRUNC);
} else if (IS("append")) {
rc = put(path, text, O_WRONLY | O_APPEND);
} else if (IS("replace")) {
if ((size_t)snprintf(tmp, sizeof tmp, "%s.tmp", path) >= sizeof tmp) {
errno = ENAMETOOLONG;
return -1;
}
rc = put(tmp, text, O_WRONLY | O_CREAT | O_TRUNC);
if (rc == 0) rc = rename(tmp, path);
} else if (IS("recreate")) {
rc = unlink(path);
if (rc == 0) rc = put(path, text, O_WRONLY | O_CREAT | O_TRUNC);
} else if (IS("delete")) {
rc = unlink(path);
} else if (IS("mkdir")) {
rc = mkdir(path, 0755);
} else if (IS("touch") || IS("none")) {
rc = 0;
} else {
errno = EINVAL;
return -1;
}
if (rc != 0) return -1;
struct stat st;
if (!IS("none") && stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
struct timespec times[2] = {{WATCH_BASE_MTIME + number, 0}, {WATCH_BASE_MTIME + number, 0}};
if (utimensat(AT_FDCWD, path, times, 0) != 0) return -1;
}
#undef IS
return 0;
}
int watch_changes(const char *path, const char *const *steps, size_t n, enum watch_change *out) {
struct file_watcher w;
if (watcher_init(&w, path) != 0) return -1;
for (size_t i = 0; i < n; i++) {
if (apply_step(path, steps[i], (long)i + 1) != 0) return -1;
if (watcher_poll(&w, &out[i]) != 0) return -1;
}
return 0;
}
watch_file.h 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
#ifndef WATCH_FILE_H
#define WATCH_FILE_H
#include <stdbool.h>
#include <stddef.h>
#include <sys/types.h>
#include <time.h>
// The cases set the mtime to WATCH_BASE_MTIME + step, in seconds.
#define WATCH_BASE_MTIME 1700000000L
enum watch_change { WATCH_NONE, WATCH_CREATED, WATCH_DELETED, WATCH_MODIFIED };
// The last signature of a file: its size and its mtime.
struct file_watcher {
const char *path;
bool exists;
off_t size;
struct timespec mtime;
};
// Takes the first signature. Returns 0, or -1 with errno (EISDIR for a directory).
int watcher_init(struct file_watcher *w, const char *path);
// Sets *change to what changed since the last poll. Returns 0, or -1 with errno.
int watcher_poll(struct file_watcher *w, enum watch_change *change);
// The name of a change: none, created, deleted or modified.
const char *watch_change_name(enum watch_change change);
// The entry of the cases: applies each of the n steps, polls after each, and
// writes the n results in out. Returns 0, or -1 with errno.
int watch_changes(const char *path, const char *const *steps, size_t n, enum watch_change *out);
#endif
test_watch_file.c 89 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
#define _POSIX_C_SOURCE 200809L
#include "watch_file.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static const char *path = "watch_tree/watched.txt";
static int failures = 0;
static void expect(int ok, const char *what) {
if (!ok) {
fprintf(stderr, "%s\n", what);
failures++;
}
}
static void fresh(void) {
if (system("rm -rf watch_tree && mkdir watch_tree") != 0) exit(2);
}
struct test_case {
const char *name;
const char *steps[4];
const char *expect[4];
};
static const struct test_case cases[] = {
{"create", {"create:hello\n"}, {"created"}},
{"create-then-write", {"create:a\n", "write:a much longer line\n"}, {"created", "modified"}},
{"create-then-delete", {"create:a\n", "delete"}, {"created", "deleted"}},
{"append", {"create:a\n", "append:b\n", "append:c\n"}, {"created", "modified", "modified"}},
{"no-change", {"create:a\n", "none", "none"}, {"created", "none", "none"}},
{"same-size", {"create:abc\n", "write:xyz\n"}, {"created", "modified"}},
{"touch-only", {"create:a\n", "touch"}, {"created", "modified"}},
{"replace-by-rename", {"create:old\n", "replace:new\n"}, {"created", "modified"}},
{"delete-and-create", {"create:a\n", "recreate:b\n"}, {"created", "modified"}},
{"never-created", {"none"}, {"none"}},
};
static void write_with_mtime(const char *text, time_t secs) {
FILE *f = fopen(path, "w");
if (!f || fputs(text, f) < 0 || fclose(f) != 0) exit(2);
struct timespec t[2] = {{secs, 0}, {secs, 0}};
if (utimensat(AT_FDCWD, path, t, 0) != 0) exit(2);
}
int main(void) {
for (size_t c = 0; c < sizeof cases / sizeof cases[0]; c++) {
fresh();
size_t n = 0;
while (n < 4 && cases[c].steps[n]) n++;
enum watch_change got[4];
int rc = watch_changes(path, cases[c].steps, n, got);
int ok = rc == 0;
for (size_t i = 0; ok && i < n; i++) ok = strcmp(watch_change_name(got[i]), cases[c].expect[i]) == 0;
expect(ok, cases[c].name);
}
fresh();
const char *mkdir_step[] = {"mkdir"};
enum watch_change got[1];
errno = 0;
expect(watch_changes(path, mkdir_step, 1, got) == -1 && errno == EISDIR, "directory");
// The same size and the same mtime hide a change.
fresh();
write_with_mtime("abc\n", 5);
struct file_watcher w;
enum watch_change change;
expect(watcher_init(&w, path) == 0, "init");
write_with_mtime("xyz\n", 5);
expect(watcher_poll(&w, &change) == 0 && change == WATCH_NONE, "same size and time");
write_with_mtime("xyz!\n", 5);
expect(watcher_poll(&w, &change) == 0 && change == WATCH_MODIFIED, "new size");
if (system("rm -rf watch_tree") != 0) failures++;
if (failures) return 1;
puts("all tests pass");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
using System.Diagnostics;
using System.Text;
/// <summary>Watch a file for changes: poll its size and modification time.</summary>
public static class WatchFile
{
/// <summary>Seconds; the cases set the mtime to BaseMtime + step.</summary>
public const long BaseMtime = 1_700_000_000;
/// <summary>The size and the mtime of a file.</summary>
private readonly record struct Signature(long Size, DateTime Mtime);
/// <summary>The signature of the file, or null when it does not exist.</summary>
private static Signature? Take(string path)
{
if (Directory.Exists(path))
{
throw new IOException($"{path} is a directory");
}
var info = new FileInfo(path);
if (!info.Exists)
{
return null;
}
return new Signature(info.Length, info.LastWriteTimeUtc);
}
/// <summary>Remembers the last signature of a file and tells what changed since then.</summary>
public sealed class FileWatcher
{
private readonly string path;
private Signature? last;
public FileWatcher(string path)
{
this.path = path;
last = Take(path);
}
/// <summary>created, deleted, modified or none, for the time since the last poll.</summary>
public string Poll()
{
Signature? now = Take(path);
Signature? before = last;
last = now;
return (before, now) switch
{
(null, null) => "none",
(null, _) => "created",
(_, null) => "deleted",
_ => before == now ? "none" : "modified",
};
}
}
/// <summary>Calls onChange once for each burst of changes, after the file is quiet.</summary>
public static void Watch(string path, Action<string> onChange, TimeSpan interval, TimeSpan quiet, CancellationToken stop)
{
var watcher = new FileWatcher(path);
long? pending = null; // the time of the last change that onChange has not seen
while (!stop.IsCancellationRequested)
{
if (watcher.Poll() != "none")
{
pending = Stopwatch.GetTimestamp();
}
else if (pending is long t && Stopwatch.GetElapsedTime(t) >= quiet)
{
pending = null;
onChange(path);
}
Thread.Sleep(interval);
}
}
/// <summary>Makes the change of one step of a case (the entry of the cases uses it).</summary>
private static void ApplyStep(string path, string step, int number)
{
int colon = step.IndexOf(':');
string kind = colon < 0 ? step : step[..colon];
string text = colon < 0 ? "" : step[(colon + 1)..];
var utf8 = new UTF8Encoding(false);
switch (kind)
{
case "create":
case "write":
File.WriteAllText(path, text, utf8);
break;
case "append":
if (!File.Exists(path))
{
throw new FileNotFoundException("no file to append to", path);
}
File.AppendAllText(path, text, utf8);
break;
case "replace":
File.WriteAllText(path + ".tmp", text, utf8);
File.Move(path + ".tmp", path, overwrite: true);
break;
case "recreate":
File.Delete(path);
File.WriteAllText(path, text, utf8);
break;
case "delete":
File.Delete(path);
break;
case "mkdir":
Directory.CreateDirectory(path);
break;
case "touch":
case "none":
break;
default:
throw new ArgumentException($"unknown step {step}");
}
if (kind != "none" && File.Exists(path))
{
File.SetLastWriteTimeUtc(path, DateTime.UnixEpoch.AddSeconds(BaseMtime + number));
}
}
/// <summary>The entry of the cases: polls after each step and returns the results.</summary>
public static List<string> WatchChanges(string path, IReadOnlyList<string> steps)
{
var watcher = new FileWatcher(path);
var results = new List<string>();
for (int i = 0; i < steps.Count; i++)
{
ApplyStep(path, steps[i], i + 1);
results.Add(watcher.Poll());
}
return results;
}
}
WatchFileTests.cs 80 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
using System.Collections.Concurrent;
using System.Diagnostics;
using Xunit;
public sealed class WatchFileTests : IDisposable
{
private readonly string dir = Directory.CreateTempSubdirectory("watch-file-").FullName;
public void Dispose() => Directory.Delete(dir, recursive: true);
private string Watched => Path.Combine(dir, "watched.txt");
public static TheoryData<string, string[], string[]> Cases => new()
{
{ "create", ["create:hello\n"], ["created"] },
{ "create-then-write", ["create:a\n", "write:a much longer line\n"], ["created", "modified"] },
{ "create-then-delete", ["create:a\n", "delete"], ["created", "deleted"] },
{ "append", ["create:a\n", "append:b\n", "append:c\n"], ["created", "modified", "modified"] },
{ "no-change", ["create:a\n", "none", "none"], ["created", "none", "none"] },
{ "same-size", ["create:abc\n", "write:xyz\n"], ["created", "modified"] },
{ "touch-only", ["create:a\n", "touch"], ["created", "modified"] },
{ "replace-by-rename", ["create:old\n", "replace:new\n"], ["created", "modified"] },
{ "delete-and-create", ["create:a\n", "recreate:b\n"], ["created", "modified"] },
{ "never-created", ["none"], ["none"] },
};
[Theory]
[MemberData(nameof(Cases))]
public void Polls(string name, string[] steps, string[] expect)
{
Assert.False(string.IsNullOrEmpty(name));
Assert.Equal(expect, WatchFile.WatchChanges(Watched, steps));
}
[Fact]
public void DirectoryIsAnError()
{
Assert.Throws<IOException>(() => WatchFile.WatchChanges(Watched, ["mkdir"]));
}
[Fact]
public void SameSizeAndSameTimeHideAChange()
{
var t = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc);
File.WriteAllText(Watched, "abc\n");
File.SetLastWriteTimeUtc(Watched, t);
var watcher = new WatchFile.FileWatcher(Watched);
File.WriteAllText(Watched, "xyz\n");
File.SetLastWriteTimeUtc(Watched, t);
Assert.Equal("none", watcher.Poll());
File.WriteAllText(Watched, "xyz!\n");
Assert.Equal("modified", watcher.Poll());
}
[Fact]
public async Task WatchCallsOnceForABurst()
{
var calls = new ConcurrentQueue<string>();
using var stop = new CancellationTokenSource();
var task = Task.Run(() => WatchFile.Watch(
Watched, calls.Enqueue, TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(500), stop.Token));
for (int i = 1; i <= 5; i++)
{
File.WriteAllText(Watched, new string('x', i));
await Task.Delay(20);
}
var clock = Stopwatch.StartNew();
while (calls.IsEmpty && clock.Elapsed < TimeSpan.FromSeconds(5))
{
await Task.Delay(10);
}
await Task.Delay(600);
stop.Cancel();
await task;
Assert.Equal([Watched], calls.ToArray());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
// Watch a file for changes: poll its size and modification time.
import * as fs from "node:fs";
const BASE_MTIME = 1_700_000_000; // seconds; the cases set the mtime to BASE_MTIME + step
// The size and the mtime in ns of the file, or null when it does not exist.
export function signature(path) {
let st;
try {
st = fs.statSync(path, { bigint: true });
} catch (err) {
if (err.code === "ENOENT") return null;
throw err;
}
if (st.isDirectory()) {
const err = new Error(`EISDIR: illegal operation on a directory, watch '${path}'`);
err.code = "EISDIR";
throw err;
}
return `${st.size}:${st.mtimeNs}`;
}
export class FileWatcher {
constructor(path) {
this.path = path;
this.last = signature(path);
}
// created, deleted, modified or none, for the time since the last poll.
poll() {
const now = signature(this.path);
const before = this.last;
this.last = now;
if (before === null && now === null) return "none";
if (before === null) return "created";
if (now === null) return "deleted";
return now !== before ? "modified" : "none";
}
}
// Call onChange(path) once for each burst of changes, after the file is quiet.
// It returns a function that stops the watch.
export function watch(path, onChange, { interval = 500, quiet = 200 } = {}) {
const watcher = new FileWatcher(path);
let pending = null;
const timer = setInterval(() => {
if (watcher.poll() !== "none") {
pending = Date.now();
} else if (pending !== null && Date.now() - pending >= quiet) {
pending = null;
onChange(path);
}
}, interval);
return () => clearInterval(timer);
}
// Make the change of one step of a case (the entry of the cases uses it).
function applyStep(path, step, number) {
const colon = step.indexOf(":");
const kind = colon < 0 ? step : step.slice(0, colon);
const text = colon < 0 ? "" : step.slice(colon + 1);
switch (kind) {
case "create":
case "write":
fs.writeFileSync(path, text);
break;
case "append":
fs.appendFileSync(path, text);
break;
case "replace":
fs.writeFileSync(`${path}.tmp`, text);
fs.renameSync(`${path}.tmp`, path);
break;
case "recreate":
fs.unlinkSync(path);
fs.writeFileSync(path, text);
break;
case "delete":
fs.unlinkSync(path);
break;
case "mkdir":
fs.mkdirSync(path);
break;
case "touch":
case "none":
break;
default:
throw new Error(`unknown step ${step}`);
}
if (kind !== "none" && fs.existsSync(path) && fs.statSync(path).isFile()) {
const t = BASE_MTIME + number;
fs.utimesSync(path, t, t);
}
}
// The entry of the cases: poll after each step and return the results.
export function watchChanges(path, steps) {
const watcher = new FileWatcher(path);
return steps.map((step, i) => {
applyStep(path, step, i + 1);
return watcher.poll();
});
}
watchFile.test.js 85 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { test } from "node:test";
import { FileWatcher, watch, watchChanges } from "./watchFile.js";
const CASES = {
"create": [["create:hello\n"], ["created"]],
"create-then-write": [["create:a\n", "write:a much longer line\n"], ["created", "modified"]],
"create-then-delete": [["create:a\n", "delete"], ["created", "deleted"]],
"append": [["create:a\n", "append:b\n", "append:c\n"], ["created", "modified", "modified"]],
"no-change": [["create:a\n", "none", "none"], ["created", "none", "none"]],
"same-size": [["create:abc\n", "write:xyz\n"], ["created", "modified"]],
"touch-only": [["create:a\n", "touch"], ["created", "modified"]],
"replace-by-rename": [["create:old\n", "replace:new\n"], ["created", "modified"]],
"delete-and-create": [["create:a\n", "recreate:b\n"], ["created", "modified"]],
"never-created": [["none"], ["none"]],
};
function tempDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), "watch-"));
}
for (const [name, [steps, expect]] of Object.entries(CASES)) {
test(name, () => {
const dir = tempDir();
try {
assert.deepEqual(watchChanges(path.join(dir, "watched.txt"), steps), expect);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
}
test("a directory is an error", () => {
const dir = tempDir();
try {
assert.throws(() => watchChanges(path.join(dir, "watched.txt"), ["mkdir"]), { code: "EISDIR" });
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("the same size and the same mtime hide a change", () => {
const dir = tempDir();
try {
const p = path.join(dir, "watched.txt");
fs.writeFileSync(p, "abc\n");
fs.utimesSync(p, 5, 5);
const watcher = new FileWatcher(p);
fs.writeFileSync(p, "xyz\n");
fs.utimesSync(p, 5, 5);
assert.equal(watcher.poll(), "none");
fs.writeFileSync(p, "xyz!\n");
assert.equal(watcher.poll(), "modified");
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("watch calls once for a burst of changes", async () => {
const dir = tempDir();
const p = path.join(dir, "watched.txt");
const calls = [];
const stop = watch(p, (f) => calls.push(f), { interval: 10, quiet: 500 });
try {
for (let i = 0; i < 5; i++) {
fs.writeFileSync(p, "x".repeat(i + 1));
await new Promise((r) => setTimeout(r, 20));
}
const deadline = Date.now() + 5000;
while (calls.length === 0 && Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 10));
}
await new Promise((r) => setTimeout(r, 600));
assert.deepEqual(calls, [p]);
} finally {
stop();
fs.rmSync(dir, { recursive: true, force: true });
}
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
// Watch a file for changes: poll its size and modification time.
import * as fs from "node:fs";
const BASE_MTIME = 1_700_000_000; // seconds; the cases set the mtime to BASE_MTIME + step
// The size and the mtime in ns of the file, or null when it does not exist.
export function signature(path: string): string | null {
let st: fs.BigIntStats;
try {
st = fs.statSync(path, { bigint: true });
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
throw err;
}
if (st.isDirectory()) {
const err: NodeJS.ErrnoException = new Error(`EISDIR: illegal operation on a directory, watch '${path}'`);
err.code = "EISDIR";
throw err;
}
return `${st.size}:${st.mtimeNs}`;
}
export class FileWatcher {
readonly path: string;
private last: string | null;
constructor(path: string) {
this.path = path;
this.last = signature(path);
}
// created, deleted, modified or none, for the time since the last poll.
poll(): string {
const now = signature(this.path);
const before = this.last;
this.last = now;
if (before === null && now === null) return "none";
if (before === null) return "created";
if (now === null) return "deleted";
return now !== before ? "modified" : "none";
}
}
// Call onChange(path) once for each burst of changes, after the file is quiet.
// It returns a function that stops the watch.
export function watch(
path: string,
onChange: (path: string) => void,
{ interval = 500, quiet = 200 }: { interval?: number; quiet?: number } = {},
): () => void {
const watcher = new FileWatcher(path);
let pending: number | null = null;
const timer = setInterval(() => {
if (watcher.poll() !== "none") {
pending = Date.now();
} else if (pending !== null && Date.now() - pending >= quiet) {
pending = null;
onChange(path);
}
}, interval);
return () => clearInterval(timer);
}
// Make the change of one step of a case (the entry of the cases uses it).
function applyStep(path: string, step: string, number: number): void {
const colon = step.indexOf(":");
const kind = colon < 0 ? step : step.slice(0, colon);
const text = colon < 0 ? "" : step.slice(colon + 1);
switch (kind) {
case "create":
case "write":
fs.writeFileSync(path, text);
break;
case "append":
fs.appendFileSync(path, text);
break;
case "replace":
fs.writeFileSync(`${path}.tmp`, text);
fs.renameSync(`${path}.tmp`, path);
break;
case "recreate":
fs.unlinkSync(path);
fs.writeFileSync(path, text);
break;
case "delete":
fs.unlinkSync(path);
break;
case "mkdir":
fs.mkdirSync(path);
break;
case "touch":
case "none":
break;
default:
throw new Error(`unknown step ${step}`);
}
if (kind !== "none" && fs.existsSync(path) && fs.statSync(path).isFile()) {
const t = BASE_MTIME + number;
fs.utimesSync(path, t, t);
}
}
// The entry of the cases: poll after each step and return the results.
export function watchChanges(path: string, steps: string[]): string[] {
const watcher = new FileWatcher(path);
return steps.map((step, i) => {
applyStep(path, step, i + 1);
return watcher.poll();
});
}
watchFile.test.ts 85 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { test } from "node:test";
import { FileWatcher, watch, watchChanges } from "./watchFile.ts";
const CASES: Record<string, [string[], string[]]> = {
"create": [["create:hello\n"], ["created"]],
"create-then-write": [["create:a\n", "write:a much longer line\n"], ["created", "modified"]],
"create-then-delete": [["create:a\n", "delete"], ["created", "deleted"]],
"append": [["create:a\n", "append:b\n", "append:c\n"], ["created", "modified", "modified"]],
"no-change": [["create:a\n", "none", "none"], ["created", "none", "none"]],
"same-size": [["create:abc\n", "write:xyz\n"], ["created", "modified"]],
"touch-only": [["create:a\n", "touch"], ["created", "modified"]],
"replace-by-rename": [["create:old\n", "replace:new\n"], ["created", "modified"]],
"delete-and-create": [["create:a\n", "recreate:b\n"], ["created", "modified"]],
"never-created": [["none"], ["none"]],
};
function tempDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), "watch-"));
}
for (const [name, [steps, expect]] of Object.entries(CASES)) {
test(name, () => {
const dir = tempDir();
try {
assert.deepEqual(watchChanges(path.join(dir, "watched.txt"), steps), expect);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
}
test("a directory is an error", () => {
const dir = tempDir();
try {
assert.throws(() => watchChanges(path.join(dir, "watched.txt"), ["mkdir"]), { code: "EISDIR" });
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("the same size and the same mtime hide a change", () => {
const dir = tempDir();
try {
const p = path.join(dir, "watched.txt");
fs.writeFileSync(p, "abc\n");
fs.utimesSync(p, 5, 5);
const watcher = new FileWatcher(p);
fs.writeFileSync(p, "xyz\n");
fs.utimesSync(p, 5, 5);
assert.equal(watcher.poll(), "none");
fs.writeFileSync(p, "xyz!\n");
assert.equal(watcher.poll(), "modified");
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("watch calls once for a burst of changes", async () => {
const dir = tempDir();
const p = path.join(dir, "watched.txt");
const calls: string[] = [];
const stop = watch(p, (f) => calls.push(f), { interval: 10, quiet: 500 });
try {
for (let i = 0; i < 5; i++) {
fs.writeFileSync(p, "x".repeat(i + 1));
await new Promise((r) => setTimeout(r, 20));
}
const deadline = Date.now() + 5000;
while (calls.length === 0 && Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 10));
}
await new Promise((r) => setTimeout(r, 600));
assert.deepEqual(calls, [p]);
} finally {
stop();
fs.rmSync(dir, { recursive: true, force: true });
}
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
// Package watchfile watches a file for changes: it polls the size and the
// modification time of the file.
package watchfile
import (
"errors"
"fmt"
"io/fs"
"os"
"strings"
"syscall"
"time"
)
// BaseMtime is in seconds; the cases set the mtime to BaseMtime + step.
const BaseMtime = 1_700_000_000
type signature struct {
size int64
mtime time.Time
}
// stat gives the signature of the file, or ok false when it does not exist.
func stat(path string) (sig signature, ok bool, err error) {
info, err := os.Stat(path)
if errors.Is(err, fs.ErrNotExist) {
return signature{}, false, nil
}
if err != nil {
return signature{}, false, err
}
if info.IsDir() {
return signature{}, false, &fs.PathError{Op: "watch", Path: path, Err: syscall.EISDIR}
}
return signature{info.Size(), info.ModTime()}, true, nil
}
// Watcher remembers the last signature of a file and tells what changed since then.
type Watcher struct {
path string
last signature
exists bool
}
// New makes a watcher of path, and takes the first signature.
func New(path string) (*Watcher, error) {
sig, ok, err := stat(path)
if err != nil {
return nil, err
}
return &Watcher{path, sig, ok}, nil
}
// Poll returns created, deleted, modified or none, for the time since the last poll.
func (w *Watcher) Poll() (string, error) {
sig, ok, err := stat(w.path)
if err != nil {
return "", err
}
before, existed := w.last, w.exists
w.last, w.exists = sig, ok
switch {
case !existed && !ok:
return "none", nil
case !existed:
return "created", nil
case !ok:
return "deleted", nil
case sig.size != before.size || !sig.mtime.Equal(before.mtime):
return "modified", nil
}
return "none", nil
}
// Watch calls onChange once for each burst of changes, after the file is
// quiet, until stop is closed.
func Watch(path string, onChange func(string), interval, quiet time.Duration, stop <-chan struct{}) error {
w, err := New(path)
if err != nil {
return err
}
var pending time.Time // the time of the last change that onChange has not seen
tick := time.NewTicker(interval)
defer tick.Stop()
for {
select {
case <-stop:
return nil
case <-tick.C:
}
change, err := w.Poll()
if err != nil {
return err
}
if change != "none" {
pending = time.Now()
} else if !pending.IsZero() && time.Since(pending) >= quiet {
pending = time.Time{}
onChange(path)
}
}
}
// applyStep makes the change of one step of a case (the entry of the cases uses it).
func applyStep(path, step string, number int) error {
kind, text, _ := strings.Cut(step, ":")
var err error
switch kind {
case "create", "write":
err = os.WriteFile(path, []byte(text), 0o644)
case "append":
var f *os.File
if f, err = os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0); err == nil {
_, err = f.WriteString(text)
if cerr := f.Close(); err == nil {
err = cerr
}
}
case "replace":
if err = os.WriteFile(path+".tmp", []byte(text), 0o644); err == nil {
err = os.Rename(path+".tmp", path)
}
case "recreate":
if err = os.Remove(path); err == nil {
err = os.WriteFile(path, []byte(text), 0o644)
}
case "delete":
err = os.Remove(path)
case "mkdir":
err = os.Mkdir(path, 0o755)
case "touch", "none":
default:
err = fmt.Errorf("unknown step %q", step)
}
if err != nil {
return err
}
if info, serr := os.Stat(path); kind != "none" && serr == nil && info.Mode().IsRegular() {
t := time.Unix(int64(BaseMtime+number), 0)
return os.Chtimes(path, t, t)
}
return nil
}
// WatchChanges is the entry of the cases: it polls after each step and returns the results.
func WatchChanges(path string, steps []string) ([]string, error) {
w, err := New(path)
if err != nil {
return nil, err
}
results := []string{}
for i, step := range steps {
if err := applyStep(path, step, i+1); err != nil {
return nil, err
}
change, err := w.Poll()
if err != nil {
return nil, err
}
results = append(results, change)
}
return results, nil
}
watch_file_test.go 112 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
package watchfile
import (
"errors"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"syscall"
"testing"
"time"
)
var cases = []struct {
name string
steps []string
expect []string
}{
{"create", []string{"create:hello\n"}, []string{"created"}},
{"create-then-write", []string{"create:a\n", "write:a much longer line\n"}, []string{"created", "modified"}},
{"create-then-delete", []string{"create:a\n", "delete"}, []string{"created", "deleted"}},
{"append", []string{"create:a\n", "append:b\n", "append:c\n"}, []string{"created", "modified", "modified"}},
{"no-change", []string{"create:a\n", "none", "none"}, []string{"created", "none", "none"}},
{"same-size", []string{"create:abc\n", "write:xyz\n"}, []string{"created", "modified"}},
{"touch-only", []string{"create:a\n", "touch"}, []string{"created", "modified"}},
{"replace-by-rename", []string{"create:old\n", "replace:new\n"}, []string{"created", "modified"}},
{"delete-and-create", []string{"create:a\n", "recreate:b\n"}, []string{"created", "modified"}},
{"never-created", []string{"none"}, []string{"none"}},
}
func TestCases(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := WatchChanges(filepath.Join(t.TempDir(), "watched.txt"), c.steps)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got, c.expect) {
t.Fatalf("got %v, want %v", got, c.expect)
}
})
}
}
func TestDirectoryIsAnError(t *testing.T) {
_, err := WatchChanges(filepath.Join(t.TempDir(), "watched.txt"), []string{"mkdir"})
if !errors.Is(err, syscall.EISDIR) {
t.Fatalf("got %v, want EISDIR", err)
}
}
func TestSameSizeAndSameTimeHideAChange(t *testing.T) {
p := filepath.Join(t.TempDir(), "watched.txt")
at := time.Unix(5, 0)
must(t, os.WriteFile(p, []byte("abc\n"), 0o644))
must(t, os.Chtimes(p, at, at))
w, err := New(p)
must(t, err)
must(t, os.WriteFile(p, []byte("xyz\n"), 0o644))
must(t, os.Chtimes(p, at, at))
if got, _ := w.Poll(); got != "none" {
t.Fatalf("got %s, want none", got)
}
must(t, os.WriteFile(p, []byte("xyz!\n"), 0o644))
if got, _ := w.Poll(); got != "modified" {
t.Fatalf("got %s, want modified", got)
}
}
func TestWatchCallsOnceForABurst(t *testing.T) {
p := filepath.Join(t.TempDir(), "watched.txt")
var mu sync.Mutex
var calls []string
stop := make(chan struct{})
done := make(chan error)
go func() {
done <- Watch(p, func(s string) { mu.Lock(); calls = append(calls, s); mu.Unlock() },
10*time.Millisecond, 500*time.Millisecond, stop)
}()
time.Sleep(30 * time.Millisecond) // let Watch take its first signature
for i := 1; i <= 5; i++ {
must(t, os.WriteFile(p, []byte(strings.Repeat("x", i)), 0o644))
time.Sleep(20 * time.Millisecond)
}
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
mu.Lock()
n := len(calls)
mu.Unlock()
if n > 0 {
break
}
time.Sleep(10 * time.Millisecond)
}
time.Sleep(600 * time.Millisecond)
close(stop)
must(t, <-done)
if !reflect.DeepEqual(calls, []string{p}) {
t.Fatalf("got %v, want one call", calls)
}
}
func must(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
//! Watch a file for changes: poll its size and modification time.
use std::fs::{self, File, FileTimes, OpenOptions};
use std::io::{self, ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
/// Seconds; the cases set the mtime to BASE_MTIME + step.
pub const BASE_MTIME: u64 = 1_700_000_000;
/// The size and the mtime of a file.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Signature {
size: u64,
mtime: SystemTime,
}
/// The signature of the file, or None when it does not exist.
fn signature(path: &Path) -> io::Result<Option<Signature>> {
let meta = match fs::metadata(path) {
Ok(meta) => meta,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
if meta.is_dir() {
return Err(io::Error::new(ErrorKind::IsADirectory, format!("{} is a directory", path.display())));
}
Ok(Some(Signature { size: meta.len(), mtime: meta.modified()? }))
}
/// Remembers the last signature of a file and tells what changed since then.
pub struct FileWatcher {
path: PathBuf,
last: Option<Signature>,
}
impl FileWatcher {
pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
let path = path.as_ref().to_path_buf();
let last = signature(&path)?;
Ok(FileWatcher { path, last })
}
/// created, deleted, modified or none, for the time since the last poll.
pub fn poll(&mut self) -> io::Result<&'static str> {
let now = signature(&self.path)?;
let before = std::mem::replace(&mut self.last, now);
Ok(match (before, now) {
(None, None) => "none",
(None, Some(_)) => "created",
(Some(_), None) => "deleted",
(Some(b), Some(n)) if b != n => "modified",
_ => "none",
})
}
}
/// Calls on_change once for each burst of changes, after the file is quiet,
/// until stop returns true.
pub fn watch(
path: impl AsRef<Path>,
mut on_change: impl FnMut(&Path),
interval: Duration,
quiet: Duration,
stop: impl Fn() -> bool,
) -> io::Result<()> {
let mut watcher = FileWatcher::new(path)?;
let mut pending: Option<Instant> = None; // the last change that on_change has not seen
while !stop() {
if watcher.poll()? != "none" {
pending = Some(Instant::now());
} else if pending.is_some_and(|t| t.elapsed() >= quiet) {
pending = None;
on_change(&watcher.path);
}
thread::sleep(interval);
}
Ok(())
}
/// Makes the change of one step of a case (the entry of the cases uses it).
fn apply_step(path: &Path, step: &str, number: u64) -> io::Result<()> {
let (kind, text) = step.split_once(':').unwrap_or((step, ""));
match kind {
"create" | "write" => fs::write(path, text)?,
"append" => OpenOptions::new().append(true).open(path)?.write_all(text.as_bytes())?,
"replace" => {
let mut tmp = path.as_os_str().to_owned();
tmp.push(".tmp");
fs::write(&tmp, text)?;
fs::rename(&tmp, path)?;
}
"recreate" => {
fs::remove_file(path)?;
fs::write(path, text)?;
}
"delete" => fs::remove_file(path)?,
"mkdir" => fs::create_dir(path)?,
"touch" | "none" => {}
_ => return Err(io::Error::new(ErrorKind::InvalidInput, format!("unknown step {step}"))),
}
if kind != "none" && path.is_file() {
let t = UNIX_EPOCH + Duration::from_secs(BASE_MTIME + number);
File::options().write(true).open(path)?.set_times(FileTimes::new().set_accessed(t).set_modified(t))?;
}
Ok(())
}
/// The entry of the cases: polls after each step and returns the results.
pub fn watch_changes(path: impl AsRef<Path>, steps: &[&str]) -> io::Result<Vec<String>> {
let path = path.as_ref();
let mut watcher = FileWatcher::new(path)?;
let mut results = Vec::new();
for (i, step) in steps.iter().enumerate() {
apply_step(path, step, i as u64 + 1)?;
results.push(watcher.poll()?.to_string());
}
Ok(results)
}
tests/watch_file_test.rs 109 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/watch-a-file-for-changes/.
use std::fs::{self, File, FileTimes};
use std::io::ErrorKind;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use algo_watch_a_file_for_changes::{watch, watch_changes, FileWatcher};
struct Tree(PathBuf);
impl Tree {
fn new(name: &str) -> Tree {
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("watch-{name}-{}-{nanos}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
Tree(dir)
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
const CASES: &[(&str, &[&str], &[&str])] = &[
("create", &["create:hello\n"], &["created"]),
("create-then-write", &["create:a\n", "write:a much longer line\n"], &["created", "modified"]),
("create-then-delete", &["create:a\n", "delete"], &["created", "deleted"]),
("append", &["create:a\n", "append:b\n", "append:c\n"], &["created", "modified", "modified"]),
("no-change", &["create:a\n", "none", "none"], &["created", "none", "none"]),
("same-size", &["create:abc\n", "write:xyz\n"], &["created", "modified"]),
("touch-only", &["create:a\n", "touch"], &["created", "modified"]),
("replace-by-rename", &["create:old\n", "replace:new\n"], &["created", "modified"]),
("delete-and-create", &["create:a\n", "recreate:b\n"], &["created", "modified"]),
("never-created", &["none"], &["none"]),
];
#[test]
fn cases() {
for (name, steps, expect) in CASES {
let tree = Tree::new(name);
let got = watch_changes(tree.0.join("watched.txt"), steps).unwrap();
assert_eq!(got, *expect, "case {name}");
}
}
#[test]
fn directory_is_an_error() {
let tree = Tree::new("dir");
let err = watch_changes(tree.0.join("watched.txt"), &["mkdir"]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::IsADirectory);
}
fn set_mtime(path: &PathBuf, secs: u64) {
let t = UNIX_EPOCH + Duration::from_secs(secs);
File::options().write(true).open(path).unwrap().set_times(FileTimes::new().set_modified(t)).unwrap();
}
#[test]
fn same_size_and_same_time_hide_a_change() {
let tree = Tree::new("same");
let p = tree.0.join("watched.txt");
fs::write(&p, "abc\n").unwrap();
set_mtime(&p, 5);
let mut watcher = FileWatcher::new(&p).unwrap();
fs::write(&p, "xyz\n").unwrap();
set_mtime(&p, 5);
assert_eq!(watcher.poll().unwrap(), "none");
fs::write(&p, "xyz!\n").unwrap();
assert_eq!(watcher.poll().unwrap(), "modified");
}
#[test]
fn watch_calls_once_for_a_burst() {
let tree = Tree::new("burst");
let p = tree.0.join("watched.txt");
let calls = Arc::new(Mutex::new(Vec::<PathBuf>::new()));
let done = Arc::new(AtomicBool::new(false));
let handle = {
let (p, calls, done) = (p.clone(), calls.clone(), done.clone());
thread::spawn(move || {
watch(
&p,
|f| calls.lock().unwrap().push(f.to_path_buf()),
Duration::from_millis(10),
Duration::from_millis(500),
|| done.load(Ordering::SeqCst),
)
})
};
for i in 1..=5 {
fs::write(&p, "x".repeat(i)).unwrap();
thread::sleep(Duration::from_millis(20));
}
let deadline = Instant::now() + Duration::from_secs(5);
while calls.lock().unwrap().is_empty() && Instant::now() < deadline {
thread::sleep(Duration::from_millis(10));
}
thread::sleep(Duration::from_millis(600));
done.store(true, Ordering::SeqCst);
handle.join().unwrap().unwrap();
assert_eq!(*calls.lock().unwrap(), vec![p]);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/watch-a-file-for-changes/.
# Watch a file for changes: poll its size and modification time.
# file_signature PATH: prints "SIZE MTIME" (the mtime in whole seconds), or
# nothing when the file does not exist. A directory is an error.
file_signature() {
local path=$1
if [ -d "$path" ]; then
printf 'watch: %s: Is a directory\n' "$path" >&2
return 1
fi
[ -e "$path" ] || return 0
# GNU stat takes -c; the stat of macOS and BSD takes -f.
stat -c '%s %Y' -- "$path" 2>/dev/null || stat -f '%z %m' -- "$path"
}
# watch_init PATH: takes the first signature into WATCH_LAST.
watch_init() {
WATCH_PATH=$1
WATCH_LAST=$(file_signature "$WATCH_PATH") || return 1
}
# watch_poll: sets WATCH_CHANGE to created, deleted, modified or none, for the
# time since the last poll. Do not call it in $( ): the new signature must stay
# in WATCH_LAST.
watch_poll() {
local now
now=$(file_signature "$WATCH_PATH") || return 1
if [ -z "$WATCH_LAST" ] && [ -z "$now" ]; then
WATCH_CHANGE=none
elif [ -z "$WATCH_LAST" ]; then
WATCH_CHANGE=created
elif [ -z "$now" ]; then
WATCH_CHANGE=deleted
elif [ "$now" != "$WATCH_LAST" ]; then
WATCH_CHANGE=modified
else
WATCH_CHANGE=none
fi
WATCH_LAST=$now
}
# watch_file PATH COMMAND [ARG...]: runs COMMAND once for each burst of
# changes, after the file is quiet for QUIET polls. INTERVAL is in seconds.
watch_file() {
local path=$1 quiet=${QUIET:-2} interval=${INTERVAL:-1} pending=-1
shift
watch_init "$path" || return 1
while :; do
watch_poll || return 1
if [ "$WATCH_CHANGE" != none ]; then
pending=0
elif [ "$pending" -ge 0 ]; then
pending=$((pending + 1))
if [ "$pending" -ge "$quiet" ]; then
pending=-1
"$@" "$path"
fi
fi
sleep "$interval"
done
}
test_watch_file.bats 81 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/watch-a-file-for-changes/.
bats_require_minimum_version 1.5.0
BASE_MTIME=1700000000
setup() {
source "$BATS_TEST_DIRNAME/watch_file.sh"
path=$BATS_TEST_TMPDIR/watched.txt
rm -rf "$path" "$path.tmp"
}
# set_mtime SECONDS FILE: GNU touch takes -d @SECONDS; BSD touch takes -t.
set_mtime() {
touch -d "@$1" "$2" 2>/dev/null || touch -t "$(date -r "$1" +%Y%m%d%H%M.%S)" "$2"
}
# apply_step STEP NUMBER: makes the change of one step of a case.
apply_step() {
local kind=${1%%:*} text=
[[ $1 == *:* ]] && text=${1#*:}
case $kind in
create | write) printf '%s' "$text" > "$path" ;;
append) [ -f "$path" ] && printf '%s' "$text" >> "$path" ;;
replace) printf '%s' "$text" > "$path.tmp" && mv -f "$path.tmp" "$path" ;;
recreate) rm "$path" && printf '%s' "$text" > "$path" ;;
delete) rm "$path" ;;
mkdir) mkdir "$path" ;;
touch | none) ;;
*) return 1 ;;
esac || return 1
if [ "$kind" != none ] && [ -f "$path" ]; then
set_mtime $((BASE_MTIME + $2)) "$path"
fi
}
# check EXPECT STEP...: the results of the polls, one for each step, joined by spaces.
check() {
local expect=$1 got=() i=0 step
shift
watch_init "$path" || return 1
for step in "$@"; do
i=$((i + 1))
apply_step "$step" "$i" || return 1
watch_poll || return 1
got+=("$WATCH_CHANGE")
done
[ "${got[*]}" = "$expect" ]
}
@test "create" { check created $'create:hello\n'; }
@test "create-then-write" { check "created modified" $'create:a\n' $'write:a much longer line\n'; }
@test "create-then-delete" { check "created deleted" $'create:a\n' delete; }
@test "append" { check "created modified modified" $'create:a\n' $'append:b\n' $'append:c\n'; }
@test "no-change" { check "created none none" $'create:a\n' none none; }
@test "same-size" { check "created modified" $'create:abc\n' $'write:xyz\n'; }
@test "touch-only" { check "created modified" $'create:a\n' touch; }
@test "replace-by-rename" { check "created modified" $'create:old\n' $'replace:new\n'; }
@test "delete-and-create" { check "created modified" $'create:a\n' $'recreate:b\n'; }
@test "never-created" { check none none; }
@test "a directory is an error" {
watch_init "$path"
mkdir "$path"
run ! watch_poll
}
@test "the same size and the same mtime hide a change" {
printf 'abc\n' > "$path"
set_mtime 5 "$path"
watch_init "$path"
printf 'xyz\n' > "$path"
set_mtime 5 "$path"
watch_poll
[ "$WATCH_CHANGE" = none ]
printf 'xyz!\n' > "$path"
watch_poll
[ "$WATCH_CHANGE" = modified ]
}
References
- Linux manual page, inotify(7), DESCRIPTION, NOTES (Limitations and caveats)
- Linux manual page, inode(7), Last modification timestamp, File timestamps
- FreeBSD System Calls Manual, kqueue(2), EVFILT_VNODE
- Apple, File System Events Programming Guide, Technology Overview, Technology Overview
- Microsoft Learn, ReadDirectoryChangesW function (winbase.h), Return value, Remarks
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), sys/stat.h, DESCRIPTION, RATIONALE
- Java SE 25 API, WatchService, Platform dependencies, Implementation Note
- .NET API reference, FileSystemWatcher Class, Remarks, Events and buffer sizes
- Node.js documentation, File system, fs.watch, Caveats, fs.watchFile
- The Python Standard Library, os, Miscellaneous operating system interfaces, os.stat_result
- Go standard library, package os, func Chtimes, type FileInfo
- The Rust Standard Library, std::fs::Metadata, modified
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag XQK5XQ Edit this page History Report an error Markdown