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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! # rsgen-avro
//!
//! **[Apache Avro](https://avro.apache.org/)** is a data serialization system which provides
//! rich data structures and a compact, fast, binary data format.
//!
//! All data in Avro is schematized, as in the following example:
//!
//! ```text
//! {
//!     "type": "record",
//!     "name": "test",
//!     "fields": [
//!         {"name": "a", "type": "long", "default": 42},
//!         {"name": "b", "type": "string"}
//!     ]
//! }
//! ```
//!
//! The **[avro-rs](https://github.com/flavray/avro-rs)** crate provides a way to
//! read and write Avro data with both Avro-specialized and Rust serde-compatible types.
//!
//! **[rsgen-avro]** provides a way to generate Rust serde-compatible types based on Avro schemas. Both a command line tool and library crate are available.
//!
//! # Using the library
//!
//! Add to your Cargo.toml:
//!
//! ```text
//! [dependencies]
//! rsgen-avro = "x.y.z"
//! ```
//!
//! Add at the top of the crate:
//!
//! ```rust
//! extern crate rsgen_avro;
//! ```
//!
//! Then, the basic usage is:
//!
//! ```rust
//! # extern crate avro_rs;
//! # extern crate rsgen_avro;
//! use std::io::{stdout, Write};
//! use avro_rs::Schema;
//! use rsgen_avro::{Source, Generator};
//!
//! let raw_schema = r#"
//! {
//!     "type": "record",
//!     "name": "test",
//!     "fields": [
//!         {"name": "a", "type": "long", "default": 42},
//!         {"name": "b", "type": "string"}
//!     ]
//! }
//! "#;
//!
//! let schema = Schema::parse_str(&raw_schema).unwrap();
//! let source = Source::Schema(&schema);
//!
//! let mut out: Box<Write> = Box::new(stdout());
//!
//! let g = Generator::new().unwrap();
//! g.gen(&source, &mut out).unwrap();
//! ```
//!
//! This will generate the following output:
//!
//! ```text
//! #[serde(default)]
//! #[derive(Debug, Deserialize, Serialize)]
//! pub struct Test {
//!     pub a: i64,
//!     pub b: String,
//! }
//!
//! impl Default for Test {
//!     fn default() -> Test {
//!         Test {
//!             a: 42,
//!             b: String::default(),
//!         }
//!     }
//! }
//! ```
//!
//! Various `Schema` sources can be used with `Generator`'s `.gen(..)` method:
//!
//! ```rust
//! # extern crate avro_rs;
//! # use avro_rs::Schema;
//! pub enum Source<'a> {
//!     Schema(&'a Schema),
//!     SchemaStr(&'a str),
//!     FilePath(&'a str),
//!     DirPath(&'a str),
//! }
//! ```
//!
//! Note also that the `Generator` can be customized with a builder:
//!
//! ```rust
//! # use rsgen_avro::Generator;
//! let g = Generator::builder().precision(2).build().unwrap();
//! ```

extern crate avro_rs;
extern crate by_address;
extern crate failure;
#[macro_use]
extern crate failure_derive;
extern crate heck;
#[macro_use]
extern crate lazy_static;
#[cfg_attr(test, macro_use)]
extern crate matches;
extern crate serde_json;
extern crate tera;

mod templates;

use std::collections::VecDeque;
use std::fs::File;
use std::io::prelude::*;

use avro_rs::{schema::RecordField, Schema};
use failure::Error;

use templates::*;

/// Describes errors happened while generating Rust code.
#[derive(Fail, Debug)]
#[fail(display = "Rsgen failure: {}", _0)]
pub struct RsgenError(String);

impl RsgenError {
    pub fn new<S>(msg: S) -> RsgenError
    where
        S: Into<String>,
    {
        RsgenError(msg.into())
    }
}

