From 91a8ce31690d54b8df896254e58206da2816b0cd Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Thu, 10 Mar 2022 11:29:27 +0800 Subject: [PATCH 01/15] feat: config init `platform` arg --- src/assets/autoreload.js | 4 +++- src/assets/dioxus.toml | 2 +- src/cli/config/mod.rs | 13 +++++++++++-- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/assets/autoreload.js b/src/assets/autoreload.js index da62e5eae..fffb3e26c 100644 --- a/src/assets/autoreload.js +++ b/src/assets/autoreload.js @@ -1,3 +1,6 @@ +// Dioxus-CLI +// https://github.com/DioxusLabs/cli + (function () { var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; var url = protocol + '//' + window.location.host + '/_dioxus/ws'; @@ -15,7 +18,6 @@ var ws = new WebSocket(url); ws.onmessage = (ev) => { if (ev.data == "reload") { - // alert("reload!!!"); window.location.reload(); } }; diff --git a/src/assets/dioxus.toml b/src/assets/dioxus.toml index d3f160242..af9cc886b 100644 --- a/src/assets/dioxus.toml +++ b/src/assets/dioxus.toml @@ -6,7 +6,7 @@ name = "{{project-name}}" # default platfrom # you can also use `dioxus serve/build --platform XXX` to use other platform # value: web | desktop -default_platform = "web" +default_platform = "{{default-platform}}" # Web `build` & `serve` dist path out_dir = "dist" diff --git a/src/cli/config/mod.rs b/src/cli/config/mod.rs index 6d672b7a5..2a1f28fda 100644 --- a/src/cli/config/mod.rs +++ b/src/cli/config/mod.rs @@ -13,6 +13,10 @@ pub enum Config { #[clap(long)] #[serde(default)] force: bool, + + /// Project default platform + #[clap(long, default_value = "web")] + platform: String, }, } @@ -20,7 +24,11 @@ impl Config { pub fn config(self) -> Result<()> { let crate_root = crate::cargo::crate_root()?; match self { - Config::Init { name, force } => { + Config::Init { + name, + force, + platform, + } => { let conf_path = crate_root.join("Dioxus.toml"); if conf_path.is_file() && !force { log::warn!( @@ -30,7 +38,8 @@ impl Config { } let mut file = File::create(conf_path)?; let content = String::from(include_str!("../../assets/dioxus.toml")) - .replace("{{project-name}}", &name); + .replace("{{project-name}}", &name) + .replace("{{default-platform}}", &platform); file.write_all(content.as_bytes())?; log::info!("🚩 Init config file completed."); } From 5fb1b3e20bb5f8282c735bcf7160dfdbcaf695d9 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Sat, 12 Mar 2022 13:00:07 +0800 Subject: [PATCH 02/15] feat: commit code --- Cargo.toml | 7 ++++- src/assets/dioxus.toml | 4 ++- src/cli/mod.rs | 1 + src/cli/tools.rs | 69 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 src/cli/tools.rs diff --git a/Cargo.toml b/Cargo.toml index 3ae7b4610..6a7a2c9d0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,10 +9,12 @@ license = "MIT/Apache-2.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] + # cli core clap = {version = "3.0.14", features = ["derive"]} thiserror = "1.0.30" wasm-bindgen-cli-support = "0.2.79" + # features log = "0.4.14" fern = { version = "0.6.0", features = ["colored"] } @@ -37,7 +39,10 @@ hyper = "0.14.17" axum = { version = "0.4.5", features = ["ws", "headers"] } tower-http = { version = "0.2.2", features = ["fs", "trace"] } headers = "0.3.7" -# hyper = { version = "0.14.11", features = ["full"] } + +# tools download +dirs = "4.0.0" +reqwest = { version = "0.11", features = ["json"] } [[bin]] path = "src/main.rs" diff --git a/src/assets/dioxus.toml b/src/assets/dioxus.toml index af9cc886b..b897a39a7 100644 --- a/src/assets/dioxus.toml +++ b/src/assets/dioxus.toml @@ -36,4 +36,6 @@ script = [] # Javascript code file # serve: [dev-server] only -script = [] \ No newline at end of file +script = [] + +[web.tools] diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 1b5ba0be7..9f31c60ae 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -5,6 +5,7 @@ pub mod config; pub mod create; pub mod serve; pub mod translate; +pub mod tools; use crate::{ cfg::{ConfigOptsBuild, ConfigOptsServe}, diff --git a/src/cli/tools.rs b/src/cli/tools.rs new file mode 100644 index 000000000..aa320275e --- /dev/null +++ b/src/cli/tools.rs @@ -0,0 +1,69 @@ +use std::path::PathBuf; + +pub enum Tool { + WasmOpt, +} + +pub fn app_path() { + let data_local = dirs::data_local_dir().unwrap(); + +} + +impl Tool { + pub fn name(&self) -> &str { + match self { + Self::WasmOpt => "wasm-opt", + } + } + + pub fn bin_path(&self) -> &str { + if cfg!(target_os = "windows") { + match self { + Self::WasmOpt => "bin/wasm-opt.exe", + } + } else { + match self { + Self::WasmOpt => "bin/wasm-opt", + } + } + } + + pub fn target_platform(&self) -> &str { + match self { + Self::WasmOpt => { + if cfg!(target_os = "windows") { + "windows" + } else if cfg!(target_os = "macos") { + "macos" + } else if cfg!(target_os = "linux") { + "linux" + } else { + panic!("unsupported platformm"); + } + } + } + } + + pub fn download_url(&self) -> String { + match self { + Self::WasmOpt => { + format!( + "https://github.com/WebAssembly/binaryen/releases/download/version_105/binaryen-version_105-x86_64-{target}.tar.gz", + target = self.target_platform() + ) + } + } + } + + pub async fn download_package(&self) { + + let download_dir = dirs::download_dir().unwrap(); + let download_url = self.download_url(); + + let resp = reqwest::get(download_url).await.unwrap(); + + resp. + + } + +} From 25ff6c5937b8907a734d05b6936f5f20e8113b5b Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Sat, 12 Mar 2022 23:48:05 +0800 Subject: [PATCH 03/15] feat: commit code --- Cargo.toml | 2 +- src/cli/tools.rs | 41 +++++++++++++++++++++++++++++++++-------- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6a7a2c9d0..0b96d72a2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,7 +42,7 @@ headers = "0.3.7" # tools download dirs = "4.0.0" -reqwest = { version = "0.11", features = ["json"] } +reqwest = { version = "0.11", features = ["rustls-tls", "stream", "trust-dns"] } [[bin]] path = "src/main.rs" diff --git a/src/cli/tools.rs b/src/cli/tools.rs index aa320275e..a042e7565 100644 --- a/src/cli/tools.rs +++ b/src/cli/tools.rs @@ -1,12 +1,29 @@ -use std::path::PathBuf; +use std::{fs::create_dir_all, path::PathBuf}; + +use anyhow::Context; +use futures::StreamExt; +use tokio::io::AsyncWriteExt; pub enum Tool { WasmOpt, } -pub fn app_path() { +pub fn app_path() -> PathBuf { let data_local = dirs::data_local_dir().unwrap(); - + let dioxus_dir = data_local.join("dioxus"); + if !dioxus_dir.is_dir() { + create_dir_all(&dioxus_dir).unwrap(); + } + dioxus_dir +} + +pub fn temp_path() -> PathBuf { + let app_path = app_path(); + let temp_path = app_path.join("temp"); + if !temp_path.is_dir() { + create_dir_all(&temp_path).unwrap(); + } + temp_path } impl Tool { @@ -55,15 +72,23 @@ impl Tool { } } - pub async fn download_package(&self) { - - let download_dir = dirs::download_dir().unwrap(); + pub async fn download_package(&self) -> anyhow::Result { + let temp_dir = temp_path(); let download_url = self.download_url(); + let temp_out = temp_dir.join(format!("{}-tool.tmp", self.name())); + let mut file = tokio::fs::File::create(&temp_out) + .await + .context("failed creating temporary output file")?; + let resp = reqwest::get(download_url).await.unwrap(); - resp. + let mut res_bytes = resp.bytes_stream(); + while let Some(chunk_res) = res_bytes.next().await { + let chunk = chunk_res.context("error reading chunk from download")?; + let _ = file.write(chunk.as_ref()).await; + } + Ok(temp_out) } - } From eea01f7f8c94c00d6c8ae4cbe6bde29e184552a6 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Sun, 13 Mar 2022 13:19:54 +0800 Subject: [PATCH 04/15] feat: commit code --- Cargo.toml | 2 ++ src/cli/mod.rs | 4 ++++ src/cli/tool/mod.rs | 40 ++++++++++++++++++++++++++++++++++++++++ src/cli/tools.rs | 45 +++++++++++++++++++++++++++++++++++++++++---- src/main.rs | 6 ++++++ 5 files changed, 93 insertions(+), 4 deletions(-) create mode 100644 src/cli/tool/mod.rs diff --git a/Cargo.toml b/Cargo.toml index 0b96d72a2..8beca8f7d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,8 @@ headers = "0.3.7" # tools download dirs = "4.0.0" reqwest = { version = "0.11", features = ["rustls-tls", "stream", "trust-dns"] } +flate2 = "1.0.22" +tar = "0.4.38" [[bin]] path = "src/main.rs" diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 9f31c60ae..6e653507d 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -6,6 +6,7 @@ pub mod create; pub mod serve; pub mod translate; pub mod tools; +pub mod tool; use crate::{ cfg::{ConfigOptsBuild, ConfigOptsServe}, @@ -56,4 +57,7 @@ pub enum Commands { /// Dioxus config file controls. #[clap(subcommand)] Config(config::Config), + /// Install & Manage tools for Dioxus-cli. + #[clap(subcommand)] + Tool(tool::Tool), } diff --git a/src/cli/tool/mod.rs b/src/cli/tool/mod.rs new file mode 100644 index 000000000..3f3a86bfc --- /dev/null +++ b/src/cli/tool/mod.rs @@ -0,0 +1,40 @@ +use super::*; + +/// Build the Rust WASM app and all of its assets. +#[derive(Clone, Debug, Deserialize, Subcommand)] +#[clap(name = "tool")] +pub enum Tool { + /// Return all dioxus-cli support tools. + List {}, + Add { + name: String + } +} + +impl Tool { + pub async fn tool(self) -> Result<()> { + match self { + Tool::List {} => { + for item in tools::tool_list() { + if tools::Tool::from_str(item).unwrap().is_installed() { + println!("{item} [installed]"); + } else { + println!("{item}"); + } + } + } + Tool::Add { name } => { + let tool_list = tools::tool_list(); + + if !tool_list.contains(&name.as_str()) { + log::error!("Tool {name} not found."); + return Ok(()); + } + let target_tool = tools::Tool::from_str(&name).unwrap(); + println!("{:?}", target_tool.download_package().await); + } + } + + Ok(()) + } +} diff --git a/src/cli/tools.rs b/src/cli/tools.rs index a042e7565..1eb68e773 100644 --- a/src/cli/tools.rs +++ b/src/cli/tools.rs @@ -8,6 +8,10 @@ pub enum Tool { WasmOpt, } +pub fn tool_list() -> Vec<&'static str> { + vec!["wasm-opt"] +} + pub fn app_path() -> PathBuf { let data_local = dirs::data_local_dir().unwrap(); let dioxus_dir = data_local.join("dioxus"); @@ -26,7 +30,24 @@ pub fn temp_path() -> PathBuf { temp_path } +pub fn tools_path(tool: &Tool) -> PathBuf { + let app_path = app_path(); + let temp_path = app_path.join("tools"); + if !temp_path.is_dir() { + create_dir_all(&temp_path).unwrap(); + } + temp_path.join(tool.name()) +} + +#[allow(clippy::should_implement_trait)] impl Tool { + pub fn from_str(name: &str) -> Option { + match name { + "wasm-opt" => Some(Self::WasmOpt), + _ => None, + } + } + pub fn name(&self) -> &str { match self { Self::WasmOpt => "wasm-opt", @@ -72,11 +93,23 @@ impl Tool { } } - pub async fn download_package(&self) -> anyhow::Result { - let temp_dir = temp_path(); - let download_url = self.download_url(); + pub fn extension(&self) -> &str { + match self { + Self::WasmOpt => "tar.gz", + } + } - let temp_out = temp_dir.join(format!("{}-tool.tmp", self.name())); + pub fn is_installed(&self) -> bool { + tools_path(self).is_dir() + } + + pub fn temp_out_path(&self) -> PathBuf { + temp_path().join(format!("{}-tool.tmp", self.name())) + } + + pub async fn download_package(&self) -> anyhow::Result { + let download_url = self.download_url(); + let temp_out = self.temp_out_path(); let mut file = tokio::fs::File::create(&temp_out) .await .context("failed creating temporary output file")?; @@ -91,4 +124,8 @@ impl Tool { Ok(temp_out) } + + pub async fn install_package() -> anyhow::Result<()> { + Ok(()) + } } diff --git a/src/main.rs b/src/main.rs index 97d4a3bb4..099ff74c0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -42,6 +42,12 @@ async fn main() -> Result<()> { log::error!("config error: {}", e); } } + + Commands::Tool(opts) => { + if let Err(e) = opts.tool().await { + log::error!("tool error: {}", e); + } + } } Ok(()) From 140d7ad7ed1b724b19806ea8999bde84b904646d Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Mon, 14 Mar 2022 19:11:12 +0800 Subject: [PATCH 05/15] feat: commit code --- Dioxus.toml | 45 +++++++++++++++++++++++++++++++ src/assets/dioxus.toml | 6 ++++- src/cli/config/mod.rs | 5 ++++ src/cli/tool/mod.rs | 26 +++++++++++++++++- src/cli/tools.rs | 61 ++++++++++++++++++++++++++++-------------- src/config.rs | 4 ++- 6 files changed, 124 insertions(+), 23 deletions(-) create mode 100644 Dioxus.toml diff --git a/Dioxus.toml b/Dioxus.toml new file mode 100644 index 000000000..ab85abe86 --- /dev/null +++ b/Dioxus.toml @@ -0,0 +1,45 @@ +[application] + +# dioxus project name +name = "{{project-name}}" + +# default platfrom +# you can also use `dioxus serve/build --platform XXX` to use other platform +# value: web | desktop +default_platform = "{{default-platform}}" + +# Web `build` & `serve` dist path +out_dir = "dist" + +# resource (static) file folder +asset_dir = "public" + +[web.app] + +# HTML title tag content +title = "dioxus | ⛺" + +[web.watcher] + +watch_path = ["src"] + +# include `assets` in web platform +[web.resource] + +# CSS style file +style = [] + +# Javascript code file +script = [] + +[web.resource.dev] + +# Javascript code file +# serve: [dev-server] only +script = [] + +[application.tools] + +# use binaryen.wasm-opt for output Wasm file +# binaryen just will trigger in `web` platform +binaryen = { wasm_opt = [".PROJECT_OUT"] } \ No newline at end of file diff --git a/src/assets/dioxus.toml b/src/assets/dioxus.toml index b897a39a7..ab85abe86 100644 --- a/src/assets/dioxus.toml +++ b/src/assets/dioxus.toml @@ -38,4 +38,8 @@ script = [] # serve: [dev-server] only script = [] -[web.tools] +[application.tools] + +# use binaryen.wasm-opt for output Wasm file +# binaryen just will trigger in `web` platform +binaryen = { wasm_opt = [".PROJECT_OUT"] } \ No newline at end of file diff --git a/src/cli/config/mod.rs b/src/cli/config/mod.rs index 2a1f28fda..6422ede27 100644 --- a/src/cli/config/mod.rs +++ b/src/cli/config/mod.rs @@ -18,6 +18,8 @@ pub enum Config { #[clap(long, default_value = "web")] platform: String, }, + /// Format Print Dioxus-Config. + FormatPrint {} } impl Config { @@ -43,6 +45,9 @@ impl Config { file.write_all(content.as_bytes())?; log::info!("🚩 Init config file completed."); } + Config::FormatPrint {} => { + println!("{:#?}", crate::CrateConfig::new()?.dioxus_config); + } } Ok(()) } diff --git a/src/cli/tool/mod.rs b/src/cli/tool/mod.rs index 3f3a86bfc..1b8768497 100644 --- a/src/cli/tool/mod.rs +++ b/src/cli/tool/mod.rs @@ -6,6 +6,9 @@ use super::*; pub enum Tool { /// Return all dioxus-cli support tools. List {}, + /// Get default app install path. + AppPath {}, + /// Install a new tool. Add { name: String } @@ -23,6 +26,9 @@ impl Tool { } } } + Tool::AppPath {} => { + println!("{}", tools::tools_path().to_str().unwrap()); + } Tool::Add { name } => { let tool_list = tools::tool_list(); @@ -31,7 +37,25 @@ impl Tool { return Ok(()); } let target_tool = tools::Tool::from_str(&name).unwrap(); - println!("{:?}", target_tool.download_package().await); + + if target_tool.is_installed() { + log::warn!("Tool {name} is installed."); + return Ok(()); + } + + log::info!("Start to download tool package..."); + if let Err(e) = target_tool.download_package().await { + log::error!("Tool download failed: {e}"); + return Ok(()); + } + + log::info!("Start to install tool package..."); + if let Err(e) = target_tool.install_package().await { + log::error!("Tool install failed: {e}"); + return Ok(()); + } + + log::info!("Tool {name} install successfully!"); } } diff --git a/src/cli/tools.rs b/src/cli/tools.rs index 1eb68e773..257c7f856 100644 --- a/src/cli/tools.rs +++ b/src/cli/tools.rs @@ -1,15 +1,21 @@ -use std::{fs::create_dir_all, path::PathBuf}; +use std::{ + fs::{create_dir_all, File}, + path::PathBuf, +}; use anyhow::Context; +use flate2::read::GzDecoder; use futures::StreamExt; +use tar::Archive; use tokio::io::AsyncWriteExt; +#[derive(Debug, PartialEq, Eq)] pub enum Tool { - WasmOpt, + Binaryen, } pub fn tool_list() -> Vec<&'static str> { - vec!["wasm-opt"] + vec!["binaryen"] } pub fn app_path() -> PathBuf { @@ -30,45 +36,39 @@ pub fn temp_path() -> PathBuf { temp_path } -pub fn tools_path(tool: &Tool) -> PathBuf { +pub fn tools_path() -> PathBuf { let app_path = app_path(); let temp_path = app_path.join("tools"); if !temp_path.is_dir() { create_dir_all(&temp_path).unwrap(); } - temp_path.join(tool.name()) + temp_path } #[allow(clippy::should_implement_trait)] impl Tool { pub fn from_str(name: &str) -> Option { match name { - "wasm-opt" => Some(Self::WasmOpt), + "binaryen" => Some(Self::Binaryen), _ => None, } } pub fn name(&self) -> &str { match self { - Self::WasmOpt => "wasm-opt", + Self::Binaryen => "binaryen", } } pub fn bin_path(&self) -> &str { - if cfg!(target_os = "windows") { - match self { - Self::WasmOpt => "bin/wasm-opt.exe", - } - } else { - match self { - Self::WasmOpt => "bin/wasm-opt", - } + match self { + Self::Binaryen => "bin", } } pub fn target_platform(&self) -> &str { match self { - Self::WasmOpt => { + Self::Binaryen => { if cfg!(target_os = "windows") { "windows" } else if cfg!(target_os = "macos") { @@ -84,7 +84,7 @@ impl Tool { pub fn download_url(&self) -> String { match self { - Self::WasmOpt => { + Self::Binaryen => { format!( "https://github.com/WebAssembly/binaryen/releases/download/version_105/binaryen-version_105-x86_64-{target}.tar.gz", target = self.target_platform() @@ -95,12 +95,12 @@ impl Tool { pub fn extension(&self) -> &str { match self { - Self::WasmOpt => "tar.gz", + Self::Binaryen => "tar.gz", } } pub fn is_installed(&self) -> bool { - tools_path(self).is_dir() + tools_path().join(self.name()).is_dir() } pub fn temp_out_path(&self) -> PathBuf { @@ -125,7 +125,28 @@ impl Tool { Ok(temp_out) } - pub async fn install_package() -> anyhow::Result<()> { + pub async fn install_package(&self) -> anyhow::Result<()> { + let temp_path = self.temp_out_path(); + let tool_path = tools_path(); + + let dir_name = if self == &Tool::Binaryen { + "binaryen-version_105" + } else { + "" + }; + + if self.extension() == "tar.gz" { + let tar_gz = File::open(temp_path)?; + let tar = GzDecoder::new(tar_gz); + let mut archive = Archive::new(tar); + archive.unpack(&tool_path)?; + // println!("{:?} -> {:?}", tool_path.join(dir_name), tool_path.join(self.name())); + std::fs::rename( + tool_path.join(dir_name), + tool_path.join(self.name()), + )?; + } + Ok(()) } } diff --git a/src/config.rs b/src/config.rs index ba0427191..f7897f5f8 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,6 +1,6 @@ use crate::error::Result; use serde::{Deserialize, Serialize}; -use std::{fs::File, io::Read, path::PathBuf}; +use std::{fs::File, io::Read, path::PathBuf, collections::HashMap}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DioxusConfig { @@ -34,6 +34,7 @@ impl Default for DioxusConfig { default_platform: "web".to_string(), out_dir: Some(PathBuf::from("dist")), asset_dir: Some(PathBuf::from("public")), + tools: None, }, web: WebConfig { app: WebAppConfing { @@ -62,6 +63,7 @@ pub struct ApplicationConfig { pub default_platform: String, pub out_dir: Option, pub asset_dir: Option, + pub tools: Option> } #[derive(Debug, Clone, Serialize, Deserialize)] From 2e83822d415e8d29503defb56eec5cccb0231ed3 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Mon, 14 Mar 2022 22:39:15 +0800 Subject: [PATCH 06/15] feat: commit code --- Dioxus.toml | 4 ++-- src/cli/mod.rs | 1 - src/cli/tool/mod.rs | 2 ++ src/lib.rs | 2 ++ src/{cli => }/tools.rs | 11 +++++++++++ 5 files changed, 17 insertions(+), 3 deletions(-) rename src/{cli => }/tools.rs (92%) diff --git a/Dioxus.toml b/Dioxus.toml index ab85abe86..2db611914 100644 --- a/Dioxus.toml +++ b/Dioxus.toml @@ -1,12 +1,12 @@ [application] # dioxus project name -name = "{{project-name}}" +name = "dioxus-cli" # default platfrom # you can also use `dioxus serve/build --platform XXX` to use other platform # value: web | desktop -default_platform = "{{default-platform}}" +default_platform = "desktop" # Web `build` & `serve` dist path out_dir = "dist" diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 6e653507d..2c91c94dd 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -5,7 +5,6 @@ pub mod config; pub mod create; pub mod serve; pub mod translate; -pub mod tools; pub mod tool; use crate::{ diff --git a/src/cli/tool/mod.rs b/src/cli/tool/mod.rs index 1b8768497..51e41e384 100644 --- a/src/cli/tool/mod.rs +++ b/src/cli/tool/mod.rs @@ -1,3 +1,5 @@ +use crate::tools; + use super::*; /// Build the Rust WASM app and all of its assets. diff --git a/src/lib.rs b/src/lib.rs index 395cbc8dc..8cd4b1f2d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,7 @@ pub mod builder; pub mod server; +pub mod tools; + pub use builder::*; pub mod cargo; diff --git a/src/cli/tools.rs b/src/tools.rs similarity index 92% rename from src/cli/tools.rs rename to src/tools.rs index 257c7f856..b5c9d658a 100644 --- a/src/cli/tools.rs +++ b/src/tools.rs @@ -47,6 +47,8 @@ pub fn tools_path() -> PathBuf { #[allow(clippy::should_implement_trait)] impl Tool { + + /// from str to tool enum pub fn from_str(name: &str) -> Option { match name { "binaryen" => Some(Self::Binaryen), @@ -54,18 +56,21 @@ impl Tool { } } + /// get current tool name str pub fn name(&self) -> &str { match self { Self::Binaryen => "binaryen", } } + /// get tool bin dir path pub fn bin_path(&self) -> &str { match self { Self::Binaryen => "bin", } } + /// get target platform pub fn target_platform(&self) -> &str { match self { Self::Binaryen => { @@ -82,6 +87,7 @@ impl Tool { } } + /// get tool package download url pub fn download_url(&self) -> String { match self { Self::Binaryen => { @@ -93,20 +99,24 @@ impl Tool { } } + /// get package extension name pub fn extension(&self) -> &str { match self { Self::Binaryen => "tar.gz", } } + /// check tool state pub fn is_installed(&self) -> bool { tools_path().join(self.name()).is_dir() } + /// get download temp path pub fn temp_out_path(&self) -> PathBuf { temp_path().join(format!("{}-tool.tmp", self.name())) } + /// start to download package pub async fn download_package(&self) -> anyhow::Result { let download_url = self.download_url(); let temp_out = self.temp_out_path(); @@ -125,6 +135,7 @@ impl Tool { Ok(temp_out) } + /// start to install package pub async fn install_package(&self) -> anyhow::Result<()> { let temp_path = self.temp_out_path(); let tool_path = tools_path(); From 3514e341124bd9f0b9f91ad6604c071cd9296685 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Tue, 15 Mar 2022 00:22:41 +0800 Subject: [PATCH 07/15] feat: commit code --- Dioxus.toml | 2 +- src/builder.rs | 27 +++++++++++++++++++++++++-- src/cli/build/mod.rs | 1 + src/tools.rs | 34 +++++++++++++++++++++++++++++----- 4 files changed, 56 insertions(+), 8 deletions(-) diff --git a/Dioxus.toml b/Dioxus.toml index 2db611914..c3e0dd8a0 100644 --- a/Dioxus.toml +++ b/Dioxus.toml @@ -42,4 +42,4 @@ script = [] # use binaryen.wasm-opt for output Wasm file # binaryen just will trigger in `web` platform -binaryen = { wasm_opt = [".PROJECT_OUT"] } \ No newline at end of file +binaryen = { wasm_opt = true } \ No newline at end of file diff --git a/src/builder.rs b/src/builder.rs index 708e1ce69..870e737f0 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -82,19 +82,42 @@ pub fn build(config: &CrateConfig) -> Result<()> { bindgen_builder .input_path(input_path) - .web(true).unwrap() + .web(true) + .unwrap() .debug(true) .demangle(true) .keep_debug(true) .remove_name_section(false) .remove_producers_section(false) .out_name(&dioxus_config.application.name) - .generate(&bindgen_outdir).unwrap(); + .generate(&bindgen_outdir) + .unwrap(); }); if bindgen_result.is_err() { log::error!("Bindgen build failed! \nThis is probably due to the Bindgen version, dioxus-cli using `0.2.79` Bindgen crate."); } + // check binaryen:wasm-opt tool + let dioxus_tools = dioxus_config.application.tools.clone().unwrap_or_default(); + if dioxus_tools.contains_key("binaryen") { + let info = dioxus_tools.get("binaryen").unwrap(); + let binaryen = crate::tools::Tool::Binaryen; + if let Some(sub) = info.as_table() { + println!("sub: {sub:?}"); + if sub.contains_key("wasm_opt") + && sub.get("wasm_opt").unwrap().as_bool().unwrap_or(false) + { + let target_file = out_dir + .join("assets") + .join("dioxus") + .join(format!("{}_bg.wasm", dioxus_config.application.name)); + println!("tf: {target_file:?}"); + if target_file.is_file() { + binaryen.call("wasm-opt", vec![target_file.to_str().unwrap(), "--print"])?; + } + } + } + } // this code will copy all public file to the output dir let copy_options = fs_extra::dir::CopyOptions { diff --git a/src/cli/build/mod.rs b/src/cli/build/mod.rs index 4c043091f..3b4d343af 100644 --- a/src/cli/build/mod.rs +++ b/src/cli/build/mod.rs @@ -12,6 +12,7 @@ impl Build { pub fn build(self) -> Result<()> { let mut crate_config = crate::CrateConfig::new()?; + // change the release state. crate_config.with_release(self.build.release); diff --git a/src/tools.rs b/src/tools.rs index b5c9d658a..b84cd5579 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -1,6 +1,7 @@ use std::{ fs::{create_dir_all, File}, path::PathBuf, + process::Command, }; use anyhow::Context; @@ -47,7 +48,6 @@ pub fn tools_path() -> PathBuf { #[allow(clippy::should_implement_trait)] impl Tool { - /// from str to tool enum pub fn from_str(name: &str) -> Option { match name { @@ -152,12 +152,36 @@ impl Tool { let mut archive = Archive::new(tar); archive.unpack(&tool_path)?; // println!("{:?} -> {:?}", tool_path.join(dir_name), tool_path.join(self.name())); - std::fs::rename( - tool_path.join(dir_name), - tool_path.join(self.name()), - )?; + std::fs::rename(tool_path.join(dir_name), tool_path.join(self.name()))?; } Ok(()) } + + pub fn call(&self, command: &str, args: Vec<&str>) -> anyhow::Result<()> { + let bin_path = tools_path().join(self.name()).join(self.bin_path()); + + let command_file = match self { + Tool::Binaryen => { + if cfg!(target_os = "windows") { + format!("{}.exe", command) + } else { + command.to_string() + } + } + }; + + if !bin_path.join(command_file).is_file() { + return Err(anyhow::anyhow!("Command file not found.")); + } + + let mut command = Command::new(bin_path.to_str().unwrap()); + + command + .args(&args[..]) + .stdout(std::process::Stdio::inherit()) + .stderr(std::process::Stdio::inherit()); + + Ok(()) + } } From 62a2292c16e54fe46c1438d7629ed67831eb5018 Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Tue, 15 Mar 2022 17:32:42 +0800 Subject: [PATCH 08/15] feat: commit code --- src/builder.rs | 18 +++++++++++++++--- src/tools.rs | 14 +++++++------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index 870e737f0..ac9f72b13 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -95,6 +95,7 @@ pub fn build(config: &CrateConfig) -> Result<()> { }); if bindgen_result.is_err() { log::error!("Bindgen build failed! \nThis is probably due to the Bindgen version, dioxus-cli using `0.2.79` Bindgen crate."); + return Ok(()); } // check binaryen:wasm-opt tool @@ -102,8 +103,13 @@ pub fn build(config: &CrateConfig) -> Result<()> { if dioxus_tools.contains_key("binaryen") { let info = dioxus_tools.get("binaryen").unwrap(); let binaryen = crate::tools::Tool::Binaryen; + + if !binaryen.is_installed() { + log::error!("Binaryen tool not found, you can use `dioxus tool add binaryen` to install it."); + return Ok(()); + } + if let Some(sub) = info.as_table() { - println!("sub: {sub:?}"); if sub.contains_key("wasm_opt") && sub.get("wasm_opt").unwrap().as_bool().unwrap_or(false) { @@ -111,9 +117,15 @@ pub fn build(config: &CrateConfig) -> Result<()> { .join("assets") .join("dioxus") .join(format!("{}_bg.wasm", dioxus_config.application.name)); - println!("tf: {target_file:?}"); if target_file.is_file() { - binaryen.call("wasm-opt", vec![target_file.to_str().unwrap(), "--print"])?; + binaryen.call( + "wasm-opt", + vec![ + target_file.to_str().unwrap(), + "-o", + target_file.to_str().unwrap(), + ], + )?; } } } diff --git a/src/tools.rs b/src/tools.rs index b84cd5579..937063be0 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -158,7 +158,7 @@ impl Tool { Ok(()) } - pub fn call(&self, command: &str, args: Vec<&str>) -> anyhow::Result<()> { + pub fn call(&self, command: &str, args: Vec<&str>) -> anyhow::Result> { let bin_path = tools_path().join(self.name()).join(self.bin_path()); let command_file = match self { @@ -171,17 +171,17 @@ impl Tool { } }; - if !bin_path.join(command_file).is_file() { + if !bin_path.join(&command_file).is_file() { return Err(anyhow::anyhow!("Command file not found.")); } - let mut command = Command::new(bin_path.to_str().unwrap()); + let mut command = Command::new(bin_path.join(&command_file).to_str().unwrap()); - command + let output = command .args(&args[..]) .stdout(std::process::Stdio::inherit()) - .stderr(std::process::Stdio::inherit()); - - Ok(()) + .stderr(std::process::Stdio::inherit()) + .output()?; + Ok(output.stdout) } } From 8b380f2617f3845db6d7006790312290c85cf19c Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Tue, 15 Mar 2022 18:28:19 +0800 Subject: [PATCH 09/15] feat: commit code --- src/builder.rs | 43 ++++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/src/builder.rs b/src/builder.rs index ac9f72b13..d58af6f43 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -105,29 +105,30 @@ pub fn build(config: &CrateConfig) -> Result<()> { let binaryen = crate::tools::Tool::Binaryen; if !binaryen.is_installed() { - log::error!("Binaryen tool not found, you can use `dioxus tool add binaryen` to install it."); - return Ok(()); - } - - if let Some(sub) = info.as_table() { - if sub.contains_key("wasm_opt") - && sub.get("wasm_opt").unwrap().as_bool().unwrap_or(false) - { - let target_file = out_dir - .join("assets") - .join("dioxus") - .join(format!("{}_bg.wasm", dioxus_config.application.name)); - if target_file.is_file() { - binaryen.call( - "wasm-opt", - vec![ - target_file.to_str().unwrap(), - "-o", - target_file.to_str().unwrap(), - ], - )?; + if let Some(sub) = info.as_table() { + if sub.contains_key("wasm_opt") + && sub.get("wasm_opt").unwrap().as_bool().unwrap_or(false) + { + let target_file = out_dir + .join("assets") + .join("dioxus") + .join(format!("{}_bg.wasm", dioxus_config.application.name)); + if target_file.is_file() { + binaryen.call( + "wasm-opt", + vec![ + target_file.to_str().unwrap(), + "-o", + target_file.to_str().unwrap(), + ], + )?; + } } } + } else { + log::warn!( + "Binaryen tool not found, you can use `dioxus tool add binaryen` to install it." + ); } } From 6b0d57abe5c70ebd8cc7cdcc9f14fea5c8b738dd Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Sun, 20 Mar 2022 18:39:28 +0800 Subject: [PATCH 10/15] feat: commit code --- Cargo.toml | 2 +- src/server/mod.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8beca8f7d..246e90517 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dioxus-cli" -version = "0.1.3" +version = "0.1.4" authors = ["Jonathan Kelley"] edition = "2018" description = "CLI tool for developing, testing, and publishing Dioxus apps" diff --git a/src/server/mod.rs b/src/server/mod.rs index 38e37d60b..7d63f3eb6 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -33,6 +33,7 @@ pub async fn startup(config: CrateConfig) -> Result<()> { // file watcher: check file change let watcher_conf = config.clone(); let mut watcher = RecommendedWatcher::new(move |_: notify::Result| { + log::info!("Start to rebuild project..."); if chrono::Local::now().timestamp() > last_update_time && builder::build(&watcher_conf).is_ok() { @@ -47,8 +48,7 @@ pub async fn startup(config: CrateConfig) -> Result<()> { { let _ = Serve::regen_dev_page(&watcher_conf); } - println!("watcher send reload"); - reload_tx.send("reload".into()).unwrap(); + let _ = reload_tx.send("reload".into()); last_update_time = chrono::Local::now().timestamp(); } }) From e5dfe84eb1f8c821fa875744ed7ec541de8013ad Mon Sep 17 00:00:00 2001 From: mrxiaozhuox Date: Sun, 20 Mar 2022 19:31:30 +0800 Subject: [PATCH 11/15] feat: add `custom html` support --- src/assets/index.html | 2 -- src/builder.rs | 17 +++++++++++++++-- src/cli/config/mod.rs | 13 +++++++++++-- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/assets/index.html b/src/assets/index.html index 9934e490d..925df0227 100644 --- a/src/assets/index.html +++ b/src/assets/index.html @@ -4,11 +4,9 @@ {style_include} -
-