Debian Codegraph @

src/main.rs

raw
1 //! The mdbook CLI.
2
3 #![allow(unreachable_pub, reason = "not needed in a bin crate")]
4
5 use anyhow::anyhow;
6 use clap::{Arg, ArgMatches, Command};
7 use clap_complete::Shell;
8 use mdbook_core::utils;
9 use std::env;
10 use std::ffi::OsStr;
11 use std::path::PathBuf;
12 use tracing::{error, info};
13
14 mod cmd;
15
16 const VERSION: &str = concat!("v", clap::crate_version!());
17
18 fn main() {
19 init_logger();
20
21 let command = create_clap_command();
22
23 // Check which subcommand the user ran...
24 let res = match command.get_matches().subcommand() {
25 Some(("init", sub_matches)) => cmd::init::execute(sub_matches),
26 Some(("build", sub_matches)) => cmd::build::execute(sub_matches),
27 Some(("clean", sub_matches)) => cmd::clean::execute(sub_matches),
28 #[cfg(feature = "watch")]
29 Some(("watch", sub_matches)) => cmd::watch::execute(sub_matches),
30 #[cfg(feature = "serve")]
31 Some(("serve", sub_matches)) => cmd::serve::execute(sub_matches),
32 Some(("test", sub_matches)) => cmd::test::execute(sub_matches),
33 Some(("completions", sub_matches)) => (|| {
34 let shell = sub_matches
35 .get_one::<Shell>("shell")
36 .ok_or_else(|| anyhow!("Shell name missing."))?;
37
38 let mut complete_app = create_clap_command();
39 clap_complete::generate(
40 *shell,
41 &mut complete_app,
42 "mdbook",
43 &mut std::io::stdout().lock(),
44 );
45 Ok(())
46 })(),
47 _ => unreachable!(),
48 };
49
50 if let Err(e) = res {
51 utils::log_backtrace(&e);
52
53 std::process::exit(101);
54 }
55 }
56
57 /// Create a list of valid arguments and sub-commands
58 fn create_clap_command() -> Command {
59 let app = Command::new(clap::crate_name!())
60 .about(clap::crate_description!())
61 .author("Mathieu David <[email protected]>")
62 .version(VERSION)
63 .propagate_version(true)
64 .arg_required_else_help(true)
65 .after_help(
66 "For more information about a specific command, try `mdbook <command> --help`\n\
67 The source code for mdBook is available at: https://github.com/rust-lang/mdBook",
68 )
69 .subcommand(cmd::init::make_subcommand())
70 .subcommand(cmd::build::make_subcommand())
71 .subcommand(cmd::test::make_subcommand())
72 .subcommand(cmd::clean::make_subcommand())
73 .subcommand(
74 Command::new("completions")
75 .about("Generate shell completions for your shell to stdout")
76 .arg(
77 Arg::new("shell")
78 .value_parser(clap::value_parser!(Shell))
79 .help("the shell to generate completions for")
80 .value_name("SHELL")
81 .required(true),
82 ),
83 );
84
85 #[cfg(feature = "watch")]
86 let app = app.subcommand(cmd::watch::make_subcommand());
87 #[cfg(feature = "serve")]
88 let app = app.subcommand(cmd::serve::make_subcommand());
89
90 app
91 }
92
93 fn init_logger() {
94 let filter = tracing_subscriber::EnvFilter::builder()
95 .with_env_var("MDBOOK_LOG")
96 .with_default_directive(tracing_subscriber::filter::LevelFilter::INFO.into())
97 .from_env_lossy();
98 let log_env = std::env::var("MDBOOK_LOG");
99 // Silence some particularly noisy dependencies unless the user
100 // specifically asks for them.
101 let silence_unless_specified = |filter: tracing_subscriber::EnvFilter, target| {
102 if !log_env.as_ref().map_or(false, |s| {
103 s.split(',').any(|directive| directive.starts_with(target))
104 }) {
105 filter.add_directive(format!("{target}=warn").parse().unwrap())
106 } else {
107 filter
108 }
109 };
110 let filter = silence_unless_specified(filter, "handlebars");
111 let filter = silence_unless_specified(filter, "html5ever");
112
113 // Don't show the target by default, since it generally isn't useful
114 // unless you are overriding the level.
115 let with_target = log_env.is_ok();
116
117 tracing_subscriber::fmt()
118 .without_time()
119 .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr()))
120 .with_writer(std::io::stderr)
121 .with_env_filter(filter)
122 .with_target(with_target)
123 .init();
124 }
125
126 fn get_book_dir(args: &ArgMatches) -> PathBuf {
127 if let Some(p) = args.get_one::<PathBuf>("dir") {
128 // Check if path is relative from current dir, or absolute...
129 if p.is_relative() {
130 env::current_dir().unwrap().join(p)
131 } else {
132 p.to_path_buf()
133 }
134 } else {
135 env::current_dir().expect("Unable to determine the current directory")
136 }
137 }
138
139 fn open<P: AsRef<OsStr>>(path: P) {
140 info!("Opening web browser");
141 if let Err(e) = opener::open(path) {
142 error!("Error opening web browser: {}", e);
143 }
144 }
145
146 #[test]
147 fn verify_app() {
148 create_clap_command().debug_assert();
149 }