Skip to content

Commit 4c4fd26

Browse files
authored
Merge pull request #2387 from itowlson/templates-static-fs-create-dir
Create assets directory from fileserver template
2 parents 769d71e + ef89e57 commit 4c4fd26

File tree

7 files changed

+152
-7
lines changed

7 files changed

+152
-7
lines changed

crates/templates/src/reader.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ pub(crate) struct RawTemplateManifestV1 {
2323
pub add_component: Option<RawTemplateVariant>,
2424
pub parameters: Option<IndexMap<String, RawParameter>>,
2525
pub custom_filters: Option<serde::de::IgnoredAny>, // kept for error messaging
26+
pub outputs: Option<IndexMap<String, RawExtraOutput>>,
2627
}
2728

2829
#[derive(Debug, Deserialize)]
@@ -45,6 +46,18 @@ pub(crate) struct RawParameter {
4546
pub pattern: Option<String>,
4647
}
4748

49+
#[derive(Debug, Deserialize)]
50+
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "action")]
51+
pub(crate) enum RawExtraOutput {
52+
CreateDir(RawCreateDir),
53+
}
54+
55+
#[derive(Debug, Deserialize)]
56+
#[serde(deny_unknown_fields, rename_all = "snake_case")]
57+
pub(crate) struct RawCreateDir {
58+
pub path: String,
59+
}
60+
4861
pub(crate) fn parse_manifest_toml(text: impl AsRef<str>) -> anyhow::Result<RawTemplateManifest> {
4962
toml::from_str(text.as_ref()).context("Failed to parse template manifest TOML")
5063
}

crates/templates/src/renderer.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ pub(crate) enum RenderOperation {
2020
AppendToml(PathBuf, TemplateContent),
2121
MergeToml(PathBuf, MergeTarget, TemplateContent), // file to merge into, table to merge into, content to merge
2222
WriteFile(PathBuf, TemplateContent),
23+
CreateDirectory(PathBuf, std::sync::Arc<liquid::Template>),
2324
}
2425

2526
pub(crate) enum MergeTarget {
@@ -75,6 +76,11 @@ impl RenderOperation {
7576
let MergeTarget::Application(target_table) = target;
7677
Ok(TemplateOutput::MergeToml(path, target_table, rendered_text))
7778
}
79+
Self::CreateDirectory(path, template) => {
80+
let rendered = template.render(globals)?;
81+
let path = path.join(rendered); // TODO: should we validate that `rendered` was relative?`
82+
Ok(TemplateOutput::CreateDirectory(path))
83+
}
7884
}
7985
}
8086
}

