Эх сурвалжийг харах

Merge pull request #3 from bidhan-a/fix/keypair-check

generate keypair file if it doesn't exist
Dean 利迪恩 4 сар өмнө
parent
commit
38f67af6ee
1 өөрчлөгдсөн 36 нэмэгдсэн , 0 устгасан
  1. 36 0
      src/commands/build.rs

+ 36 - 0
src/commands/build.rs

@@ -1,5 +1,7 @@
 use anyhow::{Error, Result};
 use dirs::home_dir;
+use ed25519_dalek::SigningKey;
+use rand::rngs::OsRng;
 use std::fs;
 use std::fs::create_dir_all;
 use std::io;
@@ -117,6 +119,40 @@ pub fn build() -> Result<()> {
         Ok(())
     }
 
+    // Function to check if keypair file exists.
+    fn has_keypair_file(dir: &Path) -> bool {
+        if dir.exists() && dir.is_dir() {
+            match fs::read_dir(dir) {
+                Ok(entries) => entries.filter_map(Result::ok).any(|entry| {
+                    entry
+                        .path()
+                        .file_name()
+                        .and_then(|name| name.to_str())
+                        .map(|name| name.ends_with("-keypair.json"))
+                        .unwrap_or(false)
+                }),
+                Err(_) => false,
+            }
+        } else {
+            false
+        }
+    }
+
+    // Check if keypair file exists. If not, create one.
+    let deploy_path = Path::new(deploy);
+    if !has_keypair_file(deploy_path) {
+        let project_path = std::env::current_dir()?;
+        let project_name = project_path
+            .file_name()
+            .and_then(|n| n.to_str())
+            .unwrap_or("program");
+        let mut rng = OsRng;
+        fs::write(
+            deploy_path.join(format!("{}-keypair.json", project_name)),
+            serde_json::json!(SigningKey::generate(&mut rng).to_keypair_bytes()[..]).to_string(),
+        )?;
+    }
+
     // Processing directories
     let src_path = Path::new(src);
     for entry in src_path.read_dir()? {