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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#![deny(clippy::all)]
#![deny(clippy::pedantic)]

use std::{convert::TryInto, fmt, path::PathBuf, str::FromStr};

use proptest::{arbitrary::Arbitrary, strategy::Strategy};

#[cfg(feature = "build-binary")]
use structopt::StructOpt;

pub mod schema;

// TODO: clean up unwraps

// TODO: create a suitable error type

#[derive(Clone, Copy, Debug, test_strategy::Arbitrary)]
pub struct Seed {
    inner: [u8; 32],
}

impl Seed {
    #[must_use]
    pub const fn fixed() -> Self {
        Self { inner: [0_u8; 32] }
    }
}

impl Default for Seed {
    /// By default seeds are non-deterministic.
    fn default() -> Self {
        Self {
            inner: rand::random(),
        }
    }
}

impl FromStr for Seed {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let inner = {
            let bytes = base64::decode(s).unwrap();
            if bytes.len() == 32 {
                bytes.try_into().unwrap()
            } else {
                return Err("invalid input");
            }
        };

        Ok(Seed { inner })
    }
}

impl fmt::Display for Seed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        write!(f, "{}", base64::encode(self.inner))
    }
}

#[derive(Debug)]
#[cfg_attr(feature = "build-binary", derive(StructOpt))]
pub enum Command {
    /// Validate IPLD schemas and data
    Validate {
        /// Path to IPLD schema file to validate.
        #[cfg_attr(feature = "build-binary", structopt(parse(from_os_str)))]
        schema_file: PathBuf,

        /// Path to IPLD data file to validate against the specified schema.
        #[cfg_attr(feature = "build-binary", structopt(parse(from_os_str)))]
        data_file: Option<PathBuf>,
    },
    /// Generate IPLD schemas and data
    Generate {
        /// Explicitly seed the PRNG for deterministic output.
        ///
        /// If unspecified, a random seed is used.
        #[cfg_attr(feature = "build-binary", structopt(long, parse(try_from_str)))]
        seed: Option<Seed>,

        /// Path to IPLD schema file to use when generating data.
        ///
        /// If unspecified, generates a schema instead of data.
        #[cfg_attr(feature = "build-binary", structopt(parse(from_os_str)))]
        schema_file: Option<PathBuf>,
    },
}

#[derive(Debug)]
#[cfg_attr(feature = "build-binary", derive(StructOpt))]
#[cfg_attr(feature = "build-binary", structopt(name = env!("CARGO_PKG_NAME"), version = env!("CARGO_PKG_VERSION"), author = env!("CARGO_PKG_AUTHORS"), about = env!("CARGO_PKG_DESCRIPTION")))]
pub struct Opt {
    #[cfg_attr(feature = "build-binary", structopt(subcommand))]
    cmd: Command,
}

#[allow(clippy::result_unit_err)]
#[allow(clippy::missing_errors_doc)]
pub fn run<W: std::io::Write>(opt: &Opt, output: &mut W) -> Result<(), ()> {
    match &opt.cmd {
        Command::Validate {
            schema_file,
            data_file,
        } => validate(schema_file, data_file, output),
        Command::Generate { seed, schema_file } => {
            generate(&seed.unwrap_or_default(), schema_file, output)
        }
    }
}

fn validate<P: AsRef<std::path::Path> + std::fmt::Debug, W: std::io::Write>(
    schema_file: &P,
    data_file: &Option<P>,
    out: &mut W,
) -> Result<(), ()> {
    match data_file {
        None => validate_schema(schema_file, out),
        Some(data) => validate_data(schema_file, data, out),
    }
}

fn validate_schema<P: AsRef<std::path::Path> + std::fmt::Debug, W: std::io::Write>(
    schema_file: &P,
    _out: &mut W,
) -> Result<(), ()> {
    schema::schema_dsl::parse(&std::fs::read_to_string(schema_file).unwrap()).unwrap();
    // TODO: write
    Ok(())
}

fn validate_data<P: AsRef<std::path::Path> + std::fmt::Debug, W: std::io::Write>(
    schema_file: &P,
    data_file: &P,
    _out: &mut W,
) -> Result<(), ()> {
    validate_schema(schema_file, &mut std::io::sink())?;

    todo!(
        "validate data ({:?}) using schema ({:?})",
        data_file,
        schema_file
    );
}

fn generate<P, W>(seed: &Seed, schema_file: &Option<P>, out: &mut W) -> Result<(), ()>
where
    P: AsRef<std::path::Path> + std::fmt::Debug,
    W: std::io::Write,
{
    let mut out = std::io::BufWriter::new(out);

    match schema_file {
        None => generate_schema(seed, &mut out),
        Some(schema) => generate_data(seed, schema, &mut out),
    }
}

fn generate_schema<W: std::io::Write>(seed: &Seed, out: &mut W) -> Result<(), ()> {
    let config = proptest::test_runner::Config::default();
    let rng = proptest::test_runner::TestRng::from_seed(
        proptest::test_runner::RngAlgorithm::ChaCha,
        &seed.inner,
    );
    let mut runner = proptest::test_runner::TestRunner::new_with_rng(config, rng);

    let schema = schema::Schema::arbitrary()
        .new_tree(&mut runner)
        .unwrap()
        .current();

    writeln!(out, "##").unwrap();
    writeln!(
        out,
        "## Deterministically generated with {} {}",
        env!("CARGO_PKG_NAME"),
        env!("CARGO_PKG_VERSION")
    )
    .unwrap();
    writeln!(out, "##").unwrap();
    writeln!(out, "##   - reproduction seed: '{}'", seed).unwrap();
    writeln!(out, "##").unwrap();
    writeln!(out).unwrap();
    writeln!(out, "{}", schema).unwrap();

    Ok(())
}

