This is an automated email from the ASF dual-hosted git repository.

mssun pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/incubator-teaclave.git

commit 97aa4fc24f3db719556acfb857cc85440bd004b9
Author: Mingshen Sun <[email protected]>
AuthorDate: Sat Jan 18 20:28:50 2020 -0800

    [config] Use the jinja2 template for build time config generator
---
 config/build.rs                       |  5 ++
 config/config_gen/Cargo.toml          |  2 +
 config/config_gen/main.rs             | 97 ++++++++++++++++-------------------
 config/config_gen/templates/config.j2 | 16 ++++++
 4 files changed, 66 insertions(+), 54 deletions(-)

diff --git a/config/build.rs b/config/build.rs
index f0428c3..06d3331 100644
--- a/config/build.rs
+++ b/config/build.rs
@@ -13,15 +13,20 @@ fn main() {
     let out_dir = env::var("OUT_DIR").expect("$OUT_DIR not set. Please build 
with cargo");
     let dest_file = Path::new(&out_dir).join("build_config.rs");
     println!("cargo:rerun-if-changed=config_gen/main.rs");
+    println!("cargo:rerun-if-changed=config_gen/templates/config.j2");
     println!("cargo:rerun-if-changed=build.config.toml");
     println!("cargo:rerun-if-changed=build.rs");
     let c = Command::new("cargo")
         .args(&[
             "run",
+            "--target-dir",
+            "/tmp/config_gen/target",
             "--manifest-path",
             "config_gen/Cargo.toml",
             "--",
+            "-t",
             "build.config.toml",
+            "-o",
             &dest_file.to_string_lossy(),
         ])
         .output()
diff --git a/config/config_gen/Cargo.toml b/config/config_gen/Cargo.toml
index 4a62d46..796fbcb 100644
--- a/config/config_gen/Cargo.toml
+++ b/config/config_gen/Cargo.toml
@@ -11,6 +11,8 @@ name = "config_gen"
 path = "main.rs"
 
 [dependencies]
+askama = "0.8"
+structopt = "0.3"
 pem = "0.7.0"
 serde = "1.0.92"
 serde_derive = "1.0.92"
diff --git a/config/config_gen/main.rs b/config/config_gen/main.rs
index 08e4d15..8956766 100644
--- a/config/config_gen/main.rs
+++ b/config/config_gen/main.rs
@@ -1,11 +1,14 @@
+use askama;
+use askama::Template;
 use serde_derive::Deserialize;
 use serde_derive::Serialize;
-use std::env;
 use std::fs;
 use std::fs::File;
 use std::io::Write;
+use std::path;
 use std::path::Path;
 use std::path::PathBuf;
+use structopt::StructOpt;
 
 #[derive(Serialize, Deserialize)]
 struct BuildConfigToml {
@@ -20,77 +23,63 @@ enum ConfigSource {
     Path(PathBuf),
 }
 
-fn display_pem_in_bytes(p: &Path) -> String {
-    let content = &fs::read(p).expect(&format!("Failed to read file: {}", 
p.display()));
-    let pem = pem::parse(content).expect("Cannot parse PEM file");
-    display_raw(&pem.contents)
-}
-
-fn display_raw(content: &[u8]) -> String {
-    let mut output = String::new();
-    output.push_str("&[");
-    for b in content {
-        output.push_str(&format!("{}, ", b));
-    }
-    output.push_str("]");
-
-    output
-}
-
 fn display_config_source(config: &ConfigSource) -> String {
     match config {
         ConfigSource::Path(p) => match 
p.extension().and_then(std::ffi::OsStr::to_str) {
-            Some("pem") => display_pem_in_bytes(p),
+            Some("pem") => {
+                let content = &fs::read(p).expect(&format!("Failed to read 
file: {}", p.display()));
+                let pem = pem::parse(content).expect("Cannot parse PEM file");
+                format!("{:?}", pem.contents)
+            }
             _ => {
                 let content = &fs::read(p).expect(&format!("Failed to read 
file: {}", p.display()));
-                display_raw(&content)
+                format!("{:?}", content)
             }
         },
     }
 }
 
-fn main() {
-    let args: Vec<String> = env::args().collect();
-    if args.len() < 3 {
-        panic!("Please specify the path of build config toml and output 
path.");
-    }
-    let contents = fs::read_to_string(&args[1]).expect("Something went wrong 
reading the file");
+#[derive(Template)]
+#[template(path = "config.j2")]
+struct ConfigTemplate {
+    ias_root_ca_cert: String,
+    auditor_public_keys: Vec<String>,
+    rpc_max_message_size: u32,
+}
+
+fn generate_build_config(toml: &Path, out: &Path) {
+    let contents = fs::read_to_string(toml).expect("Something went wrong 
reading the file");
     let config: BuildConfigToml = toml::from_str(&contents).expect("Failed to 
parse the config.");
 
     let ias_root_ca_cert = display_config_source(&config.ias_root_ca_cert);
 
-    let mut auditor_public_keys = String::new();
-    auditor_public_keys.push_str("&[");
+    let mut auditor_public_keys: Vec<String> = vec![];
     for key in &config.auditor_public_keys {
         let auditor_pulic_key = display_config_source(key);
-        auditor_public_keys.push_str(&format!("{}, ", auditor_pulic_key));
+        auditor_public_keys.push(auditor_pulic_key);
     }
-    auditor_public_keys.push_str("]");
-
-    let mut build_config_generated = String::new();
-    build_config_generated.push_str(&format!(
-        r#"
-    #[derive(Debug)]
-    pub struct BuildConfig<'a> {{
-        pub ias_root_ca_cert: &'a [u8],
-        pub auditor_public_keys: &'a [&'a [u8];{}],
-        pub rpc_max_message_size: u64,
-    }}
-
-    pub static BUILD_CONFIG: BuildConfig<'static> = BuildConfig {{
-        ias_root_ca_cert: {},
-        auditor_public_keys: {},
-        rpc_max_message_size: {},
-    }};"#,
-        config.auditor_public_keys.len(),
+    let config_template = ConfigTemplate {
         ias_root_ca_cert,
         auditor_public_keys,
-        config.rpc_max_message_size
-    ));
+        rpc_max_message_size: config.rpc_max_message_size,
+    };
+    let mut f = File::create(out).expect(&format!("Failed to create file: {}", 
out.display()));
+    f.write_all(&config_template.render().unwrap().as_bytes())
+        .expect(&format!("Failed to write file: {}", out.display()));
+}
+
+#[derive(Debug, StructOpt)]
+struct Cli {
+    #[structopt(short = "t", required = true)]
+    /// Path to the config file in toml.
+    toml_path: path::PathBuf,
 
-    let dest_path = Path::new(&args[2]);
-    let mut f =
-        File::create(&dest_path).expect(&format!("Failed to create file: {}", 
dest_path.display()));
-    f.write_all(build_config_generated.as_bytes())
-        .expect(&format!("Failed to write file: {}", dest_path.display()));
+    #[structopt(short = "o", required = true)]
+    /// Configures the output path where generated Rust file will be written.
+    out_path: path::PathBuf,
+}
+
+fn main() {
+    let args = Cli::from_args();
+    generate_build_config(&args.toml_path, &args.out_path);
 }
diff --git a/config/config_gen/templates/config.j2 
b/config/config_gen/templates/config.j2
new file mode 100644
index 0000000..5a2bd31
--- /dev/null
+++ b/config/config_gen/templates/config.j2
@@ -0,0 +1,16 @@
+#[derive(Debug)]
+pub struct BuildConfig<'a> {
+    pub ias_root_ca_cert: &'a [u8],
+    pub auditor_public_keys: &'a [&'a [u8]; {{ auditor_public_keys.len() }}],
+    pub rpc_max_message_size: u64,
+}
+
+pub static BUILD_CONFIG: BuildConfig<'static> = BuildConfig {
+    ias_root_ca_cert: &{{ ias_root_ca_cert }},
+    auditor_public_keys: &[
+{% for k in auditor_public_keys %}
+    &{{ k }},
+{% endfor %}
+    ],
+    rpc_max_message_size: {{ rpc_max_message_size }},
+};


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to