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
use std::collections::{HashMap, HashSet};

pub use trans_schema;
use trans_schema::*;

pub trait Generator {
    fn new(name: &str, version: &str) -> Self;
    fn add_only(&mut self, schema: &Schema);
    fn result(self) -> HashMap<String, String>;
}

pub struct GeneratorImpl<T: Generator> {
    inner: T,
    added: HashMap<Name, Schema>,
}

impl<T: Generator> GeneratorImpl<T> {
    pub fn new(name: &str, version: &str) -> Self {
        Self {
            inner: T::new(name, version),
            added: HashMap::new(),
        }
    }
    pub fn add(&mut self, schema: &Schema) {
        let schema_name = schema.full_name();
        let current = self.added.get(&schema_name);
        if let Some(current) = current {
            assert_eq!(
                current, schema,
                "Two schemas with same name but different structure"
            );
            return;
        }
        self.added.insert(schema_name, schema.clone());
        match schema {
            Schema::Struct(Struct { fields, .. }) => {
                for field in fields {
                    self.add(&field.schema);
                }
            }
            Schema::OneOf { variants, .. } => {
                for variant in variants {
                    for field in &variant.fields {
                        self.add(&field.schema);
                    }
                }
            }
            Schema::Option(inner) => {
                self.add(inner);
            }
            Schema::Vec(inner) => {
                self.add(inner);
            }
            Schema::Map(key_type, value_type) => {
                self.add(key_type);
                self.add(value_type);
            }
            Schema::Bool
            | Schema::Int32
            | Schema::Int64
            | Schema::Float32
            | Schema::Float64
            | Schema::String
            | Schema::Enum { .. } => {}
        }
        self.inner.add_only(schema);
    }
    pub fn result(self) -> HashMap<String, String> {
        self.inner.result()
    }
    pub fn write_to<P: AsRef<std::path::Path>>(self, dir: P) -> std::io::Result<()> {
        use std::path::Path;
        let dir = dir.as_ref();
        for (path, content) in self.result() {
            if let Some(parent) = Path::new(&path).parent() {
                std::fs::create_dir_all(dir.join(parent))?;
            }
            let mut file = std::fs::File::create(dir.join(path))?;
            use std::io::Write;
            file.write_all(content.as_bytes())?;
        }
        Ok(())
    }
}

pub fn add_all(files: &mut HashMap<String, String>, dir: &include_dir::Dir, prefix: &str) {
    for file in dir.files() {
        files.insert(
            format!("{}/{}", prefix, file.path().to_str().unwrap()),
            file.contents_utf8().unwrap().to_owned(),
        );
    }
    for subdir in dir.dirs() {
        add_all(files, subdir, prefix);
    }
}

pub struct Writer {
    content: String,
    ident_level: usize,
}

impl Writer {
    pub fn new() -> Self {
        Self {
            content: String::new(),
            ident_level: 0,
        }
    }
    pub fn inc_ident(&mut self) {
        self.ident_level += 1;
    }
    pub fn dec_ident(&mut self) {
        self.ident_level -= 1;
    }
    pub fn get(self) -> String {
        assert_eq!(self.ident_level, 0, "Incorrect indentation");
        self.content
    }
}

impl std::fmt::Write for Writer {
    fn write_str(&mut self, s: &str) -> std::fmt::Result {
        for c in s.chars() {
            if c != '\n' && self.content.chars().last().unwrap_or('\n') == '\n' {
                for _ in 0..self.ident_level * 4 {
                    self.content.push(' ');
                }
            }
            self.content.push(c);
        }
        Ok(())
    }
}