Skip to content

Templates for static fileserver and redirect #898

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

Merged
merged 3 commits into from
Nov 22, 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
35 changes: 35 additions & 0 deletions crates/templates/src/filters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,38 @@ impl Filter for SnakeCaseFilter {
Ok(input.to_value())
}
}

#[derive(Clone, liquid_derive::ParseFilter, liquid_derive::FilterReflection)]
#[filter(
name = "http_wildcard",
description = "Add Spin HTTP wildcard suffix (/...) if needed.",
parsed(HttpWildcardFilter)
)]
pub(crate) struct HttpWildcardFilterParser;

#[derive(Debug, Default, liquid_derive::Display_filter)]
#[name = "http_wildcard"]
struct HttpWildcardFilter;

impl Filter for HttpWildcardFilter {
fn evaluate(
&self,
input: &dyn ValueView,
_runtime: &dyn Runtime,
) -> Result<liquid::model::Value, liquid_core::error::Error> {
let input = input
.as_scalar()
.ok_or_else(|| liquid_core::error::Error::with_msg("String expected"))?;

let route = input.into_string().to_string();
let wildcard_route = if route.ends_with("/...") {
route
} else if route.ends_with('/') {
format!("{route}...")
} else {
format!("{route}/...")
};

Ok(wildcard_route.to_value())
}
}
29 changes: 27 additions & 2 deletions crates/templates/src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ mod tests {

use tempfile::tempdir;

use crate::RunOptions;
use crate::{RunOptions, TemplateVariantKind};

use super::*;

Expand All @@ -414,7 +414,7 @@ mod tests {
PathBuf::from(crate_dir).join("tests")
}

const TPLS_IN_THIS: usize = 9;
const TPLS_IN_THIS: usize = 11;

#[tokio::test]
async fn can_install_into_new_directory() {
Expand Down Expand Up @@ -945,4 +945,29 @@ mod tests {
.expect_err("Expected to fail to add component, but it succeeded");
}
}

#[tokio::test]
async fn cannot_new_a_component_only_template() {
let temp_dir = tempdir().unwrap();
let store = TemplateStore::new(temp_dir.path());
let manager = TemplateManager { store };
let source = TemplateSource::File(project_root());

manager
.install(&source, &InstallOptions::default(), &DiscardingReporter)
.await
.unwrap();

let redirect = manager.get("redirect").unwrap().unwrap();
assert!(!redirect.supports_variant(&TemplateVariantKind::NewApplication));
assert!(redirect.supports_variant(&TemplateVariantKind::AddComponent));

let http_rust = manager.get("http-rust").unwrap().unwrap();
assert!(http_rust.supports_variant(&TemplateVariantKind::NewApplication));
assert!(http_rust.supports_variant(&TemplateVariantKind::AddComponent));

let http_empty = manager.get("http-empty").unwrap().unwrap();
assert!(http_empty.supports_variant(&TemplateVariantKind::NewApplication));
assert!(!http_empty.supports_variant(&TemplateVariantKind::AddComponent));
}
}
2 changes: 2 additions & 0 deletions crates/templates/src/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub(crate) struct RawTemplateManifestV1 {
pub id: String,
pub description: Option<String>,
pub trigger_type: Option<String>,
pub new_application: Option<RawTemplateVariant>,
pub add_component: Option<RawTemplateVariant>,
pub parameters: Option<IndexMap<String, RawParameter>>,
pub custom_filters: Option<Vec<RawCustomFilter>>,
Expand All @@ -26,6 +27,7 @@ pub(crate) struct RawTemplateManifestV1 {
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub(crate) struct RawTemplateVariant {
pub supported: Option<bool>,
pub skip_files: Option<Vec<String>>,
pub skip_parameters: Option<Vec<String>>,
pub snippets: Option<HashMap<String, String>>,
Expand Down
10 changes: 8 additions & 2 deletions crates/templates/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,8 @@ impl Run {
let mut builder = liquid::ParserBuilder::with_stdlib()
.filter(crate::filters::KebabCaseFilterParser)
.filter(crate::filters::PascalCaseFilterParser)
.filter(crate::filters::SnakeCaseFilterParser);
.filter(crate::filters::SnakeCaseFilterParser)
.filter(crate::filters::HttpWildcardFilterParser);
for filter in self.template.custom_filters() {
builder = builder.filter(filter);
}
Expand Down Expand Up @@ -470,13 +471,18 @@ impl PreparedTemplate {
.into_iter()
.map(|(path, content)| Self::render_one(path, content, &globals))
.collect::<anyhow::Result<Vec<_>>>()?;
let outputs = HashMap::from_iter(rendered);

let deltas = self
.snippets
.into_iter()
.map(|so| Self::render_snippet(so, &globals))
.collect::<anyhow::Result<Vec<_>>>()?;

if rendered.is_empty() && deltas.is_empty() {
return Err(anyhow!("Nothing to create"));
}

let outputs = HashMap::from_iter(rendered);
Ok(TemplateOutputs {
files: outputs,
deltas,
Expand Down
36 changes: 28 additions & 8 deletions crates/templates/src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ impl Template {
id: raw.id.clone(),
description: raw.description.clone(),
trigger: Self::parse_trigger_type(raw.trigger_type, layout),
variants: Self::parse_template_variants(raw.add_component),
variants: Self::parse_template_variants(raw.new_application, raw.add_component),
parameters: Self::parse_parameters(&raw.parameters)?,
custom_filters: Self::load_custom_filters(layout, &raw.custom_filters)?,
snippets_dir,
Expand Down Expand Up @@ -200,21 +200,41 @@ impl Template {
}

fn parse_template_variants(
new_application: Option<RawTemplateVariant>,
add_component: Option<RawTemplateVariant>,
) -> HashMap<TemplateVariantKind, TemplateVariant> {
let mut variants = HashMap::default();
// TODO: in future we might have component-only templates
variants.insert(
TemplateVariantKind::NewApplication,
TemplateVariant::default(),
);
if let Some(ac) = add_component {
let vt = Self::parse_template_variant(ac);
if let Some(vt) = Self::get_variant(new_application, true) {
variants.insert(TemplateVariantKind::NewApplication, vt);
}
if let Some(vt) = Self::get_variant(add_component, false) {
variants.insert(TemplateVariantKind::AddComponent, vt);
}
variants
}

fn get_variant(
raw: Option<RawTemplateVariant>,
default_supported: bool,
) -> Option<TemplateVariant> {
match raw {
None => {
if default_supported {
Some(Default::default())
} else {
None
}
}
Some(rv) => {
if rv.supported.unwrap_or(true) {
Some(Self::parse_template_variant(rv))
} else {
None
}
}
}
}

fn parse_template_variant(raw: RawTemplateVariant) -> TemplateVariant {
TemplateVariant {
skip_files: raw.skip_files.unwrap_or_default(),
Expand Down
7 changes: 7 additions & 0 deletions templates/redirect/metadata/snippets/component.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[[component]]
source = { url = "https://github.com/fermyon/spin-redirect/releases/download/v0.0.1/redirect.wasm", digest = "sha256:d57c3d91e9b62a6b628516c6d11daf6681e1ca2355251a3672074cddefd7f391" }
id = "{{ project-name }}"
environment = { DESTINATION = "{{ redirect-to }}" }
[component.trigger]
route = "{{ redirect-from }}"
executor = { type = "wagi" }
15 changes: 15 additions & 0 deletions templates/redirect/metadata/spin-template.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
manifest_version = "1"
id = "redirect"
description = "Redirects a HTTP route"
trigger_type = "http"

[new_application]
supported = false

[add_component]
[add_component.snippets]
component = "component.txt"

[parameters]
redirect-from = { type = "string", prompt = "Redirect from", pattern = "^/\\S*$" }
redirect-to = { type = "string", prompt = "Redirect to", pattern = "^/\\S*$" }
6 changes: 6 additions & 0 deletions templates/static-fileserver/metadata/snippets/component.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[[component]]
source = { url = "https://github.com/fermyon/spin-fileserver/releases/download/v0.0.1/spin_static_fs.wasm", digest = "sha256:650376c33a0756b1a52cad7ca670f1126391b79050df0321407da9c741d32375" }
id = "{{ project-name }}"
files = [ { source = "{{ files-path }}", destination = "/" } ]
[component.trigger]
route = "{{ http-path | http_wildcard }}"
15 changes: 15 additions & 0 deletions templates/static-fileserver/metadata/spin-template.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
manifest_version = "1"
id = "static-fileserver"
description = "Serves static files from an asset directory"
trigger_type = "http"

[new_application]
supported = false

[add_component]
[add_component.snippets]
component = "component.txt"

[parameters]
http-path = { type = "string", prompt = "HTTP path", default = "/static/...", pattern = "^/\\S*$" }
files-path = { type = "string", prompt = "Directory containing the files to serve", default = "assets", pattern = "^\\S+$" }