Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change config usage #77

Merged
merged 1 commit into from
Aug 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ pub struct Settings {
pub toc: TocSettings,
}

#[derive(Clone)]
pub struct TocSettings {
pub position: TocPosition,
pub title: TocTitle,
Expand All @@ -128,11 +129,13 @@ pub struct TocSettings {
pub item_format: String,
}

#[derive(Clone)]
pub enum TocPosition {
LEFT,
RIGHT,
}

#[derive(Clone)]
pub enum TocTitle {
DEFAULT,
CUSTOM,
Expand Down
26 changes: 15 additions & 11 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use panic_message::panic_info_message;
use std::collections::HashMap;
use std::env;
use std::fmt::Write;
use std::panic::{set_hook, PanicInfo};
use uuid::Uuid;

Expand Down Expand Up @@ -63,27 +64,30 @@ where
"Unknown"
};

payload.push_str(&format!("Name: {}\n", env!("CARGO_PKG_NAME")));
payload.push_str(&format!("Version: {}\n", env!("CARGO_PKG_VERSION")));
payload.push_str(&format!("Operating System: {}\n", os));
let _ = writeln!(payload, "Name: {}", env!("CARGO_PKG_NAME"));
let _ = writeln!(payload, "Version: {}", env!("CARGO_PKG_VERSION"));
let _ = writeln!(payload, "Operating System: {}", os);

payload.push_str(&format!("Cause: {}.\n", panic_info_message(info)));
let _ = writeln!(payload, "Cause: {}", panic_info_message(info));

match info.location() {
Some(location) => payload.push_str(&format!(
"Panic occurred in file '{}' at line {}\n",
location.file(),
location.line()
)),
Some(location) => {
let _ = writeln!(
payload,
"Panic occurred in file '{}' at line {}",
location.file(),
location.line()
);
}
None => payload.push_str("Panic location unknown.\n"),
}
};

let logs = match std::fs::read_to_string(&CONFIG.logging.log_dir) {
Ok(logs) => logs,
Err(_) => "No logs available.".to_string(),
};

payload.push_str(&format!("\n\nLogs: \n{}", logs));
let _ = write!(payload, "\n\nLogs: \n{}", logs);

