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
use std::{
    env, io,
    path::{Path, PathBuf},
    process::Command,
};

/// A helper function wrapping the flatdata generator.
///
/// Can be used to write build.rs build scripts, generating outputs either from
/// a single schema, or recursively from a folder of schemas.
///
/// `schemas_path` can either be a single file, or a filder containing schemas.
/// In both cases the function will only handle files with the `.flatdata`
/// extension.
///
/// Generated files are in the same relative location, e.g.
/// ``` text
/// schemas_path/
/// ├────────────example_a/
/// │            ├─────────my_schema.flatdata
/// │            └─────────my_other_schema.flatdata
/// └────────────example_b.flatdata
/// ```
///
/// results in
/// ``` text
/// out_dir/
/// ├───────example_a/
/// │       ├─────────my_schema.rs
/// │       └─────────my_other_schema.rs
/// └───────example_b.rs
/// ```
///
/// ## Examples
///
/// `build.rs`
///
/// ```ignore
/// use std::env;
///
/// fn main() {
///     flatdata::generate("schemas_path/", &env::var("OUT_DIR").unwrap()).unwrap();
/// }
/// ```
///
/// `my_schema.rs`
///
/// ```ignore
/// #![allow(dead_code)]
///
/// include!(concat!(env!("OUT_DIR"), "/example_a/my_schema.rs"));
///
/// // re-export if desired
/// pub use my_schema::*;
/// ```
///
/// ## Development
///
/// If you are working on the generator, you can make sure your `build.rs`
/// script picks up the source by setting `FLATDATA_GENERATOR_PATH` to point to
/// the `flatdata-generator` folder.
pub fn generate(
    schemas_path: impl AsRef<Path>,
    out_dir: impl AsRef<Path>,
) -> Result<(), GeneratorError> {
    let schemas_path = schemas_path.as_ref();
    let out_dir = out_dir.as_ref();

    // create a virtualenv in the target folder
    eprintln!("creating python virtualenv");
    let _ = Command::new("python3")
        .arg("-m")
        .arg("venv")
        .arg(out_dir)
        .spawn()
        .map_err(GeneratorError::PythonError)?
        .wait()?;

    // install dependencies
    let generator_path = if let Ok(path) = env::var("FLATDATA_GENERATOR_PATH") {
        // we want to rebuild automatically if we edit the generator's code
        let path = PathBuf::from(path).canonicalize()?;
        println!("cargo:rerun-if-changed={}", path.display());
        eprintln!("installing flatdata-generator from source");
        path
    } else {
        eprintln!("installing flatdata-generator from PyPI");
        PathBuf::from("flatdata-generator==0.4.5")
    };
    let _ = Command::new(out_dir.join("bin/pip3"))
        .arg("install")
        .arg("--disable-pip-version-check")
        .arg(&generator_path)
        .spawn()
        .map_err(GeneratorError::PythonError)?
        .wait()?;

    for entry in walkdir::WalkDir::new(&schemas_path) {
        let entry = entry?;
        if entry.path().extension().map_or(true, |x| x != "flatdata") {
            continue;
        }

        let result: PathBuf = if schemas_path.is_dir() {
            out_dir
                .join(entry.path().strip_prefix(&schemas_path).unwrap())
                .with_extension("rs")
        } else {
            out_dir
                .join(entry.path().file_name().unwrap())
                .with_extension("rs")
        };
        eprintln!(
            "generating {} from {}",
            result.display(),
            schemas_path.display()
        );

        std::fs::create_dir_all(result.parent().unwrap())?;
        let exit_code = Command::new(out_dir.join("bin/flatdata-generator"))
            .arg("-g")
            .arg("rust")
            .arg("-s")
            .arg(&entry.path())
            .arg("-O")
            .arg(&result)
            .spawn()
            .map_err(|e| GeneratorError::Failure {
                schema: entry.path().into(),
                destination: result.clone(),
                error: e,
            })?
            .wait()?
            .code();

        if exit_code != Some(0) {
            return Err(GeneratorError::Failure {
                schema: entry.path().into(),
                destination: result,
                error: io::Error::new(
                    io::ErrorKind::Other,
                    match exit_code {
                        Some(code) => format!("Failed to run the generator, exit code {}", code),
                        None => "Failed to run the generator, no exit code".into(),
                    },
                ),
            });
        }

        println!("cargo:rerun-if-changed={}", entry.path().display());
    }
    Ok(())
}

/// Error type for generate function
#[derive(Debug)]
pub enum GeneratorError {
    /// Python interpreter or virtualenv not found
    PythonError(std::io::Error),
    /// Wrapper around underlying io::Error
    Io(std::io::Error),
    /// Failed to run generator
    Failure {
        /// path to the problematic schema
        schema: PathBuf,
        /// path to the generated file
        destination: PathBuf,
        /// the original io::Error
        error: std::io::Error,
    },
}

impl std::fmt::Display for GeneratorError {
    fn fmt(self: &Self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        match self {
            GeneratorError::PythonError(err) => {
                writeln!(f, "{} could not be executed", err)?;
                writeln!(
                    f,
                    "Failed to prepare virtualenv for flatdata-generator: please make sure both python3 and python3-virtualenv are installed."
                )
            }
            GeneratorError::Io(details) => {
                write!(f, "Failed to run flatdata-generator: {}", details)
            }
            GeneratorError::Failure {
                schema,
                destination,
                error,
            } => write!(
                f,
                "Failed to run generate {} from {}: {}",
                schema.display(),
                destination.display(),
                error
            ),
        }
    }
}

impl std::error::Error for GeneratorError {}

impl std::convert::From<std::io::Error> for GeneratorError {
    fn from(detail: std::io::Error) -> Self {
        GeneratorError::Io(detail)
    }
}

impl std::convert::From<walkdir::Error> for GeneratorError {
    fn from(detail: walkdir::Error) -> Self {
        GeneratorError::Io(detail.into())
    }
}