use anyhow::{Context, Result};
use mdoc::{
utils::{get_author_name, write_file},
CONFIG_FILE,
};
use std::ffi::OsStr;
use std::path::PathBuf;
pub fn init(path: Option<PathBuf>) -> Result<()> {
let (root, title) = if let Some(path) = path {
(
path.clone(),
path.file_stem()
.unwrap_or_else(|| OsStr::new("Document title"))
.to_string_lossy()
.to_string(),
)
} else {
(PathBuf::from("."), "Document title".to_string())
};
std::fs::create_dir_all(&root.join("src"))
.context("Failed at creating the directory structure.")?;
let mut config = String::new();
config.push_str("# This is the configuration file of your document.\n");
config.push_str("# It is used to specify metadata, build instructions, styling and more.\n\n");
config.push_str(&format!("title = \"{title}\"\n"));
config.push_str("date = \"now\"\n");
if let Some(author) = get_author_name() {
config.push_str(&format!("authors = [\"{author}\"]\n"))
}
config.push_str("\n# For more options, visit https://kmaasrud.com/mdoc/config");
write_file(&root.join(CONFIG_FILE), config.as_bytes())
.context("Could not write configuration to file.")?;
mdoc::success!("Created a new document in {:?}.", root);
Ok(())
}