crates/templates/src/run.rs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use crate::{
1212
cancellable::Cancellable,
1313
interaction::{InteractionStrategy, Interactive, Silent},
1414
renderer::MergeTarget,
15-
template::TemplateVariantInfo,
15+
template::{ExtraOutputAction, TemplateVariantInfo},
1616
};
1717
use crate::{
1818
renderer::{RenderOperation, TemplateContent, TemplateRenderer},
@@ -118,7 +118,14 @@ impl Run {
118118
.map(|(id, path)| self.snippet_operation(id, path))
119119
.collect::<anyhow::Result<Vec<_>>>()?;
120120

121-
let render_operations = files.into_iter().chain(snippets).collect();
121+
let extras = self
122+
.template
123+
.extra_outputs()
124+
.iter()
125+
.map(|extra| self.extra_operation(extra))
126+
.collect::<anyhow::Result<Vec<_>>>()?;
127+
128+
let render_operations = files.into_iter().chain(snippets).chain(extras).collect();
122129

123130
match interaction.populate_parameters(self) {
124131
Cancellable::Ok(parameter_values) => {
@@ -292,6 +299,17 @@ impl Run {
292299
}
293300
}
294301

302+
fn extra_operation(&self, extra: &ExtraOutputAction) -> anyhow::Result<RenderOperation> {
303+
match extra {
304+
ExtraOutputAction::CreateDirectory(_, template) => {
305+
Ok(RenderOperation::CreateDirectory(
306+
self.options.output_path.clone(),
307+
template.clone(),
308+
))
309+
}
310+
}
311+
}
312+
295313
fn list_content_files(from: &Path) -> anyhow::Result<Vec<PathBuf>> {
296314
let walker = WalkDir::new(from);
297315
let files = walker

crates/templates/src/template.rs

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ use regex::Regex;
99

1010
use crate::{
1111
constraints::StringConstraints,
12-
reader::{RawParameter, RawTemplateManifest, RawTemplateManifestV1, RawTemplateVariant},
12+
reader::{
13+
RawExtraOutput, RawParameter, RawTemplateManifest, RawTemplateManifestV1,
14+
RawTemplateVariant,
15+
},
1316
run::{Run, RunOptions},
1417
store::TemplateLayout,
1518
};
@@ -24,6 +27,7 @@ pub struct Template {
2427
trigger: TemplateTriggerCompatibility,
2528
variants: HashMap<TemplateVariantKind, TemplateVariant>,
2629
parameters: Vec<TemplateParameter>,
30+
extra_outputs: Vec<ExtraOutputAction>,
2731
snippets_dir: Option<PathBuf>,
2832
content_dir: Option<PathBuf>, // TODO: maybe always need a spin.toml file in there?
2933
}
@@ -113,6 +117,18 @@ pub(crate) struct TemplateParameter {
113117
default_value: Option<String>,
114118
}
115119

120+
pub(crate) enum ExtraOutputAction {
121+
CreateDirectory(String, std::sync::Arc<liquid::Template>),
122+
}
123+
124+
impl std::fmt::Debug for ExtraOutputAction {
125+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126+
match self {
127+
Self::CreateDirectory(orig, _) => f.debug_tuple("CreateDirectory").field(orig).finish(),
128+
}
129+
}
130+
}
131+
116132
impl Template {
117133
pub(crate) fn load_from(layout: &TemplateLayout) -> anyhow::Result<Self> {
118134
let manifest_path = layout.manifest_path();
@@ -155,6 +171,7 @@ impl Template {
155171
trigger: Self::parse_trigger_type(raw.trigger_type, layout),
156172
variants: Self::parse_template_variants(raw.new_application, raw.add_component),
157173
parameters: Self::parse_parameters(&raw.parameters)?,
174+
extra_outputs: Self::parse_extra_outputs(&raw.outputs)?,
158175
snippets_dir,
159176
content_dir,
160177
},
@@ -237,6 +254,10 @@ impl Template {
237254
self.parameters.iter().find(|p| p.id == name.as_ref())
238255
}
239256

257+
pub(crate) fn extra_outputs(&self) -> &[ExtraOutputAction] {
258+
&self.extra_outputs
259+
}
260+
240261
pub(crate) fn content_dir(&self) -> &Option<PathBuf> {
241262
&self.content_dir
242263
}
@@ -343,6 +364,18 @@ impl Template {
343364
}
344365
}
345366

367+
fn parse_extra_outputs(
368+
raw: &Option<IndexMap<String, RawExtraOutput>>,
369+
) -> anyhow::Result<Vec<ExtraOutputAction>> {
370+
match raw {
371+
None => Ok(vec![]),
372+
Some(parameters) => parameters
373+
.iter()
374+
.map(|(k, v)| ExtraOutputAction::from_raw(k, v))
375+
.collect(),
376+
}
377+
}
378+
346379
pub(crate) fn included_files(
347380
&self,
348381
base: &std::path::Path,
@@ -460,6 +493,20 @@ impl TemplateParameterDataType {
460493
}
461494
}
462495

496+
impl ExtraOutputAction {
497+
fn from_raw(id: &str, raw: &RawExtraOutput) -> anyhow::Result<Self> {
498+
Ok(match raw {
499+
RawExtraOutput::CreateDir(create) => {
500+
let path_template =
501+
liquid::Parser::new().parse(&create.path).with_context(|| {
502+
format!("Template error: output {id} is not a valid template")
503+
})?;
504+
Self::CreateDirectory(create.path.clone(), std::sync::Arc::new(path_template))
505+
}
506+
})
507+
}
508+
}
509+
463510
impl TemplateVariant {
464511
pub(crate) fn skip_file(&self, base: &std::path::Path, path: &std::path::Path) -> bool {
465512
self.skip_files

crates/templates/src/test_built_ins/mod.rs

Lines changed: 56 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,53 @@ impl ProgressReporter for DiscardingReporter {
1515
}
1616

1717
#[tokio::test]
18-
async fn add_fileserver_does_not_create_dir() -> anyhow::Result<()> {
18+
async fn new_fileserver_creates_assets_dir() -> anyhow::Result<()> {
19+
let built_ins_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
20+
let built_ins_src = TemplateSource::File(built_ins_dir);
21+
22+
let store_dir = tempfile::tempdir()?;
23+
let store = store::TemplateStore::new(store_dir.path());
24+
let manager = TemplateManager::new(store);
25+
26+
manager
27+
.install(
28+
&built_ins_src,
29+
&InstallOptions::default(),
30+
&DiscardingReporter,
31+
)
32+
.await?;
33+
34+
let app_dir = tempfile::tempdir()?;
35+
36+
// Create an app to add the fileserver into
37+
let new_fs_options = RunOptions {
38+
variant: TemplateVariantInfo::NewApplication,
39+
name: "fs".to_owned(),
40+
output_path: app_dir.path().join("fs"),
41+
values: HashMap::new(),
42+
accept_defaults: true,
43+
no_vcs: false,
44+
};
45+
manager
46+
.get("static-fileserver")?
47+
.expect("static-fileserver template should exist")
48+
.run(new_fs_options)
49+
.silent()
50+
.await?;
51+
52+
assert!(
53+
app_dir.path().join("fs").exists(),
54+
"fs dir should have been created"
55+
);
56+
assert!(
57+
app_dir.path().join("fs").join("assets").exists(),
58+
"fs/assets dir should have been created"
59+
);
60+
Ok(())
61+
}
62+
63+
#[tokio::test]
64+
async fn add_fileserver_creates_assets_dir() -> anyhow::Result<()> {
1965
let built_ins_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
2066
let built_ins_src = TemplateSource::File(built_ins_dir);
2167

@@ -49,13 +95,15 @@ async fn add_fileserver_does_not_create_dir() -> anyhow::Result<()> {
4995
.silent()
5096
.await?;
5197

98+
let fs_settings = HashMap::from_iter([("files-path".to_owned(), "moarassets".to_owned())]);
99+
52100
// Add the fileserver to that app
53101
let manifest_path = app_dir.path().join("spin.toml");
54102
let add_fs_options = RunOptions {
55103
variant: TemplateVariantInfo::AddComponent { manifest_path },
56104
name: "fs".to_owned(),
57105
output_path: app_dir.path().join("fs"),
58-
values: HashMap::new(),
106+
values: fs_settings,
59107
accept_defaults: true,
60108
no_vcs: false,
61109
};
@@ -68,8 +116,12 @@ async fn add_fileserver_does_not_create_dir() -> anyhow::Result<()> {
68116

69117
// Finally!
70118
assert!(
71-
!app_dir.path().join("fs").exists(),
72-
"<app_dir>/fs should not have been created"
119+
app_dir.path().join("fs").exists(),
120+
"<app_dir>/fs should have been created"
121+
);
122+
assert!(
123+
app_dir.path().join("fs").join("moarassets").exists(),
124+
"<app_dir>/fs/moarassets should have been created"
73125
);
74126
Ok(())
75127
}

crates/templates/src/writer.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ pub(crate) enum TemplateOutput {
1010
WriteFile(PathBuf, Vec<u8>),
1111
AppendToml(PathBuf, String),
1212
MergeToml(PathBuf, &'static str, String), // only have to worry about merging into root table for now
13+
CreateDirectory(PathBuf),
1314
}
1415

1516
impl TemplateOutputs {
@@ -57,6 +58,11 @@ impl TemplateOutput {
5758
.await
5859
.with_context(|| format!("Can't save changes to {}", path.display()))?;
5960
}
61+
TemplateOutput::CreateDirectory(dir) => {
62+
tokio::fs::create_dir_all(dir)
63+
.await
64+
.with_context(|| format!("Failed to create directory {}", dir.display()))?;
65+
}
6066
}
6167
Ok(())
6268
}

templates/static-fileserver/metadata/spin-template.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,6 @@ component = "component.txt"
1414
project-description = { type = "string", prompt = "Description", default = "" }
1515
http-path = { type = "string", prompt = "HTTP path", default = "/static/...", pattern = "^/\\S*$" }
1616
files-path = { type = "string", prompt = "Directory containing the files to serve", default = "assets", pattern = "^\\S+$" }
17+
18+
[outputs]
19+
create_asset_directory = { action = "create_dir", path = "{{ files-path }}" }

0 commit comments

Comments
 (0)