Debian Codegraph @

src/cmd/watch.rs

raw
1 use super::command_prelude::*;
2 use crate::{get_book_dir, open};
3 use anyhow::Result;
4 use mdbook_driver::MDBook;
5 use std::path::{Path, PathBuf};
6 use tracing::error;
7
8 mod native;
9 mod poller;
10
11 // Create clap subcommand arguments
12 pub fn make_subcommand() -> Command {
13 Command::new("watch")
14 .about("Watches a book's files and rebuilds it on changes")
15 .arg_dest_dir()
16 .arg_root_dir()
17 .arg_open()
18 .arg_watcher()
19 }
20
21 pub enum WatcherKind {
22 Poll,
23 Native,
24 }
25
26 impl WatcherKind {
27 pub fn from_str(s: &str) -> WatcherKind {
28 match s {
29 "poll" => WatcherKind::Poll,
30 "native" => WatcherKind::Native,
31 _ => panic!("unsupported watcher {s}"),
32 }
33 }
34 }
35
36 // Watch command implementation
37 pub fn execute(args: &ArgMatches) -> Result<()> {
38 let book_dir = get_book_dir(args);
39 let mut book = MDBook::load(&book_dir)?;
40
41 let update_config = |book: &mut MDBook| {
42 set_dest_dir(args, book);
43 };
44 update_config(&mut book);
45
46 if args.get_flag("open") {
47 book.build()?;
48 let path = book.build_dir_for("html").join("index.html");
49 if !path.exists() {
50 error!("No chapter available to open");
51 std::process::exit(1)
52 }
53 open(path);
54 }
55
56 let watcher = WatcherKind::from_str(args.get_one::<String>("watcher").unwrap());
57 rebuild_on_change(watcher, &book_dir, &update_config, &|| {});
58
59 Ok(())
60 }
61
62 pub fn rebuild_on_change(
63 kind: WatcherKind,
64 book_dir: &Path,
65 update_config: &dyn Fn(&mut MDBook),
66 post_build: &dyn Fn(),
67 ) {
68 match kind {
69 WatcherKind::Poll => self::poller::rebuild_on_change(book_dir, update_config, post_build),
70 WatcherKind::Native => self::native::rebuild_on_change(book_dir, update_config, post_build),
71 }
72 }
73
74 fn find_gitignore(book_root: &Path) -> Option<PathBuf> {
75 book_root
76 .ancestors()
77 .map(|p| p.join(".gitignore"))
78 .find(|p| p.exists())
79 }