diff --git a/src/bin/mdbook.rs b/src/bin/mdbook.rs index 50b9a2e2..357a0efb 100644 --- a/src/bin/mdbook.rs +++ b/src/bin/mdbook.rs @@ -94,7 +94,7 @@ fn init(args: &ArgMatches) -> Result<(), Box> { // If flag `--theme` is present, copy theme to src if args.is_present("theme") { - // Skip this id `--force` is present + // Skip this if `--force` is present if !args.is_present("force") { // Print warning print!("\nCopying the default theme to {:?}", book.get_src()); @@ -115,6 +115,22 @@ fn init(args: &ArgMatches) -> Result<(), Box> { } + // Because of `src/book/mdbook.rs#L37-L39`, the following will always evaluate to `true` + let is_dest_inside_root = book.get_dest().starts_with(book.get_root()); + + if !args.is_present("force") && is_dest_inside_root { + let gitignore = book.get_dest().join(".gitignore"); + println!("\nCreating default .gitignore at {:?}", gitignore); + print!("\nAre you sure you want to continue? (y/n) "); + + if confirm() { + book.create_gitignore(); + println!("\n.gitignore created."); + } else { + println!("\nSkipping...\n"); + } + } + println!("\nAll done, no errors..."); Ok(()) diff --git a/src/book/mdbook.rs b/src/book/mdbook.rs index db27830f..41038d70 100644 --- a/src/book/mdbook.rs +++ b/src/book/mdbook.rs @@ -160,12 +160,37 @@ impl MDBook { Ok(()) } + pub fn create_gitignore(&self) { + let gitignore = self.get_gitignore(); + + if !gitignore.exists() { + // Gitignore does not exist, create it + + debug!("[*]: {:?} does not exist, trying to create .gitignore", gitignore); + + let mut f = File::create(&gitignore) + .expect("Could not create file."); + + debug!("[*]: Writing to .gitignore"); + + writeln!(f, "# Ignore everything within this folder") + .expect("Could not write to file."); + writeln!(f, "*") + .expect("Could not write to file."); + writeln!(f, "") + .expect("Could not write to file."); + writeln!(f, "# Except this file") + .expect("Could not write to file."); + writeln!(f, "!.gitignore") + .expect("Could not write to file."); + } + } + /// The `build()` method is the one where everything happens. First it parses `SUMMARY.md` to /// construct the book's structure in the form of a `Vec` and then calls `render()` /// method of the current renderer. /// /// It is the renderer who generates all the output files. - pub fn build(&mut self) -> Result<(), Box> { debug!("[fn]: build"); @@ -180,6 +205,10 @@ impl MDBook { } + pub fn get_gitignore(&self) -> PathBuf { + self.config.get_dest().join(".gitignore") + } + pub fn copy_theme(&self) -> Result<(), Box> { debug!("[fn]: copy_theme"); @@ -297,6 +326,10 @@ impl MDBook { Ok(()) } + pub fn get_root(&self) -> &Path { + self.config.get_root() + } + pub fn set_dest(mut self, dest: &Path) -> Self { // Handle absolute and relative paths