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
//! # MCAI Build
//!
//! This crates allows to export `Cargo.toml` variables at compile time, so that they can be used at execution time.
//!
//! ## Usage
//!
//! 1. Add `mcai_build` in the `build-dependencies` of your package.
//! 2. Add [`serde_json`](https://crates.io/crates/serde_json) in the `dependencies` of your package.
//! 3. Add a `build.rs` file next to your `Cargo.toml` that contains the following code:
//!
//!
//! ```ignore
//! fn main() {
//!   mcai_build::build_mcai_info()
//! }
//! ```
//!
//! 4. You can now use the exported variables in your code:
//!
//! ```ignore
//! use cargo_toml::Package;
//!
//! let package: Package = include!(concat!(env!("OUT_DIR"), "/mcai_build.rs"));
//! ```

use mcai_license::McaiWorkerLicense;
use std::{io::Write, str::FromStr};

pub fn build_mcai_info() {
  let manifest = cargo_toml::Manifest::from_path("./Cargo.toml").unwrap();
  if let Some(inherited_license) = manifest.package.clone().unwrap().license {
    if let Ok(license) = inherited_license.get() {
      if let Err(error) = McaiWorkerLicense::from_str(license) {
        println!("cargo:warning={}. Possible values: 'Commercial', 'Private' or a SPDX Open Source license identifier.", error);
      }
    } else {
      println!("cargo:warning=License field is not properly inherited");
    }
  } else {
    println!("cargo:warning=License field is mandatory for MCAI workers");
  }
  let package = serde_json::to_string(&manifest.package).unwrap();
  let dst = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("mcai_build.rs");
  let mut built_file = std::fs::File::create(dst).unwrap();
  let content = format!("serde_json::from_str(r#\"{}\"#).unwrap()", package);
  built_file.write_all(content.as_bytes()).unwrap();
  println!("cargo:rerun-if-changed=build.rs")
}