Browse Source

cli: Add package.json in anchor init (#623)

Julian McCarthy 4 years ago
parent
commit
5532aca6ec
2 changed files with 57 additions and 0 deletions
  1. 22 0
      cli/src/lib.rs
  2. 35 0
      cli/src/template.rs

+ 22 - 0
cli/src/lib.rs

@@ -344,12 +344,18 @@ fn init(cfg_override: &ConfigOverride, name: String, typescript: bool) -> Result
         let mut ts_config = File::create("tsconfig.json")?;
         ts_config.write_all(template::ts_config().as_bytes())?;
 
+        let mut ts_package_json = File::create("package.json")?;
+        ts_package_json.write_all(template::ts_package_json().as_bytes())?;
+
         let mut deploy = File::create("migrations/deploy.ts")?;
         deploy.write_all(template::ts_deploy_script().as_bytes())?;
 
         let mut mocha = File::create(&format!("tests/{}.ts", name))?;
         mocha.write_all(template::ts_mocha(&name).as_bytes())?;
     } else {
+        let mut package_json = File::create("package.json")?;
+        package_json.write_all(template::package_json().as_bytes())?;
+
         let mut mocha = File::create(&format!("tests/{}.js", name))?;
         mocha.write_all(template::mocha(&name).as_bytes())?;
 
@@ -357,6 +363,22 @@ fn init(cfg_override: &ConfigOverride, name: String, typescript: bool) -> Result
         deploy.write_all(template::deploy_script().as_bytes())?;
     }
 
+    // Install node modules.
+    let yarn_result = std::process::Command::new("yarn")
+        .stdout(Stdio::inherit())
+        .stderr(Stdio::inherit())
+        .output()
+        .map_err(|e| anyhow::format_err!("yarn install failed: {}", e.to_string()))?;
+    if !yarn_result.status.success() {
+        println!("Failed yarn install will attempt to npm install");
+        std::process::Command::new("npm")
+            .stdout(Stdio::inherit())
+            .stderr(Stdio::inherit())
+            .output()
+            .map_err(|e| anyhow::format_err!("npm install failed: {}", e.to_string()))?;
+        println!("Failed to install node dependencies")
+    }
+
     println!("{} initialized", name);
 
     Ok(())

+ 35 - 0
cli/src/template.rs

@@ -184,6 +184,41 @@ describe('{}', () => {{
     )
 }
 
+pub fn package_json() -> String {
+    format!(
+        r#"{{
+    "dependencies": {{
+        "@project-serum/anchor": "^{0}"
+    }},
+    "devDependencies": {{
+        "chai": "^4.3.4",
+        "mocha": "^9.0.3"
+    }}
+}}      
+"#,
+        VERSION
+    )
+}
+
+pub fn ts_package_json() -> String {
+    format!(
+        r#"{{
+    "dependencies": {{
+        "@project-serum/anchor": "^{0}"
+    }},
+    "devDependencies": {{
+        "chai": "^4.3.4",
+        "mocha": "^9.0.3",
+        "ts-mocha": "^8.0.0",
+        "@types/mocha": "^9.0.0",
+        "typescript": "^4.3.5"
+    }}
+}}     
+"#,
+        VERSION
+    )
+}
+
 pub fn ts_mocha(name: &str) -> String {
     format!(
         r#"import * as anchor from '@project-serum/anchor';