Skip to content

Commit

Permalink
Merge pull request rust-lang#361 from Michael-F-Bryan/error-chain
Browse files Browse the repository at this point in the history
Add error-chain throughout the codebase
  • Loading branch information
azerupi committed Jun 26, 2017
2 parents 849aed4 + d798ad8 commit ea44eac
Show file tree
Hide file tree
Showing 11 changed files with 94 additions and 61 deletions.
21 changes: 21 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ matrix:
- nodejs
- os: linux
env: TARGET=x86_64-unknown-linux-musl CHANNEL=stable
dist: trusty
addons:
apt:
packages: &musl_packages
- musl
- musl-dev
- musl-tools
# Beta channel
- os: osx
env: TARGET=i686-apple-darwin CHANNEL=beta
Expand All @@ -42,6 +49,13 @@ matrix:
env: TARGET=x86_64-unknown-linux-gnu CHANNEL=beta
- os: linux
env: TARGET=x86_64-unknown-linux-musl CHANNEL=beta
dist: trusty
addons:
apt:
packages: &musl_packages
- musl
- musl-dev
- musl-tools
# Nightly channel
- os: osx
env: TARGET=i686-apple-darwin CHANNEL=nightly
Expand All @@ -56,6 +70,13 @@ matrix:
env: TARGET=x86_64-unknown-linux-gnu CHANNEL=nightly
- os: linux
env: TARGET=x86_64-unknown-linux-musl CHANNEL=nightly
dist: trusty
addons:
apt:
packages: &musl_packages
- musl
- musl-dev
- musl-tools

install:
- export PATH="$PATH:$HOME/.cargo/bin"
Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ clap = "2.24"
handlebars = "0.27"
serde = "1.0"
serde_derive = "1.0"
error-chain = "0.10.0"
serde_json = "1.0"
pulldown-cmark = "0.0.14"
log = "0.3"
Expand Down
14 changes: 7 additions & 7 deletions src/bin/mdbook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ extern crate time;
extern crate crossbeam;

use std::env;
use std::error::Error;
use std::ffi::OsStr;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use mdbook::errors::*;

use clap::{App, ArgMatches, SubCommand, AppSettings};

