Skip to content

Commit

Permalink
Make sure that zola serve/build can start from anywhere inside dir tr…
Browse files Browse the repository at this point in the history
…ee (#1761)

* Make sure that zola serve/build can start from anywhere inside dir tree

* make clippy and rustfmt a bit happier

* replace unecessary if-else with unwrap_or and display which path could not get canonicalized if it fails at startup

* canonicalize config_path to avoid crash when config.toml changes
  • Loading branch information
savente93 authored Mar 3, 2022
1 parent fb347c2 commit dde3531
Show file tree
Hide file tree
Showing 24 changed files with 82 additions and 117 deletions.
4 changes: 2 additions & 2 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ fn generate_pe_header() {
}
res.set_icon("docs/static/favicon.ico");
res.set("LegalCopyright", &copyright);
res.compile().expect("Failed to compile Windows resources!");
res.compile().expect("Failed to compile Windows resources!");
}

fn main() {
Expand All @@ -29,7 +29,7 @@ fn main() {
{
return;
}
if cfg!(windows){
if cfg!(windows) {
generate_pe_header();
}
}
17 changes: 1 addition & 16 deletions components/config/src/config/languages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
use crate::config::search;
use crate::config::taxonomies;

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct LanguageOptions {
/// Title of the site. Defaults to None
Expand All @@ -31,21 +31,6 @@ pub struct LanguageOptions {
pub translations: HashMap<String, String>,
}

impl Default for LanguageOptions {
fn default() -> Self {
LanguageOptions {
title: None,
description: None,
generate_feed: false,
feed_filename: String::new(),
build_search_index: false,
taxonomies: Vec::new(),
search: search::Search::default(),
translations: HashMap::new(),
}
}
}

/// We want to ensure the language codes are valid ones
pub fn validate_code(code: &str) -> Result<()> {
if LanguageIdentifier::from_bytes(code.as_bytes()).is_err() {
Expand Down
8 changes: 1 addition & 7 deletions components/config/src/config/markup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::highlighting::{CLASS_STYLE, THEME_SET};

pub const DEFAULT_HIGHLIGHT_THEME: &str = "base16-ocean-dark";

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ThemeCss {
/// Which theme are we generating the CSS from
Expand All @@ -22,12 +22,6 @@ pub struct ThemeCss {
pub filename: String,
}

impl Default for ThemeCss {
fn default() -> ThemeCss {
ThemeCss { theme: String::new(), filename: String::new() }
}
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Markdown {
Expand Down
2 changes: 1 addition & 1 deletion components/config/src/highlighting.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use libs::once_cell::sync::Lazy;
use libs::syntect::dumps::from_binary;
use libs::syntect::highlighting::{Theme, ThemeSet};
use libs::syntect::html::ClassStyle;
use libs::syntect::parsing::{SyntaxReference, SyntaxSet};
use libs::once_cell::sync::Lazy;

use crate::config::Config;

Expand Down
5 changes: 1 addition & 4 deletions components/library/src/content/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,7 @@ pub fn find_related_assets(path: &Path, config: &Config, recursive: bool) -> Vec
}

if let Some(ref globset) = config.ignored_content_globset {
assets = assets
.into_iter()
.filter(|p| !globset.is_match(p))
.collect();
assets = assets.into_iter().filter(|p| !globset.is_match(p)).collect();
}

assets
Expand Down
9 changes: 5 additions & 4 deletions components/library/src/content/section.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ impl Section {

#[cfg(test)]
mod tests {
use std::fs::{create_dir, File, create_dir_all};
use std::fs::{create_dir, create_dir_all, File};
use std::io::Write;
use std::path::{Path, PathBuf};

Expand Down Expand Up @@ -269,16 +269,17 @@ mod tests {
let tmp_dir = tempdir().expect("create temp dir");
let path = tmp_dir.path();
let article_path = path.join("content/posts/with-assets");
create_dir_all(path.join(&article_path).join("foo/bar/baz/quux")).expect("create nested temp dir");
create_dir_all(path.join(&article_path).join("foo/baz/quux")).expect("create nested temp dir");
create_dir_all(path.join(&article_path).join("foo/bar/baz/quux"))
.expect("create nested temp dir");
create_dir_all(path.join(&article_path).join("foo/baz/quux"))
.expect("create nested temp dir");
let mut f = File::create(article_path.join("_index.md")).unwrap();
f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
File::create(article_path.join("example.js")).unwrap();
File::create(article_path.join("graph.jpg")).unwrap();
File::create(article_path.join("fail.png")).unwrap();
File::create(article_path.join("foo/bar/baz/quux/quo.xlsx")).unwrap();
File::create(article_path.join("foo/bar/baz/quux/quo.docx")).unwrap();


let mut gsb = GlobSetBuilder::new();
gsb.add(Glob::new("*.{js,png}").unwrap());
Expand Down
5 changes: 2 additions & 3 deletions components/library/src/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,7 @@ impl Library {
section.pages.push(key);
parent_is_transparent = section.meta.transparent;
}
page.ancestors =
ancestors.get(&parent_section_path).cloned().unwrap_or_else(Vec::new);
page.ancestors = ancestors.get(&parent_section_path).cloned().unwrap_or_default();
// Don't forget to push the actual parent
page.ancestors.push(*section_key);

Expand Down Expand Up @@ -257,7 +256,7 @@ impl Library {
children.sort_by(|a, b| sections_weight[a].cmp(&sections_weight[b]));
section.subsections = children;
}
section.ancestors = ancestors.get(&section.file.path).cloned().unwrap_or_else(Vec::new);
section.ancestors = ancestors.get(&section.file.path).cloned().unwrap_or_default();
}
}

Expand Down
6 changes: 2 additions & 4 deletions components/library/src/pagination/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,8 @@ impl<'a> Paginator<'a> {
let paginate_by = taxonomy.kind.paginate_by.unwrap();
// Check for taxon-specific template, or use generic as fallback.
let specific_template = format!("{}/single.html", taxonomy.kind.name);
let template = match check_template_fallbacks(&specific_template, tera, theme) {
Some(template) => template,
None => "taxonomy_single.html",
};
let template = check_template_fallbacks(&specific_template, tera, theme)
.unwrap_or("taxonomy_single.html");
let mut paginator = Paginator {
all_pages: Cow::Borrowed(&item.pages),
pagers: Vec::with_capacity(item.pages.len() / paginate_by),
Expand Down
19 changes: 10 additions & 9 deletions components/library/src/taxonomies/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,12 +204,15 @@ impl Taxonomy {

// Check for taxon-specific template, or use generic as fallback.
let specific_template = format!("{}/single.html", self.kind.name);
let template = match check_template_fallbacks(&specific_template, tera, &config.theme) {
Some(template) => template,
None => "taxonomy_single.html",
let template = if let Some(template) =
check_template_fallbacks(&specific_template, tera, &config.theme)
{
template
} else {
"taxonomy_single.html"
};

render_template(&template, tera, context, &config.theme).map_err(|e| {
render_template(template, tera, context, &config.theme).map_err(|e| {
Error::chain(format!("Failed to render single term {} page.", self.kind.name), e)
})
}
Expand All @@ -232,12 +235,10 @@ impl Taxonomy {

// Check for taxon-specific template, or use generic as fallback.
let specific_template = format!("{}/list.html", self.kind.name);
let template = match check_template_fallbacks(&specific_template, tera, &config.theme) {
Some(template) => template,
None => "taxonomy_list.html",
};
let template = check_template_fallbacks(&specific_template, tera, &config.theme)
.unwrap_or("taxonomy_list.html");

render_template(&template, tera, context, &config.theme).map_err(|e| {
render_template(template, tera, context, &config.theme).map_err(|e| {
Error::chain(format!("Failed to render a list of {} page.", self.kind.name), e)
})
}
Expand Down
2 changes: 1 addition & 1 deletion components/link_checker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ fn check_page_for_anchor(url: &str, body: String) -> errors::Result<()> {
let index = url.find('#').unwrap();
let anchor = url.get(index + 1..).unwrap();

if has_anchor_id(&body, &anchor) {
if has_anchor_id(&body, anchor) {
Ok(())
} else {
Err(errors::Error::from(format!("Anchor `#{}` not found on page", anchor)))
Expand Down
3 changes: 2 additions & 1 deletion components/rendering/benches/all.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use std::collections::HashMap;

use config::Config;
use front_matter::InsertAnchor;
use libs::tera::Tera;
use rendering::{render_content, RenderContext};
use tera::Tera;

static CONTENT: &str = r#"
# Modus cognitius profanam ne duae virtutis mundi
Expand Down Expand Up @@ -118,6 +118,7 @@ fn bench_render_content_without_highlighting(b: &mut test::Bencher) {
b.iter(|| render_content(CONTENT, &context).unwrap());
}

#[bench]
fn bench_render_content_no_shortcode(b: &mut test::Bencher) {
let tera = Tera::default();
let content2 = CONTENT.replace(r#"{{ youtube(id="my_youtube_id") }}"#, "");
Expand Down
28 changes: 13 additions & 15 deletions components/rendering/src/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::shortcode::{Shortcode, SHORTCODE_PLACEHOLDER};

const CONTINUE_READING: &str = "<span id=\"continue-reading\"></span>";
const ANCHOR_LINK_TEMPLATE: &str = "anchor-link.html";
static EMOJI_REPLACER: Lazy<EmojiReplacer> = Lazy::new(|| EmojiReplacer::new());
static EMOJI_REPLACER: Lazy<EmojiReplacer> = Lazy::new(EmojiReplacer::new);

#[derive(Debug)]
pub struct Rendered {
Expand Down Expand Up @@ -92,23 +92,21 @@ fn fix_link(
return Err(format!("Relative link {} not found.", link).into());
}
}
} else {
if is_external_link(link) {
external_links.push(link.to_owned());
link.to_owned()
} else if link == "#" {
link.to_string()
} else if link.starts_with("#") {
// local anchor without the internal zola path
if let Some(current_path) = context.current_page_path {
internal_links.push((current_path.to_owned(), Some(link[1..].to_owned())));
format!("{}{}", context.current_page_permalink, &link)
} else {
link.to_string()
}
} else if is_external_link(link) {
external_links.push(link.to_owned());
link.to_owned()
} else if link == "#" {
link.to_string()
} else if let Some(stripped_link) = link.strip_prefix('#') {
// local anchor without the internal zola path
if let Some(current_path) = context.current_page_path {
internal_links.push((current_path.to_owned(), Some(stripped_link.to_owned())));
format!("{}{}", context.current_page_permalink, &link)
} else {
link.to_string()
}
} else {
link.to_string()
};

Ok(result)
Expand Down
2 changes: 2 additions & 0 deletions components/rendering/tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(dead_code)]

pub struct ShortCode {
pub name: &'static str,
pub output: &'static str,
Expand Down
1 change: 0 additions & 1 deletion components/rendering/tests/toc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
mod common;

use common::ShortCode;
use libs::tera;
use rendering::Heading;

Expand Down
2 changes: 1 addition & 1 deletion components/search/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ fn fill_index(
// TODO: fix it like the truncate in Tera
match body.char_indices().nth(truncate_len) {
None => row.push(body),
Some((idx, _)) => row.push((&body[..idx]).to_string()),
Some((idx, _)) => row.push((body[..idx]).to_string()),
};
} else {
row.push(body);
Expand Down
2 changes: 1 addition & 1 deletion components/site/src/feed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub fn render_feed(
);
let library = site.library.read().unwrap();
// limit to the last n elements if the limit is set; otherwise use all.
let num_entries = site.config.feed_limit.unwrap_or_else(|| pages.len());
let num_entries = site.config.feed_limit.unwrap_or(pages.len());
let p =
pages.iter().take(num_entries).map(|x| x.to_serialized_basic(&library)).collect::<Vec<_>>();

Expand Down
6 changes: 3 additions & 3 deletions components/site/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl Site {
pub fn new<P: AsRef<Path>, P2: AsRef<Path>>(path: P, config_file: P2) -> Result<Site> {
let path = path.as_ref();
let config_file = config_file.as_ref();
let mut config = get_config(config_file)?;
let mut config = get_config(&path.join(config_file))?;

if let Some(theme) = config.theme.clone() {
// Grab data from the extra section of the theme
Expand Down Expand Up @@ -163,7 +163,7 @@ impl Site {
/// Reads all .md files in the `content` directory and create pages/sections
/// out of them
pub fn load(&mut self) -> Result<()> {
let base_path = self.base_path.to_string_lossy().replace("\\", "/");
let base_path = self.base_path.to_string_lossy().replace('\\', "/");

self.library = Arc::new(RwLock::new(Library::new(0, 0, self.config.is_multilingual())));
let mut pages_insert_anchors = HashMap::new();
Expand Down Expand Up @@ -714,7 +714,7 @@ impl Site {
let p = self.static_path.join(&t.filename);
if !p.exists() {
let content = &self.config.markdown.export_theme_css(&t.theme);
create_file(&p, &content)?;
create_file(&p, content)?;
}
}

Expand Down
24 changes: 8 additions & 16 deletions components/site/src/link_checking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,14 @@ pub fn check_internal_links_with_anchors(site: &Site) -> Result<()> {
let library = site.library.write().expect("Get lock for check_internal_links_with_anchors");

// Chain all internal links, from both sections and pages.
let page_links = library
.pages()
.values()
.map(|p| {
let path = &p.file.path;
p.internal_links.iter().map(move |l| (path.clone(), l))
})
.flatten();
let section_links = library
.sections()
.values()
.map(|p| {
let path = &p.file.path;
p.internal_links.iter().map(move |l| (path.clone(), l))
})
.flatten();
let page_links = library.pages().values().flat_map(|p| {
let path = &p.file.path;
p.internal_links.iter().map(move |l| (path.clone(), l))
});
let section_links = library.sections().values().flat_map(|p| {
let path = &p.file.path;
p.internal_links.iter().map(move |l| (path.clone(), l))
});
let all_links = page_links.chain(section_links);

// Only keep links with anchor fragments, and count them too.
Expand Down
8 changes: 4 additions & 4 deletions components/templates/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub fn render_redirect_template(url: &str, tera: &Tera) -> Result<String> {

pub fn load_tera(path: &Path, config: &Config) -> Result<Tera> {
let tpl_glob =
format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "templates/**/*.{*ml,md}");
format!("{}/{}", path.to_string_lossy().replace('\\', "/"), "templates/**/*.{*ml,md}");

// Only parsing as we might be extending templates from themes and that would error
// as we haven't loaded them yet
Expand All @@ -68,9 +68,9 @@ pub fn load_tera(path: &Path, config: &Config) -> Result<Tera> {
}

let theme_tpl_glob = format!(
"{}/{}",
path.to_string_lossy().replace("\\", "/"),
format!("themes/{}/templates/**/*.{{*ml,md}}", theme)
"{}/themes/{}/templates/**/*.{{*ml,md}}",
path.to_string_lossy().replace('\\', "/"),
theme
);
let mut tera_theme = Tera::parse(&theme_tpl_glob)
.map_err(|e| Error::chain("Error parsing templates from themes", e))?;
Expand Down
2 changes: 1 addition & 1 deletion components/utils/src/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ pub fn render_template(
theme: &Option<String>,
) -> Result<String> {
if let Some(template) = check_template_fallbacks(name, tera, theme) {
return tera.render(&template, &context).map_err(std::convert::Into::into);
return tera.render(template, &context).map_err(std::convert::Into::into);
}

// maybe it's a default one?
Expand Down
4 changes: 2 additions & 2 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ pub struct Cli {
pub root: PathBuf,

/// Path to a config file other than config.toml in the root of project
#[clap(short = 'c', long)]
pub config: Option<PathBuf>,
#[clap(short = 'c', long, default_value = "config.toml")]
pub config: PathBuf,

#[clap(subcommand)]
pub command: Command,
Expand Down
Loading

0 comments on commit dde3531

Please sign in to comment.