/// Represents a schema input source.
pub enum Source<'a> {
    /// An Avro schema enum from `avro-rs` crate.
    Schema(&'a Schema),
    /// An Avro schema string in json format.
    SchemaStr(&'a str),
    /// Path to a file containing an Avro schema in json format.
    FilePath(&'a str),
    /// Path to a directory containing multiple files in Avro schema.
    DirPath(&'a str),
}

/// The main component of this library.
/// It is stateless can be reused many times.
pub struct Generator {
    templater: Templater,
    add_imports: bool,
}

impl Generator {
    /// Create a new `Generator` through a builder with default config.
    pub fn new() -> Result<Generator, Error> {
        GeneratorBuilder::new().build()
    }

    /// Returns a fluid builder for custom `Generator` instantiation.
    pub fn builder() -> GeneratorBuilder {
        GeneratorBuilder::new()
    }

    /// Generates Rust code from an Avro schema `Source`.
    /// Writes all generated types to the ouput.
    pub fn gen(&self, source: &Source, output: &mut Box<Write>) -> Result<(), Error> {
        if self.add_imports {
            output.write_all(IMPORTS.as_bytes())?;
        }

        match source {
            Source::Schema(schema) => self.gen_in_order(schema, output)?,

            Source::SchemaStr(raw_schema) => {
                let schema = Schema::parse_str(&raw_schema)?;
                self.gen_in_order(&schema, output)?
            }

            Source::FilePath(schema_file) => {
                let mut raw_schema = String::new();
                File::open(&schema_file)?.read_to_string(&mut raw_schema)?;
                let schema = Schema::parse_str(&raw_schema)?;
                self.gen_in_order(&schema, output)?
            }

            Source::DirPath(schemas_dir) => {
                for entry in std::fs::read_dir(schemas_dir)? {
                    let path = entry?.path();
                    if !path.is_dir() {
                        let mut raw_schema = String::new();
                        File::open(&path)?.read_to_string(&mut raw_schema)?;
                        let schema = Schema::parse_str(&raw_schema)?;
                        self.gen_in_order(&schema, output)?
                    }
                }
            }
        }

        Ok(())
    }

    /// Given an Avro `schema`:
    /// * Find its ordered, nested dependencies with `deps_stack(schema)`
    /// * Pops sub-schemas and generate appropriate Rust types
    /// * Keeps tracks of nested schema->name with `GenState` mapping
    /// * Appends generated Rust types to the output
    fn gen_in_order(&self, schema: &Schema, output: &mut Box<Write>) -> Result<(), Error> {
        let mut gs = GenState::new();
        let mut deps = deps_stack(schema);

        while let Some(s) = deps.pop() {
            match s {
                // Simply generate code
                Schema::Fixed { .. } => {
                    let code = &self.templater.str_fixed(&s)?;
                    output.write_all(code.as_bytes())?
                }
                Schema::Enum { .. } => {
                    let code = &self.templater.str_enum(&s)?;
                    output.write_all(code.as_bytes())?
                }

                // Generate code with potentially nested types
                Schema::Record { .. } => {
                    let code = &self.templater.str_record(&s, &gs)?;
                    output.write_all(code.as_bytes())?
                }

                // Register inner type for it to be used as a nested type later
                Schema::Array(inner) => {
                    let type_str = array_type(inner, &gs)?;
                    gs.put_type(&s, type_str)
                }
                Schema::Map(inner) => {
                    let type_str = map_type(inner, &gs)?;
                    gs.put_type(&s, type_str)
                }
                Schema::Union(union) => {
                    if let [Schema::Null, inner] = union.variants() {
                        let type_str = option_type(inner, &gs)?;
                        gs.put_type(&s, type_str)
                    }
                }

                _ => Err(RsgenError::new(format!("Not a valid root schema: {:?}", s)))?,
            }
        }
        Ok(())
    }
}

/// Utility function to find the ordered, nested dependencies of an Avro `schema`.
/// Explores nested `schema`s in a breadth-first fashion, pushing them on a stack
/// at the same time in order to have them ordered.
/// It is similar to traversing the `schema` tree in a post-order fashion.
fn deps_stack(schema: &Schema) -> Vec<&Schema> {
    let mut deps = Vec::new();
    let mut q = VecDeque::new();

    q.push_back(schema);
    while !q.is_empty() {
        let s = q.pop_front().unwrap();

        match s {
            // No nested schemas, add them to the result stack
            Schema::Fixed { .. } => deps.push(s),
            Schema::Enum { .. } => deps.push(s),

            // Explore the record fields for potentially nested schemas
            Schema::Record { fields, .. } => {
                deps.push(s);

                for RecordField { schema: sr, .. } in fields {
                    match sr {
                        // No nested schemas, add them to the result stack
                        Schema::Fixed { .. } => deps.push(sr),
                        Schema::Enum { .. } => deps.push(sr),

                        // Push to the exploration queue for further checks
                        Schema::Record { .. } => q.push_back(sr),

                        // Push to the exploration queue, depending on the inner schema format
                        Schema::Map(sc) | Schema::Array(sc) => match &**sc {
                            Schema::Fixed { .. }
                            | Schema::Enum { .. }
                            | Schema::Record { .. }
                            | Schema::Map(..)
                            | Schema::Array(..)
                            | Schema::Union(..) => q.push_back(&**sc),
                            _ => (),
                        },
                        Schema::Union(union) => {
                            if let [Schema::Null, sc] = union.variants() {
                                match sc {
                                    Schema::Fixed { .. }
                                    | Schema::Enum { .. }
                                    | Schema::Record { .. }
                                    | Schema::Map(..)
                                    | Schema::Array(..)
                                    | Schema::Union(..) => q.push_back(sc),
                                    _ => (),
                                }
                            }
                        }
                        _ => (),
                    };
                }
            }

            // Depending on the inner schema type ...
            Schema::Map(sc) | Schema::Array(sc) => match &**sc {
                // ... Needs further checks, push to the exploration queue
                Schema::Fixed { .. }
                | Schema::Enum { .. }
                | Schema::Record { .. }
                | Schema::Map(..)
                | Schema::Array(..)
                | Schema::Union(..) => q.push_back(&**sc),
                // ... Not nested, can be pushed to the result stack
                _ => deps.push(s),
            },
            Schema::Union(union) => {
                if let [Schema::Null, sc] = union.variants() {
                    match sc {
                        // ... Needs further checks, push to the exploration queue
                        Schema::Fixed { .. }
                        | Schema::Enum { .. }
                        | Schema::Record { .. }
                        | Schema::Map(..)
                        | Schema::Array(..)
                        | Schema::Union(..) => q.push_back(sc),
                        // ... Not nested, can be pushed to the result stack
                        _ => deps.push(s),
                    }
                }
            }

            // Ignore all other schema formats
            _ => (),
        }
    }

    deps
}

/// A builder class to customize `Generator`.
pub struct GeneratorBuilder {
    precision: usize,
    add_imports: bool,
}

impl GeneratorBuilder {
    /// Creates a new `GeneratorBuilder`.
    pub fn new() -> GeneratorBuilder {
        GeneratorBuilder {
            precision: 3,
            add_imports: false,
        }
    }

    /// Sets the precision for default values of f32/f64 fields.
    pub fn precision(mut self, precision: usize) -> GeneratorBuilder {
        self.precision = precision;
        self
    }

    /// Adds `extern crate ...` to the first generated lines.
    pub fn add_imports(mut self, add_imports: bool) -> GeneratorBuilder {
        self.add_imports = add_imports;
        self
    }

    /// Create a `Generator` with the builder parameters.
    pub fn build(self) -> Result<Generator, Error> {
        let mut templater = Templater::new()?;
        templater.precision = self.precision;
        Ok(Generator {
            templater,
            add_imports: self.add_imports,
        })
    }
}

#[cfg(test)]
mod tests {
    extern crate gag;

    use std::io::stdout;

    use self::gag::BufferRedirect;
    use avro_rs::schema::Name;

    use super::*;

    macro_rules! assert_schema_gen (
        ($expected:expr, $raw_schema:expr) => (
            let schema = Schema::parse_str($raw_schema).unwrap();
            let source = Source::Schema(&schema);

            let mut buf = BufferRedirect::stdout().unwrap();
            let mut out: Box<Write> = Box::new(stdout());

            let g = Generator::builder().add_imports(true).build().unwrap();
            g.gen(&source, &mut out).unwrap();

            let mut res = String::new();
            buf.read_to_string(&mut res).unwrap();
            buf.into_inner();

            assert_eq!($expected, &res);
        );
    );

    #[test]
    fn simple() {
        let raw_schema = r#"
{
  "type": "record",
  "name": "test",
  "fields": [
    {"name": "a", "type": "long", "default": 42},
    {"name": "b", "type": "string"}
  ]
}
"#;

        let expected = "#[macro_use]
extern crate serde_derive;
extern crate serde;

#[serde(default)]
#[derive(Debug, Deserialize, Serialize)]
pub struct Test {
    pub a: i64,
    pub b: String,
}

impl Default for Test {
    fn default() -> Test {
        Test {
            a: 42,
            b: String::default(),
        }
    }
}
";
        assert_schema_gen!(expected, raw_schema);
    }

    #[test]
    fn complex() {
        let raw_schema = r#"
{
  "type": "record",
  "name": "User",
  "doc": "Hi there.",
  "fields": [
    {"name": "name", "type": "string", "default": ""},
    {"name": "favorite_number",  "type": "int", "default": 7},
    {"name": "likes_pizza", "type": "boolean", "default": false},
    {"name": "oye", "type": "float", "default": 1.1},
    {"name": "aa-i32",
     "type": {"type": "array", "items": {"type": "array", "items": "int"}},
     "default": [[0], [12, -1]]}
  ]
}
"#;

        let expected = r#"#[macro_use]
extern crate serde_derive;
extern crate serde;

/// Hi there.
#[serde(default)]
#[derive(Debug, Deserialize, Serialize)]
pub struct User {
    #[serde(rename = "aa-i32")]
    pub aa_i32: Vec<Vec<i32>>,
    pub favorite_number: i32,
    pub likes_pizza: bool,
    pub name: String,
    pub oye: f32,
}

impl Default for User {
    fn default() -> User {
        User {
            aa_i32: vec![vec![0], vec![12, -1]],
            favorite_number: 7,
            likes_pizza: false,
            name: "".to_owned(),
            oye: 1.100,
        }
    }
}
"#;

        assert_schema_gen!(expected, raw_schema);
    }

    #[test]
    fn deps() {
        let raw_schema = r#"
{
  "type": "record",
  "name": "User",
  "fields": [
    {"name": "name", "type": "string", "default": "unknown"},
    {"name": "address",
     "type": {
       "type": "record",
       "name": "Address",
       "fields": [
         {"name": "city", "type": "string", "default": "unknown"},
         {"name": "country",
          "type": {"type": "enum", "name": "Country", "symbols": ["FR", "JP"]}
         }
       ]
     }
    }
  ]
}
"#;

        let schema = Schema::parse_str(&raw_schema).unwrap();
        let mut deps = deps_stack(&schema);

        let s = deps.pop().unwrap();
        assert_matches!(s, Schema::Enum{ name: Name { ref name, ..}, ..} if name == "Country");

        let s = deps.pop().unwrap();
        assert_matches!(s, Schema::Record{ name: Name { ref name, ..}, ..} if name == "Address");

        let s = deps.pop().unwrap();
        assert_matches!(s, Schema::Record{ name: Name { ref name, ..}, ..} if name == "User");

        let s = deps.pop();
        assert_matches!(s, None);
    }
}