Merge branch 'cli-serde-default' into cli-config-library

This commit is contained in:
Evan Almloff committed 2023-11-10 16:26:58 -06:00
commit 5dc3486c53
9 files changed
+103 -117

No files matched your search

+7 -24
View File
@@ -134,7 +134,7 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
} }
// check binaryen:wasm-opt tool // check binaryen:wasm-opt tool
let dioxus_tools = dioxus_config.application.tools.clone().unwrap_or_default(); let dioxus_tools = dioxus_config.application.tools.clone();
if dioxus_tools.contains_key("binaryen") { if dioxus_tools.contains_key("binaryen") {
let info = dioxus_tools.get("binaryen").unwrap(); let info = dioxus_tools.get("binaryen").unwrap();
let binaryen = crate::tools::Tool::Binaryen; let binaryen = crate::tools::Tool::Binaryen;
@@ -351,13 +351,7 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
log::info!( log::info!(
"🚩 Build completed: [./{}]", "🚩 Build completed: [./{}]",
config config.dioxus_config.application.out_dir.clone().display()
.dioxus_config
.application
.out_dir
.clone()
.unwrap_or_else(|| PathBuf::from("dist"))
.display()
); );
println!("build desktop done"); println!("build desktop done");
@@ -450,8 +444,8 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
let mut script_list = resources.script.unwrap_or_default(); let mut script_list = resources.script.unwrap_or_default();
if serve { if serve {
let mut dev_style = resources.dev.style.clone().unwrap_or_default(); let mut dev_style = resouces.dev.style.clone();
let mut dev_script = resources.dev.script.unwrap_or_default(); let mut dev_script = resouces.dev.script.clone();
style_list.append(&mut dev_style); style_list.append(&mut dev_style);
script_list.append(&mut dev_script); script_list.append(&mut dev_script);
} }
@@ -463,13 +457,7 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
&style.to_str().unwrap(), &style.to_str().unwrap(),
)) ))
} }
if config if config.application.tools.clone().contains_key("tailwindcss") {
.application
.tools
.clone()
.unwrap_or_default()
.contains_key("tailwindcss")
{
style_str.push_str("<link rel=\"stylesheet\" href=\"tailwind.css\">\n"); style_str.push_str("<link rel=\"stylesheet\" href=\"tailwind.css\">\n");
} }
@@ -520,12 +508,7 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
); );
} }
let title = config let title = config.web.app.title.clone();
.web
.app
.title
.clone()
.unwrap_or_else(|| "dioxus | ⛺".into());
replace_or_insert_before("{app_title}", &title, "</title", &mut html); replace_or_insert_before("{app_title}", &title, "</title", &mut html);
@@ -552,7 +535,7 @@ fn build_assets(config: &CrateConfig) -> Result<Vec<PathBuf>> {
let mut result = vec![]; let mut result = vec![];
let dioxus_config = &config.dioxus_config; let dioxus_config = &config.dioxus_config;
let dioxus_tools = dioxus_config.application.tools.clone().unwrap_or_default(); let dioxus_tools = dioxus_config.application.tools.clone();
// check sass tool state // check sass tool state
let sass = Tool::Sass; let sass = Tool::Sass;
+1 -8
View File
@@ -54,14 +54,7 @@ impl Build {
let mut file = std::fs::File::create( let mut file = std::fs::File::create(
crate_config crate_config
.crate_dir .crate_dir
.join( .join(crate_config.dioxus_config.application.out_dir.clone())
crate_config
.dioxus_config
.application
.out_dir
.clone()
.unwrap_or_else(|| PathBuf::from("dist")),
)
.join("index.html"), .join("index.html"),
)?; )?;
file.write_all(temp.as_bytes())?; file.write_all(temp.as_bytes())?;
+1 -5
View File
@@ -19,11 +19,7 @@ impl Clean {
return custom_error!("Cargo clean failed."); return custom_error!("Cargo clean failed.");
} }
let out_dir = crate_config let out_dir = crate_config.dioxus_config.application.out_dir;
.dioxus_config
.application
.out_dir
.unwrap_or_else(|| PathBuf::from("dist"));
if crate_config.crate_dir.join(&out_dir).is_dir() { if crate_config.crate_dir.join(&out_dir).is_dir() {
remove_dir_all(crate_config.crate_dir.join(&out_dir))?; remove_dir_all(crate_config.crate_dir.join(&out_dir))?;
} }
+3 -8
View File
@@ -60,14 +60,9 @@ impl Serve {
pub fn regen_dev_page(crate_config: &CrateConfig) -> Result<()> { pub fn regen_dev_page(crate_config: &CrateConfig) -> Result<()> {
let serve_html = gen_page(&crate_config.dioxus_config, true); let serve_html = gen_page(&crate_config.dioxus_config, true);
let dist_path = crate_config.crate_dir.join( let dist_path = crate_config
crate_config .crate_dir
.dioxus_config .join(crate_config.dioxus_config.application.out_dir.clone());
.application
.out_dir
.clone()
.unwrap_or_else(|| PathBuf::from("dist")),
);
if !dist_path.is_dir() { if !dist_path.is_dir() {
create_dir_all(&dist_path)?; create_dir_all(&dist_path)?;
} }
+77 -32
View File
@@ -87,33 +87,33 @@ fn acquire_dioxus_toml(dir: &Path) -> Option<PathBuf> {
impl Default for DioxusConfig { impl Default for DioxusConfig {
fn default() -> Self { fn default() -> Self {
let name = "name"; let name = default_name();
Self { Self {
application: ApplicationConfig { application: ApplicationConfig {
name: name.into(), name: name.clone(),
default_platform: Platform::Web, default_platform: default_platform(),
out_dir: Some(PathBuf::from("dist")), out_dir: out_dir_default(),
asset_dir: Some(PathBuf::from("public")), asset_dir: asset_dir_default(),
tools: None, tools: Default::default(),
sub_package: None, sub_package: None,
}, },
web: WebConfig { web: WebConfig {
app: WebAppConfig { app: WebAppConfig {
title: Some("dioxus | ⛺".into()), title: default_title(),
base_path: None, base_path: None,
}, },
proxy: Some(vec![]), proxy: vec![],
watcher: WebWatcherConfig { watcher: WebWatcherConfig {
watch_path: Some(vec![PathBuf::from("src"), PathBuf::from("examples")]), watch_path: watch_path_default(),
reload_html: Some(false), reload_html: false,
index_on_404: Some(true), index_on_404: true,
}, },
resource: WebResourceConfig { resource: WebResourceConfig {
dev: WebDevResourceConfig { dev: WebDevResourceConfig {
style: Some(vec![]), style: vec![],
script: Some(vec![]), script: vec![],
}, },
style: Some(vec![]), style: Some(vec![]),
script: Some(vec![]), script: Some(vec![]),
@@ -127,7 +127,7 @@ impl Default for DioxusConfig {
}, },
bundle: BundleConfig { bundle: BundleConfig {
identifier: Some(format!("io.github.{name}")), identifier: Some(format!("io.github.{name}")),
publisher: Some(name.into()), publisher: Some(name),
..Default::default() ..Default::default()
}, },
plugin: toml::Value::Table(toml::map::Map::new()), plugin: toml::Value::Table(toml::map::Map::new()),
@@ -137,20 +137,44 @@ impl Default for DioxusConfig {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApplicationConfig { pub struct ApplicationConfig {
#[serde(default = "default_name")]
pub name: String, pub name: String,
#[serde(default = "default_platform")]
pub default_platform: Platform, pub default_platform: Platform,
pub out_dir: Option<PathBuf>, #[serde(default = "out_dir_default")]
pub asset_dir: Option<PathBuf>, pub out_dir: PathBuf,
#[serde(default = "asset_dir_default")]
pub asset_dir: PathBuf,
pub tools: Option<HashMap<String, toml::Value>>, #[serde(default)]
pub tools: HashMap<String, toml::Value>,
#[serde(default)]
pub sub_package: Option<String>, pub sub_package: Option<String>,
} }
fn default_name() -> String {
"name".into()
}
fn default_platform() -> Platform {
Platform::Web
}
fn asset_dir_default() -> PathBuf {
PathBuf::from("public")
}
fn out_dir_default() -> PathBuf {
PathBuf::from("dist")
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebConfig { pub struct WebConfig {
#[serde(default)]
pub app: WebAppConfig, pub app: WebAppConfig,
pub proxy: Option<Vec<WebProxyConfig>>, #[serde(default)]
pub proxy: Vec<WebProxyConfig>,
pub watcher: WebWatcherConfig, pub watcher: WebWatcherConfig,
pub resource: WebResourceConfig, pub resource: WebResourceConfig,
#[serde(default)] #[serde(default)]
@@ -159,10 +183,24 @@ pub struct WebConfig {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebAppConfig { pub struct WebAppConfig {
pub title: Option<String>, #[serde(default = "default_title")]
pub title: String,
pub base_path: Option<String>, pub base_path: Option<String>,
} }
impl Default for WebAppConfig {
fn default() -> Self {
Self {
title: default_title(),
base_path: None,
}
}
}
fn default_title() -> String {
"dioxus | ⛺".into()
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebProxyConfig { pub struct WebProxyConfig {
pub backend: String, pub backend: String,
@@ -170,9 +208,16 @@ pub struct WebProxyConfig {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebWatcherConfig { pub struct WebWatcherConfig {
pub watch_path: Option<Vec<PathBuf>>, #[serde(default = "watch_path_default")]
pub reload_html: Option<bool>, pub watch_path: Vec<PathBuf>,
pub index_on_404: Option<bool>, #[serde(default)]
pub reload_html: bool,
#[serde(default = "true_bool")]
pub index_on_404: bool,
}
fn watch_path_default() -> Vec<PathBuf> {
vec![PathBuf::from("src"), PathBuf::from("examples")]
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -184,8 +229,10 @@ pub struct WebResourceConfig {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebDevResourceConfig { pub struct WebDevResourceConfig {
pub style: Option<Vec<PathBuf>>, #[serde(default)]
pub script: Option<Vec<PathBuf>>, pub style: Vec<PathBuf>,
#[serde(default)]
pub script: Vec<PathBuf>,
} }
#[derive(Debug, Default, Clone, Serialize, Deserialize)] #[derive(Debug, Default, Clone, Serialize, Deserialize)]
@@ -239,17 +286,11 @@ impl CrateConfig {
let workspace_dir = meta.workspace_root; let workspace_dir = meta.workspace_root;
let target_dir = meta.target_directory; let target_dir = meta.target_directory;
let out_dir = match dioxus_config.application.out_dir { let out_dir = crate_dir.join(&dioxus_config.application.out_dir);
Some(ref v) => crate_dir.join(v),
None => crate_dir.join("dist"),
};
let cargo_def = &crate_dir.join("Cargo.toml"); let cargo_def = &crate_dir.join("Cargo.toml");
let asset_dir = match dioxus_config.application.asset_dir { let asset_dir = crate_dir.join(&dioxus_config.application.asset_dir);
Some(ref v) => crate_dir.join(v),
None => crate_dir.join("public"),
};
let manifest = cargo_toml::Manifest::from_path(cargo_def).unwrap(); let manifest = cargo_toml::Manifest::from_path(cargo_def).unwrap();
@@ -581,3 +622,7 @@ impl Default for WebviewInstallMode {
Self::OfflineInstaller { silent: false } Self::OfflineInstaller { silent: false }
} }
} }
fn true_bool() -> bool {
true
}
+2 -11
View File
@@ -5,10 +5,7 @@ use dioxus_core::Template;
use dioxus_html::HtmlCtx; use dioxus_html::HtmlCtx;
use dioxus_rsx::hot_reload::*; use dioxus_rsx::hot_reload::*;
use notify::{RecommendedWatcher, Watcher}; use notify::{RecommendedWatcher, Watcher};
use std::{ use std::sync::{Arc, Mutex};
path::PathBuf,
sync::{Arc, Mutex},
};
use tokio::sync::broadcast::{self}; use tokio::sync::broadcast::{self};
mod output; mod output;
@@ -26,13 +23,7 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
let mut last_update_time = chrono::Local::now().timestamp(); let mut last_update_time = chrono::Local::now().timestamp();
// file watcher: check file change // file watcher: check file change
let allow_watch_path = config let allow_watch_path = config.dioxus_config.web.watcher.watch_path.clone();
.dioxus_config
.web
.watcher
.watch_path
.clone()
.unwrap_or_else(|| vec![PathBuf::from("src"), PathBuf::from("examples")]);
let watcher_config = config.clone(); let watcher_config = config.clone();
let mut watcher = notify::recommended_watcher(move |info: notify::Result<notify::Event>| { let mut watcher = notify::recommended_watcher(move |info: notify::Result<notify::Event>| {
+6 -14
View File
@@ -47,19 +47,13 @@ pub fn print_console_info(
} else { } else {
"Default" "Default"
}; };
let url_rewrite = if config let url_rewrite = if config.dioxus_config.web.watcher.index_on_404 {
.dioxus_config
.web
.watcher
.index_on_404
.unwrap_or(false)
{
"True" "True"
} else { } else {
"False" "False"
}; };
let proxies = config.dioxus_config.web.proxy.as_ref(); let proxies = &config.dioxus_config.web.proxy;
if options.changed.is_empty() { if options.changed.is_empty() {
println!( println!(
@@ -107,12 +101,10 @@ pub fn print_console_info(
println!(); println!();
println!("\t> Profile : {}", profile.green()); println!("\t> Profile : {}", profile.green());
println!("\t> Hot Reload : {}", hot_reload.cyan()); println!("\t> Hot Reload : {}", hot_reload.cyan());
if let Some(proxies) = proxies { if !proxies.is_empty() {
if !proxies.is_empty() { println!("\t> Proxies :");
println!("\t> Proxies :"); for proxy in proxies {
for proxy in proxies { println!("\t\t- {}", proxy.backend.blue());
println!("\t\t- {}", proxy.backend.blue());
}
} }
} }
println!("\t> Index Template : {}", custom_html_file.green()); println!("\t> Index Template : {}", custom_html_file.green());
+3 -14
View File
@@ -262,12 +262,7 @@ async fn setup_router(
.override_response_header(HeaderName::from_static("cross-origin-opener-policy"), coop) .override_response_header(HeaderName::from_static("cross-origin-opener-policy"), coop)
.and_then( .and_then(
move |response: Response<ServeFileSystemResponseBody>| async move { move |response: Response<ServeFileSystemResponseBody>| async move {
let response = if file_service_config let response = if file_service_config.dioxus_config.web.watcher.index_on_404
.dioxus_config
.web
.watcher
.index_on_404
.unwrap_or(false)
&& response.status() == StatusCode::NOT_FOUND && response.status() == StatusCode::NOT_FOUND
{ {
let body = Full::from( let body = Full::from(
@@ -299,7 +294,7 @@ async fn setup_router(
let mut router = Router::new().route("/_dioxus/ws", get(ws_handler)); let mut router = Router::new().route("/_dioxus/ws", get(ws_handler));
// Setup proxy // Setup proxy
for proxy_config in config.dioxus_config.web.proxy.unwrap_or_default() { for proxy_config in config.dioxus_config.web.proxy {
router = proxy::add_proxy(router, &proxy_config)?; router = proxy::add_proxy(router, &proxy_config)?;
} }
@@ -416,13 +411,7 @@ fn build(config: &CrateConfig, reload_tx: &Sender<()>) -> Result<BuildResult> {
let result = builder::build(config, true)?; let result = builder::build(config, true)?;
// change the websocket reload state to true; // change the websocket reload state to true;
// the page will auto-reload. // the page will auto-reload.
if config if config.dioxus_config.web.watcher.reload_html {
.dioxus_config
.web
.watcher
.reload_html
.unwrap_or(false)
{
let _ = Serve::regen_dev_page(config); let _ = Serve::regen_dev_page(config);
} }
let _ = reload_tx.send(()); let _ = reload_tx.send(());
+3 -1
View File
@@ -631,7 +631,7 @@ Finally, call `.build()` to create the instance of `{name}`.
Ok(quote! { Ok(quote! {
impl #impl_generics #name #ty_generics #where_clause { impl #impl_generics #name #ty_generics #where_clause {
#[doc = #builder_method_doc] #[doc = #builder_method_doc]
#[allow(dead_code)] #[allow(dead_code, clippy::type_complexity)]
#vis fn builder() -> #builder_name #generics_with_empty { #vis fn builder() -> #builder_name #generics_with_empty {
#builder_name { #builder_name {
fields: #empties_tuple, fields: #empties_tuple,
@@ -823,6 +823,7 @@ Finally, call `.build()` to create the instance of `{name}`.
#[allow(dead_code, non_camel_case_types, missing_docs)] #[allow(dead_code, non_camel_case_types, missing_docs)]
impl #impl_generics #builder_name < #( #ty_generics ),* > #where_clause { impl #impl_generics #builder_name < #( #ty_generics ),* > #where_clause {
#doc #doc
#[allow(clippy::type_complexity)]
pub fn #field_name (self, #field_name: #arg_type) -> #builder_name < #( #target_generics ),* > { pub fn #field_name (self, #field_name: #arg_type) -> #builder_name < #( #target_generics ),* > {
let #field_name = (#arg_expr,); let #field_name = (#arg_expr,);
let ( #(#descructuring,)* ) = self.fields; let ( #(#descructuring,)* ) = self.fields;
@@ -841,6 +842,7 @@ Finally, call `.build()` to create the instance of `{name}`.
#[deprecated( #[deprecated(
note = #repeated_fields_error_message note = #repeated_fields_error_message
)] )]
#[allow(clippy::type_complexity)]
pub fn #field_name (self, _: #repeated_fields_error_type_name) -> #builder_name < #( #target_generics ),* > { pub fn #field_name (self, _: #repeated_fields_error_type_name) -> #builder_name < #( #target_generics ),* > {
self self
} }