2016-12-20 12:36:07 +01:00
|
|
|
// Copyright (C) 2016 Élisabeth HENRY.
|
|
|
|
//
|
|
|
|
// This file is part of Crowbook.
|
|
|
|
//
|
|
|
|
// Crowbook is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU Lesser General Public License as published
|
|
|
|
// by the Free Software Foundation, either version 2.1 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// Crowbook is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU Lesser General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Lesser General Public License
|
|
|
|
// along with Crowbook. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
use error::{Error, Result, Source};
|
|
|
|
use book::Book;
|
|
|
|
use std::io::Write;
|
|
|
|
use std::fs::File;
|
|
|
|
use std::path::Path;
|
|
|
|
|
|
|
|
/// Thait that must be implemented by the various renderers to render a whole book.
|
|
|
|
|
2016-12-20 13:16:24 +01:00
|
|
|
pub trait BookRenderer: Sync {
|
2017-07-14 15:21:18 +02:00
|
|
|
/// Path destination when output is set to auto
|
|
|
|
fn auto_path(&self, _book_file: &str) -> Result<String> {
|
|
|
|
Err(Error::default(Source::empty(),
|
|
|
|
lformat!("This renderer does not support the auto output")))
|
|
|
|
}
|
|
|
|
|
2016-12-20 12:36:07 +01:00
|
|
|
/// Render the book and write the result to the specified writer
|
2016-12-20 13:16:24 +01:00
|
|
|
fn render(&self, book: &Book, to: &mut Write) -> Result<()>;
|
2016-12-20 12:36:07 +01:00
|
|
|
|
|
|
|
/// Render the book to a given file.
|
|
|
|
///
|
|
|
|
/// The default implementation creates a file and calls `render` to write to it,
|
|
|
|
/// but in some cases it might be useful to override it.
|
2016-12-20 15:31:08 +01:00
|
|
|
fn render_to_file(&self, book: &Book, path: &Path) -> Result<()> {
|
2017-03-04 15:16:16 +01:00
|
|
|
// Not optimal but avoid creating an empty file if it fails
|
|
|
|
let mut content = vec![];
|
|
|
|
self.render(book, &mut content)?;
|
2016-12-20 12:36:07 +01:00
|
|
|
let mut file = File::create(path)
|
|
|
|
.map_err(|err| Error::default(Source::empty(),
|
|
|
|
lformat!("could not create file '{file}': {err}",
|
2016-12-20 15:31:08 +01:00
|
|
|
file = path.display(),
|
2016-12-20 12:36:07 +01:00
|
|
|
err = err)))?;
|
2017-03-04 15:16:16 +01:00
|
|
|
file.write_all(&content)
|
|
|
|
.map_err(|err| Error::default(Source::empty(),
|
|
|
|
lformat!("could not write book content to file '{file}': {err}",
|
|
|
|
file = path.display(),
|
|
|
|
err = err)))?;
|
2016-12-20 12:36:07 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|