Watch a Directory for File Changes in Rust with watchexec
Seeing Things, Doing Things
This is another refinementprior to watching files for changes in Rust. This time, using watchexecwe to handle the debouncing. It'll also automatically stop a command and restart it if it hasn't finished up before the next change happens.
#!/usr/bin/env cargo -q -Zscript
---
anyhow = "1.0.98"
clearscreen = "4.0.1"
itertools = "0.14.0"
tokio =
watchexec = "8.0.1"
watchexec-events = "6.0.0"
watchexec-signals = "5.0.0"
---
use Result;
use Itertools;
use Arc;
use PathBuf;
use ;
use ;
use ;
use *;
use Signal;
async
async
Details
-
The command is run by passing a
-c
flag to bash. That means the full command (including arguments) needs to be assembled into a string and set for thecommand
of theProgram::Shell
.If you try to put stuff in
args
they won't got to your command. The way I read the docs, they go to bash, but I haven't checked that directly. -
The majority of the script is the
get_paths()
function. When a file change happens a ton of events are fired off.get_paths()
filters down to just the events where data changed (instead of metadata).The
filter_map()
filters out files that are either hidden themselves or in a hidden directory. It also filters out files that end with a~
which is Neovim's temporary file extension.
TODO
Link watch-scripts
Link watch-file
Link serve-folder
Footnotes
I'd been using notify and notify_debouncer_full to watch for changes. That's what watchexec
uses under the hood. It adds the process supervisor which is a very nice quality of life improvement.