Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
77 changes: 73 additions & 4 deletions crates/cli/src/commands/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.

use std::process::ExitCode;
use std::{collections::BTreeSet, fmt::Write, process::ExitCode};

use anyhow::{Context as _, bail};
use camino::Utf8PathBuf;
use clap::Parser;
use figment::Figment;
use mas_config::{
Expand All @@ -27,14 +29,19 @@ pub(super) struct Options {
#[derive(Parser, Debug)]
enum Subcommand {
/// Check that the templates specified in the config are valid
Check,
Check {
/// If set, templates will be rendered to this directory.
/// The directory must either not exist or be empty.
#[arg(long = "out-dir")]
out_dir: Option<Utf8PathBuf>,
},
}

impl Options {
pub async fn run(self, figment: &Figment) -> anyhow::Result<ExitCode> {
use Subcommand as SC;
match self.subcommand {
SC::Check => {
SC::Check { out_dir } => {
let _span = info_span!("cli.templates.check").entered();

let template_config = TemplatesConfig::extract_or_default(figment)
Expand Down Expand Up @@ -67,7 +74,69 @@ impl Options {
)?;
let templates =
templates_from_config(&template_config, &site_config, &url_builder).await?;
templates.check_render(clock.now(), &mut rng)?;
let all_renders = templates.check_render(clock.now(), &mut rng)?;

if let Some(out_dir) = out_dir {
// Save renders to disk.
if out_dir.exists() {
let mut read_dir =
tokio::fs::read_dir(&out_dir).await.with_context(|| {
format!("could not read {out_dir} to check it's empty")
})?;
if read_dir.next_entry().await?.is_some() {
bail!("Render directory {out_dir} is not empty, refusing to write.");
}
} else {
tokio::fs::create_dir(&out_dir)
.await
.with_context(|| format!("could not create {out_dir}"))?;
}

let all_locales: BTreeSet<&str> = all_renders
.iter()
.filter_map(|((_, sample_identifier), _)| {
sample_identifier.locale.as_deref()
})
.collect();
for locale in all_locales {
let locale_dir = out_dir.join(locale);
tokio::fs::create_dir(&locale_dir)
.await
.with_context(|| format!("could not create {locale_dir}"))?;
}

for ((template, sample_identifier), template_render) in &all_renders {
let (template_filename_base, template_ext) =
template.rsplit_once('.').unwrap_or((template, "txt"));
let template_filename_base = template_filename_base.replace('/', "_");

// Make a string like:
// - `-sample1`
// - `-session2-sample1`
let sample_suffix = {
let mut s = String::new();
if let Some(session_index) = sample_identifier.session_index {
write!(s, "-session{session_index}")?;
}
write!(s, "-sample{}", sample_identifier.index)?;
s
};

let locale_dir = if let Some(locale) = &sample_identifier.locale {
out_dir.join(locale)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not convinced that we should do one directory per locale

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought it'd make it easier for a German deployment to only care about the German outputs, for example. Maybe there are better ways of doing that.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

feels like the kind of post-processing a consumer could do themselves?

} else {
out_dir.clone()
};

let render_path = locale_dir.join(format!(
"{template_filename_base}{sample_suffix}.{template_ext}"
));

tokio::fs::write(&render_path, template_render.as_bytes())
.await
.with_context(|| format!("could not write render to {render_path}"))?;
}
}

Ok(ExitCode::SUCCESS)
}
Expand Down
Loading
Loading