fn generate_data<P: AsRef<std::path::Path> + std::fmt::Debug, W: std::io::Write>(
    seed: &Seed,
    schema_file: &P,
    out: &mut W,
) -> Result<(), ()> {
    validate_schema(schema_file, &mut std::io::sink())?;

    writeln!(out, "##").unwrap();
    writeln!(
        out,
        "## Deterministically generated with {} {}",
        env!("CARGO_PKG_NAME"),
        env!("CARGO_PKG_VERSION")
    )
    .unwrap();
    writeln!(out, "##").unwrap();
    writeln!(out, "##   - reproduction seed: '{}'", seed).unwrap();
    writeln!(out, "##   - schema file: {:?}", schema_file).unwrap(); // TODO: consider emitting a CID for the schema file's contents too
    writeln!(out, "##").unwrap();
    writeln!(out).unwrap();

    todo!(
        "generate data using seed '{}' and schema {:?}",
        seed,
        schema_file
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    use test_strategy::proptest;

    #[cfg(feature = "fast-test")]
    const CASES: u32 = 10;
    #[cfg(not(feature = "fast-test"))]
    const CASES: u32 = 1000;

    #[cfg(feature = "fast-test")]
    const MAX_SHRINK_ITERS: u32 = 2;
    #[cfg(not(feature = "fast-test"))]
    const MAX_SHRINK_ITERS: u32 = 10000;

    #[cfg(not(feature = "fast-test"))]
    use insta::assert_debug_snapshot;

    #[test]
    #[cfg(not(feature = "fast-test"))]
    fn snapshot_of_schema_generated_from_fixed_seed() {
        let seed = Some(Seed::fixed());

        let mut schema_buffer = std::io::Cursor::new(vec![]);
        run(
            &Opt {
                cmd: Command::Generate {
                    seed,
                    schema_file: None,
                },
            },
            &mut schema_buffer,
        )
        .unwrap();

        assert_debug_snapshot!(schema::schema_dsl::parse(&String::from_utf8_lossy(
            &schema_buffer.into_inner()
        ))
        .unwrap());
    }

    #[test]
    #[cfg(not(feature = "fast-test"))]
    #[ignore = "TODO: implement data generator based on a schema"]
    fn snapshot_of_data_generated_from_fixed_seed() {
        let seed = Some(Seed::fixed());

        let mut schema_file = tempfile::NamedTempFile::new().unwrap();
        run(
            &Opt {
                cmd: Command::Generate {
                    seed,
                    schema_file: None,
                },
            },
            &mut schema_file,
        )
        .unwrap();

        let mut data_buffer = std::io::Cursor::new(vec![]);
        run(
            &Opt {
                cmd: Command::Generate {
                    seed,
                    schema_file: Some(schema_file.path().into()),
                },
            },
            &mut data_buffer,
        )
        .unwrap();

        assert_debug_snapshot!(schema::schema_dsl::parse(&String::from_utf8_lossy(
            &data_buffer.into_inner()
        ))
        .unwrap());
    }

    #[proptest(cases = CASES, max_shrink_iters = MAX_SHRINK_ITERS)]
    fn generated_schemas_are_valid(seed: Seed) {
        let mut schema_file = tempfile::NamedTempFile::new()?;
        run(
            &Opt {
                cmd: Command::Generate {
                    seed: Some(seed),
                    schema_file: None,
                    // schema_file: Some(schema_file.path().into())
                },
            },
            &mut schema_file,
        )
        .unwrap();

        let mut output = std::io::Cursor::new(vec![]);
        run(
            &Opt {
                cmd: Command::Validate {
                    schema_file: schema_file.path().into(),
                    data_file: None,
                },
            },
            &mut output,
        )
        .unwrap();

        // TODO: assertions about output

        schema_file.close()?;
    }

    #[proptest(cases = CASES, max_shrink_iters = MAX_SHRINK_ITERS)]
    #[ignore = "TODO: implement data generator based on a schema"]
    fn generated_data_are_valid(seed: Seed) {
        let mut schema_file = tempfile::NamedTempFile::new()?;
        run(
            &Opt {
                cmd: Command::Generate {
                    seed: Some(seed),
                    schema_file: None,
                },
            },
            &mut schema_file,
        )
        .unwrap();

        let mut data_file = tempfile::NamedTempFile::new()?;
        run(
            &Opt {
                cmd: Command::Generate {
                    seed: Some(seed),
                    schema_file: Some(schema_file.path().into()),
                },
            },
            &mut data_file,
        )
        .unwrap();

        let mut output = std::io::Cursor::new(vec![]);
        run(
            &Opt {
                cmd: Command::Validate {
                    schema_file: schema_file.path().into(),
                    data_file: Some(data_file.path().into()),
                },
            },
            &mut output,
        )
        .unwrap();

        // TODO: assertions about output

        schema_file.close()?;
        data_file.close()?;
    }
}