Skip to content

Commit

Permalink
Big clean-up, reduced the unwrap's to 2 in the library part! Closes #36
Browse files Browse the repository at this point in the history
… The unwraps where replaced with more diverse error messages #14
  • Loading branch information
azerupi committed Aug 11, 2015
1 parent b6034e8 commit 0932bfd
Show file tree
Hide file tree
Showing 6 changed files with 166 additions and 75 deletions.
2 changes: 1 addition & 1 deletion book-example/src/cli/init.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ by appending a path to the command:
mdbook init path/to/book
```

#### --theme
## --theme

When you use the `--theme` argument, the default theme will be copied into a directory
called `theme` in your source directory so that you can modify it.
Expand Down
58 changes: 39 additions & 19 deletions src/book/bookconfig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use std::path::{Path, PathBuf};
pub struct BookConfig {
pub title: String,
pub author: String,
root: PathBuf,
dest: PathBuf,
src: PathBuf,
pub indent_spaces: i32,
Expand All @@ -16,10 +17,11 @@ pub struct BookConfig {


impl BookConfig {
pub fn new() -> Self {
pub fn new(root: &Path) -> Self {
BookConfig {
title: String::new(),
author: String::new(),
root: root.to_owned(),
dest: PathBuf::from("book"),
src: PathBuf::from("src"),
indent_spaces: 4, // indentation used for SUMMARY.md
Expand All @@ -42,32 +44,50 @@ impl BookConfig {

debug!("[*]: Reading config");
let mut data = String::new();
config_file.read_to_string(&mut data).unwrap();

// Convert to JSON
let config = Json::from_str(&data).unwrap();

// Extract data

debug!("[*]: Extracting data from config");
// Title & author
if let Some(a) = config.find_path(&["title"]) { self.title = a.to_string().replace("\"", "") }
if let Some(a) = config.find_path(&["author"]) { self.author = a.to_string().replace("\"", "") }

// Destination
if let Some(a) = config.find_path(&["dest"]) {
let dest = PathBuf::from(&a.to_string().replace("\"", ""));
// Just return if an error occured.
// I would like to propagate the error, but I have to return `&self`
match config_file.read_to_string(&mut data) {
Err(_) => return self,
_ => {},
}

// If path is relative make it absolute from the parent directory of src
if dest.is_relative() {
let dest = &self.get_src().parent().unwrap().join(&dest);
self.set_dest(dest);
// Convert to JSON
if let Ok(config) = Json::from_str(&data) {
// Extract data

debug!("[*]: Extracting data from config");
// Title & author
if let Some(a) = config.find_path(&["title"]) { self.title = a.to_string().replace("\"", "") }
if let Some(a) = config.find_path(&["author"]) { self.author = a.to_string().replace("\"", "") }

// Destination
if let Some(a) = config.find_path(&["dest"]) {
let dest = PathBuf::from(&a.to_string().replace("\"", ""));

// If path is relative make it absolute from the parent directory of src
match dest.is_relative() {
true => {
let dest = self.get_root().join(&dest).to_owned();
self.set_dest(&dest);
},
false => { self.set_dest(&dest); },
}
}
}

self
}

pub fn get_root(&self) -> &Path {
&self.root
}

pub fn set_root(&mut self, root: &Path) -> &mut Self {
self.root = root.to_owned();
self
}

pub fn get_dest(&self) -> &Path {
&self.dest
}
Expand Down
41 changes: 29 additions & 12 deletions src/book/mdbook.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::path::{Path, PathBuf};
use std::path::Path;
use std::fs::{self, File, metadata};
use std::io::Write;
use std::error::Error;
Expand All @@ -12,7 +12,6 @@ use renderer::HtmlHandlebars;

pub struct MDBook {
config: BookConfig,
pub root: PathBuf,
pub content: Vec<BookItem>,
renderer: Box<Renderer>,
}
Expand All @@ -39,9 +38,8 @@ impl MDBook {
}

MDBook {
root: root.to_path_buf(),
content: vec![],
config: BookConfig::new()
config: BookConfig::new(root)
.set_src(&root.join("src"))
.set_dest(&root.join("book"))
.to_owned(),
Expand Down Expand Up @@ -106,7 +104,7 @@ impl MDBook {
// There is a very high chance that the error is due to the fact that
// the directory / file does not exist
debug!("[*]: {:?} does not exist, trying to create directory", dest);
fs::create_dir(&dest).unwrap();
try!(fs::create_dir(&dest));
},
Ok(_) => { /* If there is no error, the directory / file does exist */ }
}
Expand All @@ -117,7 +115,7 @@ impl MDBook {
// There is a very high chance that the error is due to the fact that
// the directory / file does not exist
debug!("[*]: {:?} does not exist, trying to create directory", src);
fs::create_dir(&src).unwrap();
try!(fs::create_dir(&src));
},
Ok(_) => { /* If there is no error, the directory / file does exist */ }
}
Expand All @@ -128,7 +126,7 @@ impl MDBook {
// There is a very high chance that the error is due to the fact that
// the directory / file does not exist
debug!("[*]: {:?} does not exist, trying to create SUMMARY.md", src.join("SUMMARY.md"));
Ok(File::create(&src.join("SUMMARY.md")).unwrap())
Ok(try!(File::create(&src.join("SUMMARY.md"))))
},
Ok(_) => {
/* If there is no error, the directory / file does exist */
Expand All @@ -143,7 +141,7 @@ impl MDBook {
try!(writeln!(f, ""));
try!(writeln!(f, "- [Chapter 1](./chapter_1.md)"));

let mut chapter_1 = File::create(&src.join("chapter_1.md")).unwrap();
let mut chapter_1 = try!(File::create(&src.join("chapter_1.md")));
try!(writeln!(chapter_1, "# Chapter 1"));
}

Expand Down Expand Up @@ -181,7 +179,7 @@ impl MDBook {
// There is a very high chance that the error is due to the fact that
// the directory / file does not exist
debug!("[*]: {:?} does not exist, trying to create directory", theme_dir);
fs::create_dir(&theme_dir).unwrap();
try!(fs::create_dir(&theme_dir));
},
Ok(_) => { /* If there is no error, the directory / file does exist */ }
}
Expand Down Expand Up @@ -226,7 +224,8 @@ impl MDBook {
/// of the current working directory by using a relative path instead of an absolute path.

pub fn read_config(mut self) -> Self {
self.config.read_config(&self.root);
let root = self.config.get_root().to_owned();
self.config.read_config(&root);
self
}

Expand Down Expand Up @@ -256,7 +255,16 @@ impl MDBook {
}

pub fn set_dest(mut self, dest: &Path) -> Self {
self.config.set_dest(&self.root.join(dest));

// Handle absolute and relative paths
match dest.is_absolute() {
true => { self.config.set_dest(dest); },
false => {
let dest = self.config.get_root().join(dest).to_owned();
self.config.set_dest(&dest);
}
}

self
}

Expand All @@ -265,7 +273,16 @@ impl MDBook {
}

pub fn set_src(mut self, src: &Path) -> Self {
self.config.set_src(&self.root.join(src));

// Handle absolute and relative paths
match src.is_absolute() {
true => { self.config.set_src(src); },
false => {
let src = self.config.get_root().join(src).to_owned();
self.config.set_src(&src);
}
}

self
}

Expand Down
11 changes: 9 additions & 2 deletions src/renderer/html_handlebars/hbs_renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,11 @@ impl Renderer for HtmlHandlebars {

// Remove content from previous file and render content for this one
data.remove("path");
data.insert("path".to_string(), item.path.to_str().unwrap().to_json());
match item.path.to_str() {
Some(p) => { data.insert("path".to_string(), p.to_json()); },
None => return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not convert path to str"))),
}


// Remove content from previous file and render content for this one
data.remove("content");
Expand Down Expand Up @@ -144,7 +148,10 @@ fn make_data(book: BookItems, config: &BookConfig) -> Result<BTreeMap<String,Jso
let mut chapter = BTreeMap::new();
chapter.insert("section".to_string(), section.to_json());
chapter.insert("name".to_string(), item.name.to_json());
chapter.insert("path".to_string(), item.path.to_str().unwrap().to_json());
match item.path.to_str() {
Some(p) => { chapter.insert("path".to_string(), p.to_json()); },
None => return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Could not convert path to str"))),
}

chapters.push(chapter);
}
Expand Down
Loading

0 comments on commit 0932bfd

Please sign in to comment.