1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use crate::value::{Array, Documentation, Env, Text, Value};
use psl::PreviewFeature;
use std::{borrow::Cow, fmt};

/// The generator block of the datasource.
#[derive(Debug)]
pub struct Generator<'a> {
    name: &'a str,
    provider: Env<'a>,
    output: Option<Env<'a>>,
    preview_features: Option<Array<Text<PreviewFeature>>>,
    binary_targets: Array<Env<'a>>,
    documentation: Option<Documentation<'a>>,
    config: Vec<(&'a str, Value<'a>)>,
}

impl<'a> Generator<'a> {
    /// A new generator with the required values set.
    ///
    /// ```ignore
    /// generator js {
    /// //        ^^ name
    ///   provider = "prisma-client-js"
    /// //            ^^^^^^^^^^^^^^^^ provider
    /// }
    /// ```
    pub fn new(name: &'a str, provider: impl Into<Env<'a>>) -> Self {
        Self {
            name,
            provider: provider.into(),
            output: None,
            preview_features: None,
            binary_targets: Array::new(),
            documentation: None,
            config: Vec::new(),
        }
    }

    /// Sets an output target.
    ///
    /// ```ignore
    /// generator js {
    ///   output = env("OUTPUT_DIR")
    /// //              ^^^^^^^^^^ this
    /// }
    /// ```
    pub fn output(&mut self, output: impl Into<Env<'a>>) {
        self.output = Some(output.into());
    }

    /// Add a new preview feature to the generator block.
    ///
    /// ```ignore
    /// generator js {
    ///   previewFeatures = ["postgresqlExtensions"]
    /// //                    ^^^^^^^^^^^^^^^^^^^^ pushed here
    /// }
    /// ```
    pub fn push_preview_feature(&mut self, feature: PreviewFeature) {
        let features = self.preview_features.get_or_insert_with(Array::new);
        features.push(Text(feature));
    }

    /// Add a new binary target to the generator block.
    ///
    /// ```ignore
    /// generator js {
    ///   binaryTargets = [env("FOO_TARGET")]
    /// //                 ^^^^^^^^^^^^^^^^^ pushed here
    /// }
    /// ```
    pub fn push_binary_target(&mut self, target: impl Into<Env<'a>>) {
        self.binary_targets.push(target.into())
    }

    /// Set the generator block documentation.
    ///
    /// ```ignore
    /// /// This here is the documentation.
    /// generator js {
    ///   provider = "prisma-client-js"
    /// }
    /// ```
    pub fn documentation(&mut self, docs: impl Into<Cow<'a, str>>) {
        self.documentation = Some(Documentation(docs.into()));
    }

    /// Add a custom config value to the block.
    ///
    /// ```ignore
    /// generator js {
    ///   provider = "prisma-client-js"
    ///   custom   = "foo"
    /// //           ^^^^^ value
    /// //^^^^^^ key
    /// }
    /// ```
    pub fn push_config_value(&mut self, key: &'a str, val: impl Into<Value<'a>>) {
        self.config.push((key, val.into()));
    }

    /// Create a rendering from a PSL generator.
    pub fn from_psl(psl_gen: &'a psl::Generator) -> Self {
        let preview_features = psl_gen
            .preview_features
            .map(|f| f.iter().map(Text).collect::<Vec<Text<_>>>())
            .map(Array::from);

        let binary_targets: Vec<Env<'_>> = psl_gen.binary_targets.iter().map(Env::from).collect();

        let config = psl_gen.config.iter().map(|(k, v)| (k.as_str(), v.into())).collect();

        Self {
            name: &psl_gen.name,
            provider: Env::from(&psl_gen.provider),
            output: psl_gen.output.as_ref().map(Env::from),
            preview_features,
            binary_targets: Array::from(binary_targets),
            documentation: psl_gen.documentation.as_deref().map(Cow::Borrowed).map(Documentation),
            config,
        }
    }
}

impl<'a> fmt::Display for Generator<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(ref doc) = self.documentation {
            doc.fmt(f)?;
        }

        writeln!(f, "generator {} {{", self.name)?;
        writeln!(f, "provider = {}", self.provider)?;

        if let Some(output) = self.output {
            writeln!(f, "output = {output}")?;
        }

        if let Some(ref features) = self.preview_features {
            writeln!(f, "previewFeatures = {features}")?;
        }

        if !self.binary_targets.is_empty() {
            writeln!(f, "binaryTargets = {}", self.binary_targets)?;
        }

        for (k, v) in self.config.iter() {
            writeln!(f, "{k} = {v}")?;
        }

        f.write_str("}\n")?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::{configuration::*, value::*};
    use expect_test::expect;
    use psl::PreviewFeature;

    #[test]
    fn kitchen_sink() {
        let mut generator = Generator::new("client", Env::value("prisma-client-js"));

        generator.documentation("Here comes the sun.\n\nAnd I say,\nIt's alright.");

        generator.output(Env::value("/dev/null"));
        generator.push_binary_target(Env::variable("BINARY TARGET"));

        generator.push_preview_feature(PreviewFeature::MultiSchema);
        generator.push_preview_feature(PreviewFeature::PostgresqlExtensions);

        generator.push_config_value("customValue", "meow");
        generator.push_config_value("otherValue", "purr");

        generator.push_config_value("customFeatures", vec![Value::from("enums"), Value::from("models")]);
        generator.push_config_value(
            "afterGenerate",
            vec![
                Value::from("lambda"),
                Vec::<Value>::new().into(),
                vec![
                    Value::from("print"),
                    vec![Value::from("quote"), Value::from("done!")].into(),
                ]
                .into(),
            ],
        );

        let expected = expect![[r#"
            /// Here comes the sun.
            ///
            /// And I say,
            /// It's alright.
            generator client {
              provider        = "prisma-client-js"
              output          = "/dev/null"
              previewFeatures = ["multiSchema", "postgresqlExtensions"]
              binaryTargets   = [env("BINARY TARGET")]
              customValue     = "meow"
              otherValue      = "purr"
              customFeatures  = ["enums", "models"]
              afterGenerate   = ["lambda", [], ["print", ["quote", "done!"]]]
            }
        "#]];

        let rendered = psl::reformat(&format!("{generator}"), 2).unwrap();
        expected.assert_eq(&rendered)
    }
}