|
| 1 | +use crate::project_root; |
| 2 | +use std::{error::Error, process::Command}; |
| 3 | + |
| 4 | +pub fn run_book(task: &str) -> Result<(), Box<dyn Error>> { |
| 5 | + let args: &[&str] = if task == "serve" { &["--open"] } else { &[] }; |
| 6 | + |
| 7 | + execute_mdbook_command(task, args)?; |
| 8 | + |
| 9 | + Ok(()) |
| 10 | +} |
| 11 | + |
| 12 | +fn execute_mdbook_command(command: &str, additional_args: &[&str]) -> Result<(), Box<dyn Error>> { |
| 13 | + check_mdbook_version()?; |
| 14 | + |
| 15 | + let book_dest = project_root().join("book").to_str().unwrap().to_string(); |
| 16 | + |
| 17 | + let mut args = vec![command, "--dest-dir", &book_dest]; |
| 18 | + args.extend_from_slice(additional_args); |
| 19 | + |
| 20 | + let status = Command::new("mdbook") |
| 21 | + .current_dir(project_root()) |
| 22 | + .args(&args) |
| 23 | + .status()?; |
| 24 | + |
| 25 | + if !status.success() { |
| 26 | + return Err(format!("`mdbook {command}` failed to run successfully!").into()); |
| 27 | + } |
| 28 | + |
| 29 | + Ok(()) |
| 30 | +} |
| 31 | + |
| 32 | +fn check_mdbook_version() -> Result<(), Box<dyn Error>> { |
| 33 | + let required_version = "0.4.43"; |
| 34 | + |
| 35 | + let output = Command::new("mdbook").arg("--version").output()?; |
| 36 | + |
| 37 | + if !output.status.success() { |
| 38 | + println!("Error: `mdbook` not found. Please ensure it is installed!"); |
| 39 | + println!("You can install it using:"); |
| 40 | + println!(" cargo install mdbook@{required_version}"); |
| 41 | + return Err(Box::new(std::io::Error::new( |
| 42 | + std::io::ErrorKind::NotFound, |
| 43 | + "`mdbook` is not installed", |
| 44 | + ))); |
| 45 | + } |
| 46 | + |
| 47 | + let version_output = String::from_utf8_lossy(&output.stdout); |
| 48 | + let version_str = version_output.trim(); |
| 49 | + |
| 50 | + if !version_str.starts_with(&format!("mdbook {}", required_version)) { |
| 51 | + println!( |
| 52 | + "Warning: You are using version {version_str} of `mdbook`. Version {required_version} is required." |
| 53 | + ); |
| 54 | + println!( |
| 55 | + "Errors may occur if using a different version. Please install version {required_version}:" |
| 56 | + |
| 57 | + ); |
| 58 | + println!(" cargo install mdbook@{required_version}"); |
| 59 | + } |
| 60 | + |
| 61 | + Ok(()) |
| 62 | +} |
0 commit comments