1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
use crate::config::Config;
use crate::git::GitRepo;
use anyhow::Context as _;
use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher, recommended_watcher};
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
/// Repository watcher
///
/// This object watches file changes and perform auto save when file is saved
pub struct RepoWatcher {
#[allow(unused)]
watcher: RecommendedWatcher,
#[allow(unused)]
debounce_thread: thread::JoinHandle<()>,
}
fn debounce_worker(rx: mpsc::Receiver<Event>, path: PathBuf, conf: Config) {
loop {
// Wait for the first event
if rx.recv().is_err() {
tracing::debug!("channel closed");
break;
}
// Debounce: keep receiving until no events for `delay` seconds
loop {
match rx.recv_timeout(Duration::from_secs(conf.delay)) {
Ok(_) => {
// Got another event, continue waiting
continue;
}
Err(mpsc::RecvTimeoutError::Timeout) => {
// No events for `delay` seconds, perform commit
tracing::info!(
"edited and {} secs past; save current contents of {} to branch {}",
conf.delay,
path.display(),
&conf.branch,
);
if let Ok(repo) = GitRepo::new(&path)
&& let Err(e) = repo.save(
conf.branch.clone(),
conf.commit_message.clone(),
conf.merge_message.clone(),
)
{
tracing::error!("{e}");
}
break;
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
// Channel closed, exit
tracing::debug!("channel closed");
return;
}
}
}
}
}
impl RepoWatcher {
/// Create new watcher in specified path, specified configuration
pub fn new(path: impl AsRef<Path>, conf: Config) -> anyhow::Result<Self> {
let path_buf = path.as_ref().to_path_buf();
// Create channel for debouncing
let (tx, rx) = mpsc::channel();
// Spawn single debounce worker thread
let debounce_thread = {
let path = path_buf.clone();
thread::spawn(move || {
debounce_worker(rx, path, conf);
})
};
let mut watcher =
recommended_watcher(move |result: Result<notify::Event, notify::Error>| {
if let Ok(ev) = result
&& (ev.kind.is_create() || ev.kind.is_modify() || ev.kind.is_remove())
{
// Just send signal to debounce worker, ignore send errors
if let Err(e) = tx.send(ev).context("send file change event error") {
tracing::warn!("{e:?}");
}
}
})
.context("Watcher create error")?;
watcher
.watch(path.as_ref(), RecursiveMode::Recursive)
.context("Watch start error")?;
tracing::info!("Start watching: {}", &path.as_ref().display());
Ok(Self {
watcher,
debounce_thread,
})
}
}