Add a LanguageOption for the default language if there is none

This commit is contained in:
Vincent Prouillet 2021-03-06 23:31:04 +01:00
parent 975800eb5b
commit 7484138a91
5 changed files with 38 additions and 35 deletions

View file

@ -7,6 +7,10 @@ use unic_langid::LanguageIdentifier;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct LanguageOptions {
/// Title of the site. Defaults to None
pub title: Option<String>,
/// Description of the site. Defaults to None
pub description: Option<String>,
/// Whether to generate a feed for that language, defaults to `false`
pub generate_feed: bool,
/// Whether to generate search index for that language, defaults to `false`
@ -15,7 +19,7 @@ pub struct LanguageOptions {
impl Default for LanguageOptions {
fn default() -> Self {
LanguageOptions { generate_feed: false, build_search_index: false }
LanguageOptions { title: None, description: None, generate_feed: false, build_search_index: false }
}
}

View file

@ -129,15 +129,23 @@ impl Config {
bail!("Highlight theme {} defined in config does not exist.", highlight_theme);
}
if config.languages.iter().any(|(code, _)| code == &config.default_language) {
bail!("Default language `{}` should not appear both in `config.default_language` and `config.languages`", config.default_language)
}
languages::validate_code(&config.default_language)?;
for code in config.languages.keys() {
languages::validate_code(&code)?;
}
// We automatically insert a language option for the default language *if* it isn't present
// TODO: what to do if there is like an empty dict for the lang? merge it or use the language
// TODO: as source of truth?
if !config.languages.contains_key(&config.default_language) {
config.languages.insert(config.default_language.clone(), languages::LanguageOptions {
title: config.title.clone(),
description: config.title.clone(),
generate_feed: config.generate_feed,
build_search_index: config.build_search_index,
});
}
if !config.ignored_content.is_empty() {
// Convert the file glob strings into a compiled glob set matcher. We want to do this once,
// at program initialization, rather than for every page, for example. We arrange for the
@ -278,14 +286,20 @@ impl Config {
self.add_theme_extra(&theme)
}
/// Is this site using i18n?
pub fn is_multilingual(&self) -> bool {
!self.languages.is_empty()
pub fn other_languages(&self) -> HashMap<&str, &languages::LanguageOptions> {
let mut others = HashMap::new();
for (k, v) in &self.languages {
if k == &self.default_language {
continue;
}
others.insert(k.as_str(), v);
}
others
}
/// Returns the codes of all additional languages
pub fn languages_codes(&self) -> Vec<&str> {
self.languages.iter().map(|(code, _)| code.as_ref()).collect()
/// Is this site using i18n?
pub fn is_multilingual(&self) -> bool {
!self.other_languages().is_empty()
}
pub fn is_in_build_mode(&self) -> bool {
@ -545,6 +559,7 @@ title = "A title"
#[test]
fn can_use_present_translation() {
let config = Config::parse(CONFIG_TRANSLATION).unwrap();
assert!(config.languages.contains_key("fr"));
assert_eq!(config.get_translation("fr", "title").unwrap(), "Un titre");
assert_eq!(config.get_translation("en", "title").unwrap(), "A title");
}
@ -671,22 +686,6 @@ anchors = "off"
assert_eq!(config.slugify.anchors, SlugifyStrategy::Off);
}
#[test]
fn error_on_language_set_twice() {
let config_str = r#"
base_url = "https://remplace-par-ton-url.fr"
default_language = "fr"
[languages.fr]
[languages.en]
"#;
let config = Config::parse(config_str);
let err = config.unwrap_err();
assert_eq!("Default language `fr` should not appear both in `config.default_language` and `config.languages`", format!("{}", err));
}
#[test]
fn cannot_overwrite_theme_mapping_with_invalid_type() {
let config_str = r#"

View file

@ -136,7 +136,7 @@ impl FileInfo {
// The language code is not present in the config: typo or the user forgot to add it to the
// config
if !config.languages_codes().contains(&parts[1].as_ref()) {
if !config.other_languages().contains_key(&parts[1].as_ref()) {
bail!("File {:?} has a language code of {} which isn't present in the config.toml `languages`", self.path, parts[1]);
}

View file

@ -124,10 +124,10 @@ impl Site {
/// The index sections are ALWAYS at those paths
/// There are one index section for the default language + 1 per language
fn index_section_paths(&self) -> Vec<(PathBuf, Option<String>)> {
fn index_section_paths(&self) -> Vec<(PathBuf, Option<&str>)> {
let mut res = vec![(self.content_path.join("_index.md"), None)];
for code in self.config.languages.keys() {
res.push((self.content_path.join(format!("_index.{}.md", code)), Some(code.clone())));
for (code, _) in self.config.other_languages() {
res.push((self.content_path.join(format!("_index.{}.md", code)), Some(code)));
}
res
}
@ -174,7 +174,7 @@ impl Site {
// so it's kinda necessecary
let mut dir_walker = WalkDir::new(format!("{}/{}", base_path, "content/")).into_iter();
let mut allowed_index_filenames: Vec<_> =
self.config.languages.iter().map(|(code, _)| format!("_index.{}.md", code)).collect();
self.config.other_languages().iter().map(|(code, _)| format!("_index.{}.md", code)).collect();
allowed_index_filenames.push("_index.md".to_string());
loop {
@ -657,7 +657,7 @@ impl Site {
start = log_time(start, "Generated feed in default language");
}
for (code, language) in &self.config.languages {
for (code, language) in &self.config.other_languages() {
if !language.generate_feed {
continue;
}
@ -701,7 +701,7 @@ impl Site {
),
)?;
for (code, language) in &self.config.languages {
for (code, language) in &self.config.other_languages() {
if code != &self.config.default_language && language.build_search_index {
create_file(
&self.output_path.join(&format!("search_index.{}.js", &code)),

View file

@ -67,7 +67,7 @@ fn make_path_with_lang(path: String, lang: &str, config: &Config) -> Result<Stri
return Ok(path);
}
if !config.languages.iter().any(|(x, _)| x == lang) {
if !config.other_languages().contains_key(lang) {
return Err(
format!("`{}` is not an authorized language (check config.languages).", lang).into()
);