Expand Down Expand Up @@ -110,7 +110,7 @@ fn confirm() -> bool {


// Init command implementation
fn init(args: &ArgMatches) -> Result<(), Box<Error>> {
fn init(args: &ArgMatches) -> Result<()> {

let book_dir = get_book_dir(args);
let mut book = MDBook::new(&book_dir);
Expand Down Expand Up @@ -163,7 +163,7 @@ fn init(args: &ArgMatches) -> Result<(), Box<Error>> {


// Build command implementation
fn build(args: &ArgMatches) -> Result<(), Box<Error>> {
fn build(args: &ArgMatches) -> Result<()> {
let book_dir = get_book_dir(args);
let book = MDBook::new(&book_dir).read_config()?;

Expand Down Expand Up @@ -194,7 +194,7 @@ fn build(args: &ArgMatches) -> Result<(), Box<Error>> {

// Watch command implementation
#[cfg(feature = "watch")]
fn watch(args: &ArgMatches) -> Result<(), Box<Error>> {
fn watch(args: &ArgMatches) -> Result<()> {
let book_dir = get_book_dir(args);
let book = MDBook::new(&book_dir).read_config()?;

Expand Down Expand Up @@ -233,7 +233,7 @@ mod serve {

use std;
use std::path::Path;
use std::error::Error;
use mdbook::errors::*;
use self::iron::{Iron, AfterMiddleware, IronResult, IronError, Request, Response, status, Set, Chain};
use clap::ArgMatches;
use mdbook::MDBook;
Expand All @@ -253,7 +253,7 @@ mod serve {
}

// Watch command implementation
pub fn serve(args: &ArgMatches) -> Result<(), Box<Error>> {
pub fn serve(args: &ArgMatches) -> Result<()> {
const RELOAD_COMMAND: &'static str = "reload";

let book_dir = get_book_dir(args);
Expand Down Expand Up @@ -334,7 +334,7 @@ mod serve {
}
}

fn test(args: &ArgMatches) -> Result<(), Box<Error>> {
fn test(args: &ArgMatches) -> Result<()> {
let book_dir = get_book_dir(args);
let mut book = MDBook::new(&book_dir).read_config()?;

Expand Down
3 changes: 2 additions & 1 deletion src/book/bookitem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use serde::{Serialize, Serializer};
use serde::ser::SerializeStruct;
use std::path::PathBuf;


#[derive(Debug, Clone)]
pub enum BookItem {
Chapter(String, Chapter), // String = section
Expand Down Expand Up @@ -37,7 +38,7 @@ impl Chapter {


impl Serialize for Chapter {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
where S: Serializer
{
let mut struct_ = serializer.serialize_struct("Chapter", 2)?;
Expand Down
41 changes: 15 additions & 26 deletions src/book/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@ pub use self::bookitem::{BookItem, BookItems};

use std::path::{Path, PathBuf};
use std::fs::{self, File};
use std::error::Error;
use std::io;
use std::io::{Read, Write};
use std::io::ErrorKind;
use std::process::Command;

use {theme, parse, utils};
use renderer::{Renderer, HtmlHandlebars};
use errors::*;

use config::BookConfig;
use config::tomlconfig::TomlConfig;
Expand Down Expand Up @@ -129,7 +127,7 @@ impl MDBook {
/// and adds a `SUMMARY.md` and a
/// `chapter_1.md` to the source directory.

pub fn init(&mut self) -> Result<(), Box<Error>> {
pub fn init(&mut self) -> Result<()> {

debug!("[fn]: init");

Expand Down Expand Up @@ -239,7 +237,7 @@ impl MDBook {
/// method of the current renderer.
///
/// It is the renderer who generates all the output files.
pub fn build(&mut self) -> Result<(), Box<Error>> {
pub fn build(&mut self) -> Result<()> {
debug!("[fn]: build");

self.init()?;
Expand All @@ -249,17 +247,15 @@ impl MDBook {
utils::fs::remove_dir_content(htmlconfig.get_destination())?;
}

self.renderer.render(&self)?;

Ok(())
self.renderer.render(&self)
}


pub fn get_gitignore(&self) -> PathBuf {
self.config.get_root().join(".gitignore")
}

pub fn copy_theme(&self) -> Result<(), Box<Error>> {
pub fn copy_theme(&self) -> Result<()> {
debug!("[fn]: copy_theme");

if let Some(htmlconfig) = self.config.get_html_config() {
Expand Down Expand Up @@ -298,24 +294,22 @@ impl MDBook {
Ok(())
}

pub fn write_file<P: AsRef<Path>>(&self, filename: P, content: &[u8]) -> Result<(), Box<Error>> {
pub fn write_file<P: AsRef<Path>>(&self, filename: P, content: &[u8]) -> Result<()> {
let path = self.get_destination()
.ok_or(String::from("HtmlConfig not set, could not find a destination"))?
.join(filename);

utils::fs::create_file(&path)
.and_then(|mut file| file.write_all(content))
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Could not create {}: {}", path.display(), e)))?;

Ok(())
utils::fs::create_file(&path)?
.write_all(content)
.map_err(|e| e.into())
}

/// Parses the `book.json` file (if it exists) to extract
/// the configuration parameters.
/// The `book.json` file should be in the root directory of the book.
/// The root directory is the one specified when creating a new `MDBook`

pub fn read_config(mut self) -> Result<Self, Box<Error>> {
pub fn read_config(mut self) -> Result<Self> {

let toml = self.get_root().join("book.toml");
let json = self.get_root().join("book.json");
Expand Down Expand Up @@ -369,9 +363,9 @@ impl MDBook {
self
}

pub fn test(&mut self) -> Result<(), Box<Error>> {
pub fn test(&mut self) -> Result<()> {
// read in the chapters
self.parse_summary()?;
self.parse_summary().chain_err(|| "Couldn't parse summary")?;
for item in self.iter() {

if let BookItem::Chapter(_, ref ch) = *item {
Expand All @@ -381,15 +375,10 @@ impl MDBook {

println!("[*]: Testing file: {:?}", path);

let output_result = Command::new("rustdoc").arg(&path).arg("--test").output();
let output = output_result?;
let output = Command::new("rustdoc").arg(&path).arg("--test").output()?;

if !output.status.success() {
return Err(Box::new(io::Error::new(ErrorKind::Other,
format!("{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)))) as
Box<Error>);
bail!(ErrorKind::Subprocess("Rustdoc returned an error".to_string(), output));
}
}
}
Expand Down Expand Up @@ -556,7 +545,7 @@ impl MDBook {
}

// Construct book
fn parse_summary(&mut self) -> Result<(), Box<Error>> {
fn parse_summary(&mut self) -> Result<()> {
// When append becomes stable, use self.content.append() ...
self.content = parse::construct_bookitems(&self.get_source().join("SUMMARY.md"))?;
Ok(())
Expand Down
5 changes: 3 additions & 2 deletions src/config/jsonconfig.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
extern crate serde_json;
use std::path::PathBuf;
use errors::*;

/// The JSON configuration is **deprecated** and will be removed in the near future.
/// Please migrate to the TOML configuration.
Expand Down Expand Up @@ -32,9 +33,9 @@ pub struct JsonConfig {
/// assert_eq!(config.dest, Some(PathBuf::from("htmlbook")));
/// ```
impl JsonConfig {
pub fn from_json(input: &str) -> Result<Self, String> {
pub fn from_json(input: &str) -> Result<Self> {
let config: JsonConfig = serde_json::from_str(input)
.map_err(|e| format!("Could not parse JSON: {}", e))?;
.chain_err(|| format!("Could not parse JSON"))?;

return Ok(config);
}
Expand Down
5 changes: 3 additions & 2 deletions src/config/tomlconfig.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
extern crate toml;
use std::path::PathBuf;
use errors::*;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TomlConfig {
Expand Down Expand Up @@ -44,9 +45,9 @@ pub struct TomlHtmlConfig {
/// assert_eq!(config.output.unwrap().html.unwrap().destination, Some(PathBuf::from("htmlbook")));
/// ```
impl TomlConfig {
pub fn from_toml(input: &str) -> Result<Self, String> {
pub fn from_toml(input: &str) -> Result<Self> {
let config: TomlConfig = toml::from_str(input)
.map_err(|e| format!("Could not parse TOML: {}", e))?;
.chain_err(|| "Could not parse TOML")?;

return Ok(config);
}
Expand Down
23 changes: 22 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,13 @@
//!
//! Make sure to take a look at it.

#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate serde_derive;
extern crate serde;
#[macro_use] extern crate serde_json;
#[macro_use]
extern crate serde_json;

extern crate handlebars;
extern crate pulldown_cmark;
Expand All @@ -90,3 +93,21 @@ pub mod utils;
pub use book::MDBook;
pub use book::BookItem;
pub use renderer::Renderer;

/// The error types used through out this crate.
pub mod errors {
error_chain!{
foreign_links {
Io(::std::io::Error);
HandlebarsRender(::handlebars::RenderError);
HandlebarsTemplate(::handlebars::TemplateError);
Utf8(::std::string::FromUtf8Error);
}

errors {
Subprocess(message: String, output: ::std::process::Output) {
description("A subprocess failed")
}
}
}
}
Loading

0 comments on commit ea44eac

Please sign in to comment.