Browse Source

fix: `dist` setting

mrxiaozhuox 3 years ago
parent
commit
5395e7693c
9 changed files with 61 additions and 26 deletions
  1. 5 4
      src/builder.rs
  2. 6 1
      src/cli/build/mod.rs
  3. 29 9
      src/cli/init/mod.rs
  4. 1 2
      src/cli/mod.rs
  5. 7 4
      src/cli/serve/mod.rs
  6. 1 1
      src/lib.rs
  7. 10 3
      src/server/mod.rs
  8. 1 1
      src/template/config.toml
  9. 1 1
      src/template/default.rs

+ 5 - 4
src/builder.rs

@@ -2,10 +2,10 @@ use crate::{
     config::{CrateConfig, ExecutableType},
     error::{Error, Result},
 };
-use std::{io::Write, process::Command};
+use std::{io::Write, path::PathBuf, process::Command};
 use wasm_bindgen_cli_support::Bindgen;
 
-pub fn build(config: &CrateConfig) -> Result<()> {
+pub fn build(config: &CrateConfig, dist: PathBuf) -> Result<()> {
     /*
     [1] Build the project with cargo, generating a wasm32-unknown-unknown target (is there a more specific, better target to leverage?)
     [2] Generate the appropriate build folders
@@ -15,7 +15,6 @@ pub fn build(config: &CrateConfig) -> Result<()> {
     */
 
     let CrateConfig {
-        out_dir,
         crate_dir,
         target_dir,
         static_dir,
@@ -23,10 +22,12 @@ pub fn build(config: &CrateConfig) -> Result<()> {
         ..
     } = config;
 
+    let out_dir = crate_dir.join(dist);
+
     let t_start = std::time::Instant::now();
 
     // [1] Build the .wasm module
-    log::info!("🚅 Running build commands...");
+    log::info!("🚅 Running build command...");
     let mut cmd = Command::new("cargo");
     cmd.current_dir(&crate_dir)
         .arg("build")

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

@@ -1,3 +1,5 @@
+use std::path::PathBuf;
+
 use crate::cfg::ConfigOptsBuild;
 use structopt::StructOpt;
 
@@ -16,7 +18,10 @@ impl Build {
         // change the relase state.
         crate_config.with_release(self.build.release);
 
-        crate::builder::build(&crate_config)?;
+        crate::builder::build(
+            &crate_config,
+            self.build.dist.unwrap_or(PathBuf::from("dist")),
+        )?;
 
         Ok(())
     }

+ 29 - 9
src/cli/init/mod.rs

@@ -1,14 +1,18 @@
-use std::{process::{Command, Stdio}, fs::File, path::PathBuf, io::Write};
+use std::{
+    fs::{File, OpenOptions},
+    io::Write,
+    path::PathBuf,
+    process::{Command, Stdio},
+};
 
 use structopt::StructOpt;
 
-use crate::{error::{Error, Result}, cargo};
+use crate::error::{Error, Result};
 
 /// Build the Rust WASM app and all of its assets.
 #[derive(Clone, Debug, StructOpt)]
 #[structopt(name = "init")]
 pub struct Init {
-
     /// Init project path
     #[structopt(default_value = ".")]
     path: String,
@@ -16,24 +20,26 @@ pub struct Init {
     /// Template path
     #[structopt(default_value = "default", long)]
     template: String,
-
 }
 
 impl Init {
     pub fn init(self) -> Result<()> {
-        
         log::info!("🔧 Start to init a new project '{}'.", self.path);
 
         let project_path = PathBuf::from(&self.path);
 
+        if project_path.join("Cargo.toml").is_file() {
+            log::warn!("Path '{}' is initialized.", self.path);
+            return Ok(());
+        }
+
         let output = Command::new("cargo")
             .arg("init")
             .arg(&self.path)
             .arg("--bin")
             .stdout(Stdio::piped())
             .stderr(Stdio::piped())
-            .output()?
-        ;
+            .output()?;
 
         if !output.status.success() {
             return Err(Error::CargoError("Cargo init failed".into()));
@@ -54,8 +60,22 @@ impl Init {
 
         // log::info!("🎯 Project initialization completed.");
 
-        
+        if !Command::new("cargo")
+            .args(["add", "dioxus", "--features web"])
+            .output()?
+            .status
+            .success()
+        {
+            let mut file = OpenOptions::new()
+                .append(true)
+                .open(project_path.join("Cargo.toml"))?;
+            file.write_all("dioxus = { version = \"0.1.7\", features = [\"web\"] }".as_bytes())?;
+        }
+
+        log::info!("\n💡 Project initialized:");
+        log::info!("🎯> cd {}", self.path);
+        log::info!("🎯> dioxus serve");
 
         Ok(())
     }
-}
+}

+ 1 - 2
src/cli/mod.rs

@@ -3,9 +3,9 @@ use structopt::StructOpt;
 pub mod build;
 pub mod cfg;
 pub mod clean;
+pub mod init;
 pub mod serve;
 pub mod translate;
-pub mod init;
 
 /// Build, bundle, & ship your Dioxus app.
 ///
@@ -36,7 +36,6 @@ pub enum Commands {
     Serve(serve::Serve),
     /// Init a new project for Dioxus.
     Init(init::Init),
-
     // /// Clean output artifacts.
     // Clean(clean::Clean),
 

+ 7 - 4
src/cli/serve/mod.rs

@@ -1,5 +1,5 @@
 use crate::{cfg::ConfigOptsServe, server};
-use std::io::Write;
+use std::{io::Write, path::PathBuf};
 use structopt::StructOpt;
 
 /// Run the WASM project on dev-server
@@ -16,15 +16,18 @@ impl Serve {
         // change the relase state.
         crate_config.with_release(self.serve.release);
 
-        crate::builder::build(&crate_config).expect("build failed");
+        let dist_path = self.serve.dist.clone().unwrap_or(PathBuf::from("dist"));
+
+        crate::builder::build(&crate_config, dist_path.clone()).expect("build failed");
 
         let serve_html = String::from(include_str!("../../server/serve.html"));
 
-        let mut file = std::fs::File::create(crate_config.out_dir.join("index.html"))?;
+        let mut file =
+            std::fs::File::create(crate_config.crate_dir.join(dist_path).join("index.html"))?;
         file.write_all(serve_html.as_bytes())?;
 
         // start the develop server
-        server::startup(crate_config.clone()).await?;
+        server::startup(crate_config.clone(), &self.serve).await?;
 
         Ok(())
     }

+ 1 - 1
src/lib.rs

@@ -15,4 +15,4 @@ pub mod error;
 pub use error::*;
 
 pub mod logging;
-pub use logging::*;
+pub use logging::*;

+ 10 - 3
src/server/mod.rs

@@ -6,8 +6,11 @@ use axum::{
     AddExtensionLayer, Router,
 };
 use notify::{watcher, DebouncedEvent, Watcher};
-use std::sync::{mpsc::channel, Arc, Mutex};
 use std::time::Duration;
+use std::{
+    path::PathBuf,
+    sync::{mpsc::channel, Arc, Mutex},
+};
 use tower_http::services::ServeDir;
 
 use crate::{builder, CrateConfig};
@@ -22,7 +25,10 @@ impl WsRelodState {
     }
 }
 
-pub async fn startup(config: CrateConfig) -> anyhow::Result<()> {
+pub async fn startup(
+    config: CrateConfig,
+    opts: &crate::cfg::ConfigOptsServe,
+) -> anyhow::Result<()> {
     log::info!("🚀 Starting development server...");
 
     let (tx, rx) = channel();
@@ -40,6 +46,7 @@ pub async fn startup(config: CrateConfig) -> anyhow::Result<()> {
 
     let watcher_conf = config.clone();
     let watcher_ws_state = ws_reload_state.clone();
+    let dist_path = opts.dist.clone().unwrap_or(PathBuf::from("dist"));
     tokio::spawn(async move {
         loop {
             if let Ok(v) = rx.recv() {
@@ -48,7 +55,7 @@ pub async fn startup(config: CrateConfig) -> anyhow::Result<()> {
                     | DebouncedEvent::Write(_)
                     | DebouncedEvent::Remove(_)
                     | DebouncedEvent::Rename(_, _) => {
-                        if let Ok(_) = builder::build(&watcher_conf) {
+                        if let Ok(_) = builder::build(&watcher_conf, dist_path.clone()) {
                             // change the websocket reload state to true;
                             // the page will auto-reload.
                             watcher_ws_state.lock().unwrap().change();

+ 1 - 1
src/template/config.toml

@@ -6,4 +6,4 @@ edition = "2021"
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
 [dependencies]
-dioxus = { version = "0.1.7", features = ["web"] }
+dioxus = { version = "0.1.7", features = ["web"] }

+ 1 - 1
src/template/default.rs

@@ -1,7 +1,7 @@
 use dioxus::prelude::*;
 
 fn main() {
-    dioxus::desktop::launch(app);
+    dioxus::web::launch(app);
 }
 
 fn app(cx: Scope) -> Element {