mdbook/src/cmd/watch.rs

81 lines
2 KiB
Rust
Raw Normal View History

2022-07-04 23:16:31 +08:00
use super::command_prelude::*;
use crate::{get_book_dir, open};
use mdbook::errors::Result;
2018-07-23 12:45:01 -05:00
use mdbook::MDBook;
use std::path::{Path, PathBuf};
2024-02-24 13:35:39 -08:00
mod native;
mod poller;
// Create clap subcommand arguments
2022-07-04 23:16:31 +08:00
pub fn make_subcommand() -> Command {
Command::new("watch")
2018-08-02 15:48:22 -05:00
.about("Watches a book's files and rebuilds it on changes")
2022-07-04 23:16:31 +08:00
.arg_dest_dir()
.arg_root_dir()
.arg_open()
2024-02-24 13:35:39 -08:00
.arg_watcher()
}
pub enum WatcherKind {
Poll,
Native,
}
impl WatcherKind {
pub fn from_str(s: &str) -> WatcherKind {
match s {
"poll" => WatcherKind::Poll,
"native" => WatcherKind::Native,
_ => panic!("unsupported watcher {s}"),
}
}
}
// Watch command implementation
pub fn execute(args: &ArgMatches) -> Result<()> {
let book_dir = get_book_dir(args);
2024-02-24 13:35:39 -08:00
let mut book = MDBook::load(&book_dir)?;
2020-05-17 11:04:29 -07:00
let update_config = |book: &mut MDBook| {
2022-07-04 23:16:31 +08:00
if let Some(dest_dir) = args.get_one::<PathBuf>("dest-dir") {
2020-05-17 11:04:29 -07:00
book.config.build.build_dir = dest_dir.into();
}
};
update_config(&mut book);
2022-07-04 23:16:31 +08:00
if args.get_flag("open") {
book.build()?;
let path = book.build_dir_for("html").join("index.html");
if !path.exists() {
error!("No chapter available to open");
std::process::exit(1)
2022-05-10 11:19:23 -07:00
}
open(path);
}
2024-02-24 13:35:39 -08:00
let watcher = WatcherKind::from_str(args.get_one::<String>("watcher").unwrap());
rebuild_on_change(watcher, &book_dir, &update_config, &|| {});
Ok(())
}
2024-02-24 13:35:39 -08:00
pub fn rebuild_on_change(
kind: WatcherKind,
book_dir: &Path,
update_config: &dyn Fn(&mut MDBook),
post_build: &dyn Fn(),
) {
match kind {
WatcherKind::Poll => self::poller::rebuild_on_change(book_dir, update_config, post_build),
WatcherKind::Native => self::native::rebuild_on_change(book_dir, update_config, post_build),
}
}
2021-05-31 20:27:52 -07:00
fn find_gitignore(book_root: &Path) -> Option<PathBuf> {
book_root
.ancestors()
.map(|p| p.join(".gitignore"))
.find(|p| p.exists())
}