Skip to content

Commit

Permalink
enh(watcher): add event debounce
Browse files Browse the repository at this point in the history
  • Loading branch information
kkharji committed Apr 19, 2022
1 parent 4764a91 commit 18697f0
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 8 deletions.
4 changes: 2 additions & 2 deletions src/state/workspace.rs
Expand Up @@ -95,7 +95,7 @@ impl Workspace {
pub async fn on_directory_change(
&mut self,
path: PathBuf,
_event: notify::EventKind,
_event: &notify::EventKind,
) -> Result<()> {
if crate::xcodegen::is_workspace(self) {
self.update_xcodeproj(path.file_name().unwrap().eq("project.yml"))
Expand Down Expand Up @@ -126,7 +126,7 @@ impl Workspace {
Ok(())
}
Err(e) => {
tracing::error!("{:?}", e);
tracing::error!("xcodegen generate: {:#?}", e);
Err(e)
}
}
Expand Down
1 change: 1 addition & 0 deletions src/util/tracing.rs
Expand Up @@ -14,6 +14,7 @@ pub fn install_tracing(root: &str, filename: &str) -> Result<()> {
fmt::Layer::new()
.with_writer(io::stdout)
.with_target(true)
.with_line_number(true)
.with_file(false),
)
.with(
Expand Down
31 changes: 26 additions & 5 deletions src/util/watch.rs
Expand Up @@ -51,6 +51,8 @@ pub async fn update(state: crate::state::SharedState, _msg: crate::DaemonCommand

for root in start_watching {
let handle = new(state.clone(), root.clone());
#[cfg(feature = "logging")]
tracing::info!("Watching {root}");
current_state.watchers.insert(root, handle);
}
}
Expand All @@ -69,7 +71,7 @@ async fn get_ignore_patterns(state: crate::SharedState, root: &String) -> Vec<St
.map(|e| e.to_string())
.collect();

// FIXME: Addding extra ignore patterns to `ignore` local config requires restarting deamon.
// FIXME: Adding extra ignore patterns to `ignore` local config requires restarting daemon.
let extra_patterns = state
.lock()
.await
Expand All @@ -87,20 +89,23 @@ async fn get_ignore_patterns(state: crate::SharedState, root: &String) -> Vec<St

#[cfg(feature = "daemon")]
fn new(state: crate::SharedState, root: String) -> tokio::task::JoinHandle<anyhow::Result<()>> {
// NOTE: should watch for registerd directories?
// NOTE: should watch for registered directories?
// TODO: Support provideing additional ignore wildcard
//
// Some files can be generated as direct result of running build command.
// In my case this `Info.plist`.
//
// For example, define key inside project.yml under xcodebase key, ignoreGlob of type array.

let mut debounce = Box::new(std::time::SystemTime::now());
tokio::spawn(async move {
let (tx, mut rx) = mpsc::channel(100);

let mut watcher = RecommendedWatcher::new(move |res: Result<Event, Error>| {
if res.is_ok() {
tx.blocking_send(res.unwrap()).unwrap()
if let Ok(event) = res {
tx.blocking_send(event).unwrap();
} else {
tracing::error!("Watch Error: {:?}", res);
};
})?;

Expand Down Expand Up @@ -131,6 +136,17 @@ fn new(state: crate::SharedState, root: String) -> tokio::task::JoinHandle<anyho
continue;
}

let pass_threshold = debounce.elapsed().unwrap().as_millis() > 1;
if !pass_threshold {
#[cfg(feature = "logging")]
tracing::debug!(
"Skipping event: milliseconds: {} pass_threshold: {pass_threshold}, path: {:?}\n",
debounce.elapsed().unwrap().as_millis(),
event.paths
);
continue;
}

// debug!("[FSEVENT] {:?}", &event);
// NOTE: maybe better handle in tokio::spawn?
match &event.kind {
Expand Down Expand Up @@ -182,8 +198,13 @@ fn new(state: crate::SharedState, root: String) -> tokio::task::JoinHandle<anyho

match state.lock().await.workspaces.get_mut(&root) {
Some(w) => {
w.on_directory_change(path, event.kind).await?;
if let Err(e) = w.on_directory_change(path, &event.kind).await {
#[cfg(feature = "logging")]
tracing::error!("Fail to process {:?}:\n {:#?}", event, e);
}
debounce = Box::new(std::time::SystemTime::now())
}

// NOTE: should stop watch here
None => continue,
};
Expand Down
2 changes: 1 addition & 1 deletion src/xcode/compilation.rs
Expand Up @@ -90,7 +90,7 @@ impl Compiliation {

match command::CompilationCommand::new(directory, command) {
Ok(command) => {
tracing::debug!("Extracted {} Module Command", command.name);
tracing::debug!("Extracting swift module commands for [{}]", command.name);
Some(command)
}
Err(e) => {
Expand Down
1 change: 1 addition & 0 deletions src/xcodegen/mod.rs
Expand Up @@ -28,6 +28,7 @@ pub async fn generate<P: AsRef<Path> + Debug>(root: P) -> Result<Vec<String>> {
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.arg("generate")
.arg("-c")
.spawn()
.expect("Failed to start xcodeGen.")
.wait_with_output()
Expand Down

0 comments on commit 18697f0

Please sign in to comment.