Debian Codegraph @

src/cmd/watch/native.rs

raw
1 //! A filesystem watcher using native operating system facilities.
2
3 use ignore::gitignore::Gitignore;
4 use mdbook_driver::MDBook;
5 use std::path::{Path, PathBuf};
6 use std::sync::mpsc::channel;
7 use std::thread::sleep;
8 use std::time::Duration;
9 use tracing::{error, info, warn};
10
11 pub fn rebuild_on_change(
12 book_dir: &Path,
13 update_config: &dyn Fn(&mut MDBook),
14 post_build: &dyn Fn(),
15 ) {
16 use notify::RecursiveMode::*;
17
18 let mut book = MDBook::load(book_dir).unwrap_or_else(|e| {
19 error!("failed to load book: {e}");
20 std::process::exit(1);
21 });
22
23 // Create a channel to receive the events.
24 let (tx, rx) = channel();
25
26 let mut debouncer = match notify_debouncer_mini::new_debouncer(Duration::from_secs(1), tx) {
27 Ok(d) => d,
28 Err(e) => {
29 error!("Error while trying to watch the files:\n\n\t{:?}", e);
30 std::process::exit(1)
31 }
32 };
33 let watcher = debouncer.watcher();
34
35 // Add the source directory to the watcher
36 if let Err(e) = watcher.watch(&book.source_dir(), Recursive) {
37 error!("Error while watching {:?}:\n {:?}", book.source_dir(), e);
38 std::process::exit(1);
39 };
40
41 let _ = watcher.watch(&book.theme_dir(), Recursive);
42
43 // Add the book.toml file to the watcher if it exists
44 let _ = watcher.watch(&book.root.join("book.toml"), NonRecursive);
45
46 for dir in &book.config.build.extra_watch_dirs {
47 let path = book.root.join(dir);
48 let canonical_path = path.canonicalize().unwrap_or_else(|e| {
49 error!("Error while watching extra directory {path:?}:\n {e}");
50 std::process::exit(1);
51 });
52
53 if let Err(e) = watcher.watch(&canonical_path, Recursive) {
54 error!(
55 "Error while watching extra directory {:?}:\n {:?}",
56 canonical_path, e
57 );
58 std::process::exit(1);
59 }
60 }
61
62 info!("Listening for changes...");
63
64 loop {
65 let first_event = rx.recv().unwrap();
66 sleep(Duration::from_millis(50));
67 let other_events = rx.try_iter();
68
69 let all_events = std::iter::once(first_event).chain(other_events);
70
71 let paths: Vec<_> = all_events
72 .filter_map(|event| match event {
73 Ok(events) => Some(events),
74 Err(error) => {
75 warn!("error while watching for changes: {error}");
76 None
77 }
78 })
79 .flatten()
80 .map(|event| event.path)
81 .collect();
82
83 // If we are watching files outside the current repository (via extra-watch-dirs), then they are definitionally
84 // ignored by gitignore. So we handle this case by including such files into the watched paths list.
85 let any_external_paths = paths.iter().filter(|p| !p.starts_with(&book.root)).cloned();
86 let mut paths = remove_ignored_files(&book.root, &paths[..]);
87 paths.extend(any_external_paths);
88
89 if !paths.is_empty() {
90 info!("Files changed: {paths:?}");
91 match MDBook::load(book_dir) {
92 Ok(mut b) => {
93 update_config(&mut b);
94 if let Err(e) = b.build() {
95 error!("failed to build the book: {e:?}");
96 } else {
97 post_build();
98 }
99 book = b;
100 }
101 Err(e) => error!("failed to load book config: {e:?}"),
102 }
103 }
104 }
105 }
106
107 fn remove_ignored_files(book_root: &Path, paths: &[PathBuf]) -> Vec<PathBuf> {
108 if paths.is_empty() {
109 return vec![];
110 }
111
112 match super::find_gitignore(book_root) {
113 Some(gitignore_path) => {
114 let (ignore, err) = Gitignore::new(&gitignore_path);
115 if let Some(err) = err {
116 warn!(
117 "error reading gitignore `{}`: {err}",
118 gitignore_path.display()
119 );
120 }
121 filter_ignored_files(ignore, paths)
122 }
123 None => {
124 // There is no .gitignore file.
125 paths.iter().map(|path| path.to_path_buf()).collect()
126 }
127 }
128 }
129
130 // Note: The usage of `canonicalize` may encounter occasional failures on the Windows platform, presenting a potential risk.
131 // For more details, refer to [Pull Request #2229](https://github.com/rust-lang/mdBook/pull/2229#discussion_r1408665981).
132 fn filter_ignored_files(ignore: Gitignore, paths: &[PathBuf]) -> Vec<PathBuf> {
133 let ignore_root = ignore
134 .path()
135 .canonicalize()
136 .expect("ignore root canonicalize error");
137
138 paths
139 .iter()
140 .filter(|path| {
141 let relative_path = pathdiff::diff_paths(&path, &ignore_root)
142 .expect("One of the paths should be an absolute");
143 !ignore
144 .matched_path_or_any_parents(&relative_path, relative_path.is_dir())
145 .is_ignore()
146 })
147 .map(|path| path.to_path_buf())
148 .collect()
149 }
150
151 #[cfg(test)]
152 mod tests {
153 use super::*;
154 use ignore::gitignore::GitignoreBuilder;
155 use std::env;
156
157 #[test]
158 fn test_filter_ignored_files() {
159 let current_dir = env::current_dir().unwrap();
160
161 let ignore = GitignoreBuilder::new(&current_dir)
162 .add_line(None, "*.html")
163 .unwrap()
164 .build()
165 .unwrap();
166 let should_remain = current_dir.join("record.text");
167 let should_filter = current_dir.join("index.html");
168
169 let remain = filter_ignored_files(ignore, &[should_remain.clone(), should_filter]);
170 assert_eq!(remain, vec![should_remain])
171 }
172
173 #[test]
174 fn filter_ignored_files_should_handle_parent_dir() {
175 let current_dir = env::current_dir().unwrap();
176
177 let ignore = GitignoreBuilder::new(&current_dir)
178 .add_line(None, "*.html")
179 .unwrap()
180 .build()
181 .unwrap();
182
183 let parent_dir = current_dir.join("..");
184 let should_remain = parent_dir.join("record.text");
185 let should_filter = parent_dir.join("index.html");
186
187 let remain = filter_ignored_files(ignore, &[should_remain.clone(), should_filter]);
188 assert_eq!(remain, vec![should_remain])
189 }
190 }