Browse Source

`init` subcommand (#1840)

* `init` subcommand

* clippy
hem1t 1 year ago
parent
commit
c6e1b0f728

+ 40 - 35
packages/cli/src/cli/create.rs

@@ -21,47 +21,52 @@ impl Create {
 
         let path = cargo_generate::generate(args)?;
 
-        // first run cargo fmt
-        let mut cmd = Command::new("cargo");
-        let cmd = cmd.arg("fmt").current_dir(&path);
-        let output = cmd.output().expect("failed to execute process");
-        if !output.status.success() {
-            log::error!("cargo fmt failed");
-            log::error!("stdout: {}", String::from_utf8_lossy(&output.stdout));
-            log::error!("stderr: {}", String::from_utf8_lossy(&output.stderr));
-        }
+        post_create(&path)
+    }
+}
+
+// being also used by `init`
+pub fn post_create(path: &PathBuf) -> Result<()> {
+    // first run cargo fmt
+    let mut cmd = Command::new("cargo");
+    let cmd = cmd.arg("fmt").current_dir(path);
+    let output = cmd.output().expect("failed to execute process");
+    if !output.status.success() {
+        log::error!("cargo fmt failed");
+        log::error!("stdout: {}", String::from_utf8_lossy(&output.stdout));
+        log::error!("stderr: {}", String::from_utf8_lossy(&output.stderr));
+    }
 
-        // then format the toml
-        let toml_paths = [path.join("Cargo.toml"), path.join("Dioxus.toml")];
-        for toml_path in &toml_paths {
-            let toml = std::fs::read_to_string(toml_path)?;
-            let mut toml = toml.parse::<toml_edit::Document>().map_err(|e| {
-                anyhow::anyhow!(
-                    "failed to parse toml at {}: {}",
-                    toml_path.display(),
-                    e.to_string()
-                )
-            })?;
+    // then format the toml
+    let toml_paths = [path.join("Cargo.toml"), path.join("Dioxus.toml")];
+    for toml_path in &toml_paths {
+        let toml = std::fs::read_to_string(toml_path)?;
+        let mut toml = toml.parse::<toml_edit::Document>().map_err(|e| {
+            anyhow::anyhow!(
+                "failed to parse toml at {}: {}",
+                toml_path.display(),
+                e.to_string()
+            )
+        })?;
 
-            toml.as_table_mut().fmt();
+        toml.as_table_mut().fmt();
 
-            let as_string = toml.to_string();
-            let new_string = remove_triple_newlines(&as_string);
-            let mut file = std::fs::File::create(toml_path)?;
-            file.write_all(new_string.as_bytes())?;
-        }
+        let as_string = toml.to_string();
+        let new_string = remove_triple_newlines(&as_string);
+        let mut file = std::fs::File::create(toml_path)?;
+        file.write_all(new_string.as_bytes())?;
+    }
 
-        // remove any triple newlines from the readme
-        let readme_path = path.join("README.md");
-        let readme = std::fs::read_to_string(&readme_path)?;
-        let new_readme = remove_triple_newlines(&readme);
-        let mut file = std::fs::File::create(readme_path)?;
-        file.write_all(new_readme.as_bytes())?;
+    // remove any triple newlines from the readme
+    let readme_path = path.join("README.md");
+    let readme = std::fs::read_to_string(&readme_path)?;
+    let new_readme = remove_triple_newlines(&readme);
+    let mut file = std::fs::File::create(readme_path)?;
+    file.write_all(new_readme.as_bytes())?;
 
-        log::info!("Generated project at {}", path.display());
+    log::info!("Generated project at {}", path.display());
 
-        Ok(())
-    }
+    Ok(())
 }
 
 fn remove_triple_newlines(string: &str) -> String {

+ 33 - 0
packages/cli/src/cli/init.rs

@@ -0,0 +1,33 @@
+use super::*;
+use cargo_generate::{GenerateArgs, TemplatePath};
+
+#[derive(Clone, Debug, Default, Deserialize, Parser)]
+#[clap(name = "init")]
+pub struct Init {
+    /// Template path
+    #[clap(default_value = "gh:dioxuslabs/dioxus-template", long)]
+    template: String,
+}
+
+impl Init {
+    pub fn init(self) -> Result<()> {
+        // get dir name
+        let name = std::env::current_dir()?
+            .file_name()
+            .map(|f| f.to_str().unwrap().to_string());
+
+        let args = GenerateArgs {
+            template_path: TemplatePath {
+                auto_path: Some(self.template),
+                ..Default::default()
+            },
+            name,
+            init: true,
+            ..Default::default()
+        };
+
+        let path = cargo_generate::generate(args)?;
+
+        create::post_create(&path)
+    }
+}

+ 6 - 1
packages/cli/src/cli/mod.rs

@@ -6,6 +6,7 @@ pub mod check;
 pub mod clean;
 pub mod config;
 pub mod create;
+pub mod init;
 pub mod plugin;
 pub mod serve;
 pub mod translate;
@@ -56,9 +57,12 @@ pub enum Commands {
     /// Build, watch & serve the Rust WASM app and all of its assets.
     Serve(serve::Serve),
 
-    /// Init a new project for Dioxus.
+    /// Create a new project for Dioxus.
     Create(create::Create),
 
+    /// Init a new project for Dioxus
+    Init(init::Init),
+
     /// Clean output artifacts.
     Clean(clean::Clean),
 
@@ -94,6 +98,7 @@ impl Display for Commands {
             Commands::Translate(_) => write!(f, "translate"),
             Commands::Serve(_) => write!(f, "serve"),
             Commands::Create(_) => write!(f, "create"),
+            Commands::Init(_) => write!(f, "init"),
             Commands::Clean(_) => write!(f, "clean"),
             Commands::Config(_) => write!(f, "config"),
             Commands::Version(_) => write!(f, "version"),

+ 4 - 0
packages/cli/src/main.rs

@@ -52,6 +52,10 @@ async fn main() -> anyhow::Result<()> {
             .create()
             .map_err(|e| anyhow!("🚫 Creating new project failed: {}", e)),
 
+        Init(opts) => opts
+            .init()
+            .map_err(|e| anyhow!("🚫 Initialising a new project failed: {}", e)),
+
         Config(opts) => opts
             .config()
             .map_err(|e| anyhow!("🚫 Configuring new project failed: {}", e)),