Debian Codegraph @

src/cmd/init.rs

raw
1 use crate::get_book_dir;
2 use anyhow::Result;
3 use clap::{ArgMatches, Command as ClapCommand, arg};
4 use mdbook_core::config;
5 use mdbook_driver::MDBook;
6 use std::io;
7 use std::io::Write;
8 use std::process::Command;
9 use tracing::debug;
10
11 // Create clap subcommand arguments
12 pub fn make_subcommand() -> ClapCommand {
13 ClapCommand::new("init")
14 .about("Creates the boilerplate structure and files for a new book")
15 .arg(
16 arg!([dir]
17 "Directory to create the book in\n\
18 (Defaults to the current directory when omitted)"
19 )
20 .value_parser(clap::value_parser!(std::path::PathBuf)),
21 )
22 .arg(arg!(--theme "Copies the default theme into your source folder"))
23 .arg(arg!(--force "Skips confirmation prompts"))
24 .arg(arg!(--title <title> "Sets the book title"))
25 .arg(
26 arg!(--ignore <ignore> "Creates a VCS ignore file (i.e. .gitignore)")
27 .value_parser(["none", "git"]),
28 )
29 }
30
31 // Init command implementation
32 pub fn execute(args: &ArgMatches) -> Result<()> {
33 let book_dir = get_book_dir(args);
34 let mut builder = MDBook::init(&book_dir);
35 let mut config = config::Config::default();
36 // If flag `--theme` is present, copy theme to src
37 if args.get_flag("theme") {
38 let theme_dir = book_dir.join("theme");
39 println!();
40 println!("Copying the default theme to {}", theme_dir.display());
41 // Skip this if `--force` is present
42 if !args.get_flag("force") && theme_dir.exists() {
43 println!("This could potentially overwrite files already present in that directory.");
44 print!("\nAre you sure you want to continue? (y/n) ");
45
46 // Read answer from user and exit if it's not 'yes'
47 if confirm() {
48 builder.copy_theme(true);
49 }
50 } else {
51 builder.copy_theme(true);
52 }
53 }
54
55 if let Some(ignore) = args.get_one::<String>("ignore").map(|s| s.as_str()) {
56 match ignore {
57 "git" => builder.create_gitignore(true),
58 _ => builder.create_gitignore(false),
59 };
60 } else if !args.get_flag("force") {
61 println!("\nDo you want a .gitignore to be created? (y/n)");
62 if confirm() {
63 builder.create_gitignore(true);
64 }
65 }
66
67 config.book.title = if args.contains_id("title") {
68 args.get_one::<String>("title").map(String::from)
69 } else if args.get_flag("force") {
70 None
71 } else {
72 request_book_title()
73 };
74
75 if let Some(author) = get_author_name() {
76 debug!("Obtained user name from gitconfig: {:?}", author);
77 config.book.authors.push(author);
78 }
79
80 builder.with_config(config);
81 builder.build()?;
82 println!("\nAll done, no errors...");
83
84 Ok(())
85 }
86
87 /// Obtains author name from git config file by running the `git config` command.
88 fn get_author_name() -> Option<String> {
89 let output = Command::new("git")
90 .args(["config", "--get", "user.name"])
91 .output()
92 .ok()?;
93
94 if output.status.success() {
95 Some(String::from_utf8_lossy(&output.stdout).trim().to_owned())
96 } else {
97 None
98 }
99 }
100
101 /// Request book title from user and return if provided.
102 fn request_book_title() -> Option<String> {
103 println!("What title would you like to give the book? ");
104 io::stdout().flush().unwrap();
105 let mut resp = String::new();
106 io::stdin().read_line(&mut resp).unwrap();
107 let resp = resp.trim();
108 if resp.is_empty() {
109 None
110 } else {
111 Some(resp.into())
112 }
113 }
114
115 // Simple function for user confirmation
116 fn confirm() -> bool {
117 io::stdout().flush().unwrap();
118 let mut s = String::new();
119 io::stdin().read_line(&mut s).ok();
120 matches!(s.trim(), "Y" | "y" | "yes" | "Yes")
121 }