Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Watch For File Changes In A Rust App

This works, but there's a better way to do it where you just look at the paths direclty to see what's changed that way:

2uxj96li

Code

use core::fmt::Error;
use core::time::Duration;
use miette::Result;
use std::path::PathBuf;
use watchexec::{
    action::Action,
    action::Outcome,
    config::{InitConfig, RuntimeConfig},
    Watchexec,
};
use watchexec_events::filekind::FileEventKind;
use watchexec_events::filekind::ModifyKind;
use watchexec_events::Tag;

#[tokio::main]
async fn main() -> Result<()> {
    println!("Starting process");
    let init = InitConfig::default();
    let mut runtime = RuntimeConfig::default();
    runtime.pathset(["/Users/alan/Desktop"]);
    runtime.action_throttle(Duration::new(0, 100000));
    let we = Watchexec::new(init, runtime.clone())?;
    runtime.on_action(move |action: Action| {
        async move {
            let mut events: Vec<PathBuf> = vec![];
            for event in action.events.iter() {
                let mut trigger: bool = false;
                let mut file_path: Option<PathBuf> = None;
                event.tags.iter().for_each(|tag| match tag {
                    Tag::Path { path, .. } => {
                        file_path = Some(path.to_path_buf());
                        events.push(file_path.clone().unwrap());
                    }
                    Tag::FileEventKind(event_kind) => match event_kind {
                        FileEventKind::Create(_) => {
                            trigger = true;
                        }
                        FileEventKind::Modify(modify_kind) => match modify_kind {
                            ModifyKind::Data(_) => {
                                trigger = true;
                            }
                            _ => {}
                        },
                        _ => {}
                    },
                    _ => {}
                });
            }
            events.dedup();
            events.iter().for_each(|p| do_something(p.to_path_buf()));
            action.outcome(Outcome::DoNothing);
            Ok::<(), Error>(())
        }
    });
    we.reconfigure(runtime).unwrap();
    we.main().await.unwrap().unwrap();
    Ok(())
}

fn do_something(file_path: PathBuf) {
    dbg!(file_path);
}

References