Skip to content

Commit

Permalink
Render empty preview feature lists (#2546)
Browse files Browse the repository at this point in the history
If the user has an empty list defined for preview features in their generator
block, do not remove the parameter when re-introspecting.
  • Loading branch information
Julius de Bruijn authored Jan 3, 2022
1 parent ac17a7d commit 6d16e41
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 34 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1781,7 +1781,7 @@ async fn re_introspecting_custom_compound_id_names(api: &TestApi) -> TestResult
@@id([first, last], name: "compound", map: "User.something@invalid-and/weird")
}
model User2 {
first Int
last Int
Expand All @@ -1798,7 +1798,7 @@ async fn re_introspecting_custom_compound_id_names(api: &TestApi) -> TestResult
@@id([first, last], name: "compound", map: "User.something@invalid-and/weird")
}
model User2 {
first Int
last Int
Expand Down
21 changes: 17 additions & 4 deletions libs/datamodel/core/src/configuration/generator.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{common::preview_features::PreviewFeature, configuration::StringFromEnvVar};
use enumflags2::BitFlags;
use serde::Serialize;
use serde::{Serialize, Serializer};
use std::collections::HashMap;

#[derive(Debug, Serialize, Clone)]
Expand All @@ -14,15 +14,28 @@ pub struct Generator {
#[serde(default)]
pub binary_targets: Vec<StringFromEnvVar>,

#[serde(default)]
pub preview_features: Vec<PreviewFeature>,
#[serde(default, serialize_with = "mcf_preview_features")]
pub preview_features: Option<Vec<PreviewFeature>>,

#[serde(skip_serializing_if = "Option::is_none")]
pub documentation: Option<String>,
}

pub fn mcf_preview_features<S>(feat: &Option<Vec<PreviewFeature>>, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match feat {
Some(feats) => feats.serialize(s),
None => Vec::<String>::new().serialize(s),
}
}

impl Generator {
pub fn preview_features(&self) -> BitFlags<PreviewFeature> {
self.preview_features.iter().copied().collect()
match self.preview_features {
Some(ref preview_features) => preview_features.iter().copied().collect(),
None => BitFlags::empty(),
}
}
}
5 changes: 1 addition & 4 deletions libs/datamodel/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,8 +289,5 @@ fn render_schema_ast_to(stream: &mut dyn std::fmt::Write, schema: &ast::SchemaAs
}

fn preview_features(generators: &[Generator]) -> BitFlags<PreviewFeature> {
generators
.iter()
.flat_map(|gen| gen.preview_features.iter().cloned())
.collect()
generators.iter().map(|gen| gen.preview_features()).collect()
}
26 changes: 11 additions & 15 deletions libs/datamodel/core/src/transform/ast_to_dml/generator_loader.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::super::helpers::*;
use crate::{
ast::{self, Span, WithSpan},
ast::{self, WithSpan},
common::preview_features::GENERATOR,
configuration::Generator,
diagnostics::*,
Expand Down Expand Up @@ -95,22 +95,18 @@ impl GeneratorLoader {
.or_else(|| args.get(EXPERIMENTAL_FEATURES_KEY))
.map(|v| (v.as_array().to_str_vec(), v.span()));

let (raw_preview_features, span) = match preview_features_arg {
Some((Ok(arr), span)) => (arr, span),
Some((Err(err), span)) => {
let preview_features = match preview_features_arg {
Some((Ok(arr), span)) => {
let (features, mut diag) = parse_and_validate_preview_features(arr, &GENERATOR, span);
diagnostics.append(&mut diag);

Some(features)
}
Some((Err(err), _)) => {
diagnostics.push_error(err);
(Vec::new(), span)
None
}
None => (Vec::new(), Span::empty()),
};

let preview_features = if !raw_preview_features.is_empty() {
let (features, mut diag) = parse_and_validate_preview_features(raw_preview_features, &GENERATOR, span);
diagnostics.append(&mut diag);

features
} else {
vec![]
None => None,
};

for prop in &ast_generator.properties {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,38 +17,39 @@ impl GeneratorSerializer {
}

fn lower_generator(generator: &Generator) -> ast::GeneratorConfig {
let mut arguments: Vec<ast::Argument> = vec![super::lower_string_from_env_var("provider", &generator.provider)];
let mut properties: Vec<ast::Argument> =
vec![super::lower_string_from_env_var("provider", &generator.provider)];

if let Some(output) = &generator.output {
arguments.push(super::lower_string_from_env_var("output", output));
properties.push(super::lower_string_from_env_var("output", output));
}

if !&generator.preview_features.is_empty() {
let features: Vec<ast::Expression> = generator
.preview_features
if let Some(ref features) = dbg!(&generator.preview_features) {
let features: Vec<ast::Expression> = features
.iter()
.map(|f| ast::Expression::StringValue(f.to_string(), ast::Span::empty()))
.collect::<Vec<ast::Expression>>();

arguments.push(ast::Argument::new_array("previewFeatures", features));
properties.push(dbg!(ast::Argument::new_array("previewFeatures", features)));
}

let platform_values: Vec<ast::Expression> = generator
.binary_targets
.iter()
.map(|p| lower_string_from_env_var("binaryTargets", p).value)
.collect();

if !platform_values.is_empty() {
arguments.push(ast::Argument::new_array("binaryTargets", platform_values));
properties.push(ast::Argument::new_array("binaryTargets", platform_values));
}

for (key, value) in &generator.config {
arguments.push(ast::Argument::new_string(key, value.to_string()));
properties.push(ast::Argument::new_string(key, value.to_string()));
}

ast::GeneratorConfig {
name: ast::Identifier::new(&generator.name),
properties: arguments,
properties,
documentation: generator.documentation.clone().map(|text| ast::Comment { text }),
span: ast::Span::empty(),
}
Expand Down
44 changes: 44 additions & 0 deletions libs/datamodel/core/tests/config/generators.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use datamodel::Datamodel;

use crate::common::*;

#[test]
Expand Down Expand Up @@ -420,3 +422,45 @@ fn empty_preview_features_array_with_empty_space_should_work() {

assert!(config.preview_features().is_empty());
}

#[test]
fn empty_preview_features_are_kept_when_rendering() {
let schema = indoc! {r#"
generator js1 {
provider = "a_cat"
previewFeatures = []
}
"#};

let config = parse_configuration(schema);
let rendered = datamodel::render_datamodel_and_config_to_string(&Datamodel::default(), &config);

let expected = expect![[r#"
generator js1 {
provider = "a_cat"
previewFeatures = []
}
"#]];

expected.assert_eq(&rendered);
}

#[test]
fn not_defining_preview_features_should_not_add_them_as_empty_when_rendering() {
let schema = indoc! {r#"
generator js1 {
provider = "a_cat"
}
"#};

let config = parse_configuration(schema);
let rendered = datamodel::render_datamodel_and_config_to_string(&Datamodel::default(), &config);

let expected = expect![[r#"
generator js1 {
provider = "a_cat"
}
"#]];

expected.assert_eq(&rendered);
}

0 comments on commit 6d16e41

Please sign in to comment.