f(Some(path), payload);
}))
Expand Down
17 changes: 10 additions & 7 deletions src/ui/article/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use crate::ui::utils::remove_view_from_layout;
use crate::wiki::{
article::{
parser::{DefaultParser, Parser},
Article, ArticleBuilder,
},
article::{parser::DefaultParser, Article, ArticleBuilder},
search::SearchResult,
};
use crate::{
Expand Down Expand Up @@ -34,8 +31,12 @@ pub fn on_article_submit(siv: &mut Cursive, search_result: &SearchResult) {
search_result.title(),
search_result.page_id()
);
let article = match ArticleBuilder::new(*search_result.page_id(), None)
.build(&mut DefaultParser::new())
let article = match ArticleBuilder::new(
*search_result.page_id(),
None,
&CONFIG.api_config.base_url,
)
.build(&mut DefaultParser::new(&CONFIG.settings.toc))
{
Ok(article) => article,
Err(error) => {
Expand Down Expand Up @@ -126,7 +127,9 @@ fn open_link(siv: &mut Cursive, target: String) {

// fetch the article
log::debug!("fetching the article");
let article = match ArticleBuilder::new(0, Some(target)).build(&mut DefaultParser::new()) {
let article = match ArticleBuilder::new(0, Some(target), &CONFIG.api_config.base_url)
.build(&mut DefaultParser::new(&CONFIG.settings.toc))
{
Ok(article) => article,
Err(error) => {
log::warn!("{:?}", error);
Expand Down
2 changes: 1 addition & 1 deletion src/ui/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use cursive::{align::HAlign, utils::markup::StyledString, Cursive};

/// Returns the default SearchBuilder
fn build_search() -> SearchBuilder {
SearchBuilder::new()
SearchBuilder::new(&config::CONFIG.api_config.base_url)
.info(SearchMetadata::new().total_hits())
.prop(SearchProperties::new().snippet())
.sort(SearchSortOrder::JustMatch)
Expand Down
29 changes: 17 additions & 12 deletions src/wiki/article/builder.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use crate::{
config::CONFIG,
wiki::article::{compiled_article::Article, parser::Parser},
};
use crate::wiki::article::{compiled_article::Article, parser::Parser};

use anyhow::Result;
use reqwest::blocking::{get, Response};
Expand All @@ -12,13 +9,19 @@ pub struct ArticleBuilder {
page_id: i32,
/// The optional link of the article to be fetched
target: Option<String>,
/// The url of wikipedia
base_url: String,
}

impl ArticleBuilder {
/// Creates a new Articlebuilder
pub fn new(page_id: i32, target: Option<String>) -> ArticleBuilder {
pub fn new(page_id: i32, target: Option<String>, base_url: &str) -> ArticleBuilder {
log::debug!("creating a new instance of ArticleBuilder");
ArticleBuilder { page_id, target }
ArticleBuilder {
page_id,
target,
base_url: base_url.to_string(),
}
}

/// Fetches the article and parses it with a given parser. Any errors it encounters will be returned
Expand All @@ -36,8 +39,8 @@ impl ArticleBuilder {
/// Creates a url from the link
fn build_url(&self) -> String {
match self.target {
Some(ref target) => format!("{}{}", CONFIG.api_config.base_url, target),
None => format!("{}?curid={}", CONFIG.api_config.base_url, self.page_id),
Some(ref target) => format!("{}{}", self.base_url, target),
None => format!("{}?curid={}", self.base_url, self.page_id),
}
}

Expand All @@ -54,16 +57,18 @@ impl ArticleBuilder {

#[cfg(test)]
mod tests {
const BASE_URL: &str = "https://en.wikipedia.org/";

#[test]
fn correct_url() {
use super::ArticleBuilder;
assert_eq!(
ArticleBuilder::new(1234, None).build_url(),
"https://en.wikipedia.org/?curid=1234".to_string()
ArticleBuilder::new(1234, None, BASE_URL).build_url(),
format!("{}?curid=1234", BASE_URL)
);
assert_eq!(
ArticleBuilder::new(1234, Some("/wiki/Software".to_string())).build_url(),
"https://en.wikipedia.org//wiki/Software".to_string()
ArticleBuilder::new(1234, Some("/wiki/Software".to_string()), BASE_URL).build_url(),
format!("{}/wiki/Software", BASE_URL)
);
}
}
49 changes: 25 additions & 24 deletions src/wiki/article/parser.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::config::{TocTitle, CONFIG};
use crate::config::{TocSettings, TocTitle, CONFIG};
use crate::wiki::article::{
compiled_article::Article,
element::ArticleElement,
Expand All @@ -17,7 +17,6 @@ use std::io::Read;

/// The Parser trait allows for generating an Article from a html source
pub trait Parser {
fn new() -> Self;
fn parse<R: Read>(&mut self, html: R) -> Result<Article>;
}

Expand All @@ -26,10 +25,21 @@ pub trait Parser {
pub struct DefaultParser {
/// The elements that have been parsed already
elements: Vec<ArticleElement>,
/// The toc configuration
toc_settings: TocSettings,
}

impl DefaultParser {
/// This functinon takes generates a TableOfContents from a given document. When no
/// Creates a new DefaultParser with a given toc configuration
pub fn new(toc_settings: &TocSettings) -> Self {
log::debug!("creating a new instance of DefaultParser");
Self {
elements: Vec::new(),
toc_settings: toc_settings.clone(),
}
}

/// This function takes generates a TableOfContents from a given document. When no
/// TableOfContents can be found in the document, it returns Ok(None). Any errors it
/// encounters are returned
fn parse_toc(&self, document: &Document) -> Result<Option<TableOfContents>> {
Expand All @@ -43,16 +53,15 @@ impl DefaultParser {
.context("No table of contents was found")?;

// get the title of the toc
let toc_title = match CONFIG.settings.toc.title {
let toc_title = match self.toc_settings.title {
TocTitle::DEFAULT => toc_node
.find(Class("toctitle"))
.next()
.context("No toc title was found")?
.text(),
TocTitle::ARTICLE => self.get_title(document)?,
TocTitle::CUSTOM => CONFIG
.settings
.toc
TocTitle::CUSTOM => self
.toc_settings
.title_custom
.clone()
.unwrap_or_else(|| "NONE".to_string()),
Expand Down Expand Up @@ -116,7 +125,7 @@ impl DefaultParser {

// format the text
let text = {
let mut text = CONFIG.settings.toc.item_format.to_string();
let mut text = self.toc_settings.item_format.to_string();
for (k, v) in &data {
text = text.replace(k, v);
}
Expand Down Expand Up @@ -298,14 +307,6 @@ impl DefaultParser {
}

impl Parser for DefaultParser {
/// Creates a new DefaultParser with the given ParserConfig
fn new() -> Self {
log::debug!("creating a new instance of DefaultParser");
Self {
elements: Vec::new(),
}
}

/// Tries to parse a given html document into an Article. Any errors it encounters will be
/// returned
fn parse<R: Read>(&mut self, html: R) -> Result<Article> {
Expand Down Expand Up @@ -383,7 +384,7 @@ mod tests {

#[test]
fn parse_link() {
let mut parser = DefaultParser::new();
let mut parser = DefaultParser::new(&CONFIG.settings.toc);

let test_html = generate_html(
"<h1 class=\"mw-first-heading\">Github</h1><p><a href=\"/wiki/Software_development\">software development</a></p>",
Expand All @@ -405,7 +406,7 @@ mod tests {

#[test]
fn parse_text() {
let mut parser = DefaultParser::new();
let mut parser = DefaultParser::new(&CONFIG.settings.toc);

let test_html =
generate_html("<h1 class=\"mw-first-heading\">Github</h1><p>is a provider of</p>");
Expand All @@ -424,7 +425,7 @@ mod tests {

#[test]
fn parse_header() {
let mut parser = DefaultParser::new();
let mut parser = DefaultParser::new(&CONFIG.settings.toc);

let test_html = generate_html(
"<h1 class=\"mw-first-heading\">Github</h1><h2><span class=\"mw-headline\">History</span></h2>",
Expand All @@ -446,7 +447,7 @@ mod tests {

#[test]
fn parse_bold() {
let mut parser = DefaultParser::new();
let mut parser = DefaultParser::new(&CONFIG.settings.toc);

let test_html =
generate_html("<h1 class=\"mw-first-heading\">Github</h1><p><b>GitHub, Inc.</b></p>");
Expand All @@ -465,7 +466,7 @@ mod tests {

#[test]
fn parse_italic() {
let mut parser = DefaultParser::new();
let mut parser = DefaultParser::new(&CONFIG.settings.toc);

let test_html =
generate_html("<h1 class=\"mw-first-heading\">Github</h1><p><i>GitHub, Inc.</i></p>");
Expand All @@ -484,7 +485,7 @@ mod tests {

#[test]
fn parse_list() {
let mut parser = DefaultParser::new();
let mut parser = DefaultParser::new(&CONFIG.settings.toc);

let test_html = generate_html(
"<h1 class=\"mw-first-heading\">Github</h1><ul><li>Documentation,<a href=\"/wiki/README\">README</a></li></ul>",
Expand Down Expand Up @@ -516,7 +517,7 @@ mod tests {

#[test]
fn parse_code_block() {
let mut parser = DefaultParser::new();
let mut parser = DefaultParser::new(&CONFIG.settings.toc);

let test_html = generate_html(
"<h1 class=\"mw-first-heading\">Github</h1><pre><code>inverse(a, n) t := 0</code></pre>",
Expand All @@ -536,7 +537,7 @@ mod tests {

#[test]
fn incorrect_html() {
let mut parser = DefaultParser::new();
let mut parser = DefaultParser::new(&CONFIG.settings.toc);

let test_html = generate_html("nope");
assert!(parser.parse(test_html.as_bytes()).is_err())
Expand Down
Loading