mcai_build/
lib.rs

1//! # MCAI Build
2//!
3//! This crates allows to export `Cargo.toml` variables at compile time, so that they can be used at execution time.
4//!
5//! ## Usage
6//!
7//! 1. Add `mcai_build` in the `build-dependencies` of your package.
8//! 2. Add [`serde_json`](https://crates.io/crates/serde_json) in the `dependencies` of your package.
9//! 3. Add a `build.rs` file next to your `Cargo.toml` that contains the following code:
10//!
11//!
12//! ```ignore
13//! fn main() {
14//!   mcai_build::build_mcai_info()
15//! }
16//! ```
17//!
18//! 4. You can now use the exported variables in your code:
19//!
20//! ```ignore
21//! use cargo_toml::Package;
22//!
23//! let package: Package = include!(concat!(env!("OUT_DIR"), "/mcai_build.rs"));
24//! ```
25
26use mcai_license::McaiWorkerLicense;
27use std::{io::Write, str::FromStr};
28
29pub fn build_mcai_info() {
30  let manifest = cargo_toml::Manifest::from_path("./Cargo.toml").unwrap();
31  if let Some(inherited_license) = manifest.package.clone().unwrap().license {
32    if let Ok(license) = inherited_license.get() {
33      if let Err(error) = McaiWorkerLicense::from_str(license) {
34        println!("cargo:warning={}. Possible values: 'Commercial', 'Private' or a SPDX Open Source license identifier.", error);
35      }
36    } else {
37      println!("cargo:warning=License field is not properly inherited");
38    }
39  } else {
40    println!("cargo:warning=License field is mandatory for MCAI workers");
41  }
42  let package = serde_json::to_string(&manifest.package).unwrap();
43  let dst = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("mcai_build.rs");
44  let mut built_file = std::fs::File::create(dst).unwrap();
45  let content = format!("serde_json::from_str(r#\"{}\"#).unwrap()", package);
46  built_file.write_all(content.as_bytes()).unwrap();
47  println!("cargo:rerun-if-changed=build.rs")
48}