Add exit codes; I sure hope no memory leaks happened

This commit is contained in:
Sofia 2018-04-18 21:06:02 +03:00
parent 208f1eb254
commit 1bad6a2309
5 changed files with 78 additions and 55 deletions

View File

@ -1,6 +1,6 @@
[website]
website_name = "TestWebsite"
built_pages = ["test_page/otus_test.toml"]
built_pages = ["test_page/about.toml", "test_page/other.toml"]
use_default_css = true
javascript = []
css = []

View File

@ -5,7 +5,7 @@ use template::Template;
use renderer;
use logger::{LogLevel, Logger};
use error::Error;
use options::BuildOps;
use options::{BuildOpt, Opt};
use file_writer;
const DEFAULT_CSS: &'static str = include_str!("templates/default-css.css");
@ -20,14 +20,14 @@ fn fetch_config() -> Result<Config, Error> {
}
}
pub fn build(logger: &Logger, ops: &BuildOps) -> Result<(), Error> {
pub fn build(logger: &Logger, opt: &Opt, _: &BuildOpt) -> Result<(), Error> {
logger.log(LogLevel::INFO, "Starting build");
let config = fetch_config()?;
if config.global_config.website.use_default_css {
let css_path = file_writer::add_to_beginning(PathBuf::from("css/default.css"), "public")?;
logger.log(LogLevel::DETAIL, format!("Adding {:?}", css_path));
file_writer::write_file(&css_path, DEFAULT_CSS, ops.overwrite)?;
file_writer::write_file(&css_path, DEFAULT_CSS, opt.overwrite)?;
}
logger.log(LogLevel::INFO, "Generating page templates");
@ -62,7 +62,7 @@ pub fn build(logger: &Logger, ops: &BuildOps) -> Result<(), Error> {
let html_path = file_writer::add_to_beginning(PathBuf::from(html_path), "public")?;
logger.log(LogLevel::DETAILER, format!("Writing {:?}", html_path));
if let Some(render) = renders.get(idx) {
file_writer::write_file(&html_path, render.clone(), ops.overwrite)?;
file_writer::write_file(&html_path, render.clone(), opt.overwrite)?;
} else {
return Err(Error::new(
LogLevel::SEVERE,

View File

@ -22,6 +22,7 @@ mod file_writer;
use std::collections::HashMap;
use std::path::PathBuf;
use std::process::exit;
use structopt::StructOpt;
@ -30,34 +31,49 @@ use options::{Opt, Subcommands};
use config_toml::{GlobalConfigToml, NavbarConfig, NavbarItem, WebsiteConfig};
fn main() {
exit(match run() {
Ok(()) => 0,
Err(()) => 1,
})
}
fn run() -> Result<(), ()> {
let opt = Opt::from_args();
let log_level = (3 - opt.quiet as i8 + opt.verbose as i8).max(0).min(5);
let logger = Logger::new(LogLevel::from(log_level as u8));
match opt.cmd {
Subcommands::Build(ops) => match builder::build(&logger, &ops) {
Ok(_) => logger.log(LogLevel::DETAILER, "Building finished successfully."),
match opt.clone().cmd {
Subcommands::Build(build_opt) => match builder::build(&logger, &opt, &build_opt) {
Ok(_) => {
logger.log(LogLevel::DETAILER, "Building finished successfully.");
Ok(())
}
Err(err) => {
logger.log(err.severity(), err.description());
logger.log(LogLevel::SEVERE, "Aborting building due to error.");
Err(())
}
},
Subcommands::New(ops) => match new_page::generate_new_page(ops, &logger) {
Ok(_) => logger.log(
LogLevel::DETAILER,
"Generating the new page finished successfully.",
),
Subcommands::New(new_opt) => match new_page::generate_new_page(&logger, &opt, &new_opt) {
Ok(_) => {
logger.log(
LogLevel::DETAILER,
"Generating the new page finished successfully.",
);
Ok(())
}
Err(err) => {
logger.log(err.severity(), err.description());
logger.log(LogLevel::SEVERE, "Aborting building due to error.");
Err(())
}
},
Subcommands::Initialize(ops) => {
Subcommands::Initialize(init_opt) => {
logger.log(LogLevel::DETAIL, "Generating config.toml");
let mut navbar = None;
if !ops.no_default_navbar {
if !init_opt.no_default_navbar {
let mut hashmap = HashMap::new();
hashmap.insert(
"test".to_owned(),
@ -83,28 +99,34 @@ fn main() {
let config = GlobalConfigToml {
website: WebsiteConfig {
website_name: ops.name,
website_name: init_opt.name,
built_pages: Vec::new(),
use_default_css: true,
javascript: Vec::new(),
css: Vec::new(),
favicon: ops.favicon,
favicon: init_opt.favicon,
before_navbar_url: None,
before_content_url: None,
after_content_url: None,
twitter_author: ops.twitter_author,
twitter_author: init_opt.twitter_author,
google_robots: None,
google_site_verification: None,
},
navbar: navbar,
};
match file_writer::write_toml(&PathBuf::from("config.toml"), &config, ops.overwrite) {
Ok(_) => logger.log(LogLevel::INFO, "Done!"),
Err(err) => logger.log(
err.severity(),
format!("Initialization failed: {}", err.description()),
),
match file_writer::write_toml(&PathBuf::from("config.toml"), &config, opt.overwrite) {
Ok(_) => {
logger.log(LogLevel::INFO, "Done!");
Ok(())
}
Err(err) => {
logger.log(
err.severity(),
format!("Initialization failed: {}", err.description()),
);
Err(())
}
}
}
}

View File

@ -1,6 +1,6 @@
use std::path::PathBuf;
use options::NewOps;
use options::{NewOpt, Opt};
use logger::{LogLevel, Logger};
use file_writer;
use error::Error;
@ -17,16 +17,16 @@ This is the markdown file, where you will insert this page's contents.
See [CommonMark](http://commonmark.org/help/) for reference."#;
pub fn generate_new_page(ops: NewOps, logger: &Logger) -> Result<(), Error> {
pub fn generate_new_page(logger: &Logger, opt: &Opt, new_opt: &NewOpt) -> Result<(), Error> {
logger.log(
LogLevel::DETAILER,
format!("Starting to create paths for given files"),
);
let toml_path = ensure_extension(ops.toml_path, "toml", false)?;
let toml_path = ensure_extension(new_opt.toml_path.clone(), "toml", false)?;
let markdown_path;
if let Some(markdown) = ops.markdown_path {
if let Some(markdown) = new_opt.markdown_path.clone() {
markdown_path = ensure_extension(markdown, "md", false)?;
} else {
markdown_path = ensure_extension(toml_path.clone(), "md", true)?;
@ -46,14 +46,14 @@ pub fn generate_new_page(ops: NewOps, logger: &Logger) -> Result<(), Error> {
);
let html_path;
if let Some(path) = ops.html_path {
if let Some(path) = new_opt.html_path.clone() {
html_path = ensure_extension(path, "html", false)?;
} else {
html_path = ensure_extension(toml_path.clone(), "html", true)?;
}
let title: String;
if let Some(t) = ops.title {
if let Some(t) = new_opt.title.clone() {
title = t;
} else {
let mut parts = toml_path.file_name().unwrap().to_str().unwrap().split(".");
@ -87,7 +87,7 @@ pub fn generate_new_page(ops: NewOps, logger: &Logger) -> Result<(), Error> {
},
};
match file_writer::write_toml(&toml_path, &page_config, ops.overwrite) {
match file_writer::write_toml(&toml_path, &page_config, opt.overwrite) {
Ok(_) => logger.log(
LogLevel::INFO,
format!("{:?} created successfully", toml_path),
@ -105,9 +105,9 @@ pub fn generate_new_page(ops: NewOps, logger: &Logger) -> Result<(), Error> {
format!("Creating a new .md file at {:?}", markdown_path),
);
file_writer::write_file(&markdown_path, PLACEHOLDER_MARKDOWN, ops.overwrite)?;
file_writer::write_file(&markdown_path, PLACEHOLDER_MARKDOWN, opt.overwrite)?;
if !ops.no_modify_config {
if !new_opt.no_modify_config {
logger.log(
LogLevel::INFO,
format!("Adding page config path to config.toml"),
@ -123,7 +123,7 @@ pub fn generate_new_page(ops: NewOps, logger: &Logger) -> Result<(), Error> {
format!("Re-serializing config and writing it"),
);
match file_writer::write_toml(&PathBuf::from("config.toml"), &config, ops.overwrite) {
match file_writer::write_toml(&PathBuf::from("config.toml"), &config, opt.overwrite) {
Ok(_) => {}
Err(err) => {
return Err(Error::new(

View File

@ -1,6 +1,6 @@
use std::path::PathBuf;
#[derive(StructOpt, Debug)]
#[derive(StructOpt, Debug, Clone)]
#[structopt(name = "Teasca.de Generator",
about = "A website generator, used mainly for generating teasca.de")]
pub struct Opt {
@ -12,66 +12,67 @@ pub struct Opt {
#[structopt(short = "q", long = "quiet", parse(from_occurrences))]
pub quiet: u8,
/// Overwrites necessary files to create new ones.
#[structopt(short = "o", long = "overwrite")]
pub overwrite: bool,
#[structopt(subcommand)]
pub cmd: Subcommands,
}
#[derive(StructOpt, Debug)]
#[derive(StructOpt, Debug, Clone)]
pub enum Subcommands {
/// Build the website
#[structopt(name = "build")]
Build(BuildOps),
Build(BuildOpt),
/// Create a new page
#[structopt(name = "new")]
New(NewOps),
New(NewOpt),
/// Initializes a config.toml
#[structopt(name = "init")]
Initialize(InitializeOps),
Initialize(InitializeOpt),
}
#[derive(StructOpt, Debug)]
pub struct BuildOps {
/// Overwrites necessary files to create new ones.
#[structopt(short = "o", long = "overwrite")]
pub overwrite: bool,
}
#[derive(StructOpt, Debug, Clone)]
pub struct BuildOpt {}
#[derive(StructOpt, Debug)]
pub struct NewOps {
#[derive(StructOpt, Debug, Clone)]
pub struct NewOpt {
/// File path for the .toml file created
#[structopt(parse(from_os_str))]
pub toml_path: PathBuf,
/// File path for the markdown file created
#[structopt(short = "m", long = "markdown", parse(from_os_str))]
pub markdown_path: Option<PathBuf>,
/// Outpuh html file path of the generated page
#[structopt(short = "h", long = "html", parse(from_os_str))]
pub html_path: Option<PathBuf>,
/// Sets the title of the generated page
#[structopt(short = "t", long = "title")]
pub title: Option<String>,
/// Overwrites existing .toml / .md files
#[structopt(short = "o", long = "overwrite")]
pub overwrite: bool,
/// Don't modify config.toml automatically
#[structopt(short = "n", long = "no-modify-config")]
pub no_modify_config: bool,
}
#[derive(StructOpt, Debug)]
pub struct InitializeOps {
#[derive(StructOpt, Debug, Clone)]
pub struct InitializeOpt {
/// Name of the webpage
#[structopt()]
pub name: String,
/// Favicon
#[structopt(short = "f", long = "favicon")]
pub favicon: Option<String>,
/// Twitter author
#[structopt(short = "t", long = "twitter")]
pub twitter_author: Option<String>,
/// Overwrites existing config.toml
#[structopt(short = "o", long = "overwrite")]
pub overwrite: bool,
/// Disables the default navbar
#[structopt(short = "n", long = "no-navbar")]
pub no_default_navbar: bool,