Merge branch 'master' into breaking

This commit is contained in:
Jonathan Kelley committed 2024-01-30 16:20:19 -08:00
commit eff1dd6c90
29 files changed
+684 -258

No files matched your search

+2 -2
View File
@@ -13,7 +13,7 @@ pub fn asset_manifest(crate_config: &CrateConfig) -> AssetManifest {
/// Create a head file that contains all of the imports for assets that the user project uses
pub fn create_assets_head(config: &CrateConfig, manifest: &AssetManifest) -> Result<()> {
let mut file = File::create(config.out_dir.join("__assets_head.html"))?;
let mut file = File::create(config.out_dir().join("__assets_head.html"))?;
file.write_all(manifest.head().as_bytes())?;
Ok(())
}
@@ -29,7 +29,7 @@ pub(crate) fn process_assets(config: &CrateConfig, manifest: &AssetManifest) ->
.clone()
.unwrap_or_default(),
);
let static_asset_output_dir = config.out_dir.join(static_asset_output_dir);
let static_asset_output_dir = config.out_dir().join(static_asset_output_dir);
manifest.copy_static_assets_to(static_asset_output_dir)?;
+21 -21
View File
@@ -39,14 +39,14 @@ pub fn build(config: &CrateConfig, _: bool, skip_assets: bool) -> Result<BuildRe
// [6] Link up the html page to the wasm module
let CrateConfig {
out_dir,
crate_dir,
target_dir,
asset_dir,
executable,
dioxus_config,
..
} = config;
let out_dir = config.out_dir();
let asset_dir = config.asset_dir();
let _guard = WebAssetConfigDropGuard::new();
let _manganis_support = ManganisSupportGuard::default();
@@ -251,15 +251,15 @@ pub fn build(config: &CrateConfig, _: bool, skip_assets: bool) -> Result<BuildRe
if path.is_file() {
std::fs::copy(&path, out_dir.join(path.file_name().unwrap()))?;
} else {
match fs_extra::dir::copy(&path, out_dir, &copy_options) {
match fs_extra::dir::copy(&path, &out_dir, &copy_options) {
Ok(_) => {}
Err(_e) => {
log::warn!("Error copying dir: {}", _e);
}
}
for ignore in &ignore_files {
let ignore = ignore.strip_prefix(&config.asset_dir).unwrap();
let ignore = config.out_dir.join(ignore);
let ignore = ignore.strip_prefix(&config.asset_dir()).unwrap();
let ignore = out_dir.join(ignore);
if ignore.is_file() {
std::fs::remove_file(ignore)?;
}
@@ -369,13 +369,13 @@ pub fn build_desktop(
file_name
};
if !config.out_dir.is_dir() {
create_dir_all(&config.out_dir)?;
if !config.out_dir().is_dir() {
create_dir_all(config.out_dir())?;
}
copy(res_path, config.out_dir.join(target_file))?;
copy(res_path, config.out_dir().join(target_file))?;
// this code will copy all public file to the output dir
if config.asset_dir.is_dir() {
if config.asset_dir().is_dir() {
let copy_options = fs_extra::dir::CopyOptions {
overwrite: true,
skip_exist: false,
@@ -385,20 +385,20 @@ pub fn build_desktop(
depth: 0,
};
for entry in std::fs::read_dir(&config.asset_dir)? {
for entry in std::fs::read_dir(config.asset_dir())? {
let path = entry?.path();
if path.is_file() {
std::fs::copy(&path, &config.out_dir.join(path.file_name().unwrap()))?;
std::fs::copy(&path, &config.out_dir().join(path.file_name().unwrap()))?;
} else {
match fs_extra::dir::copy(&path, &config.out_dir, &copy_options) {
match fs_extra::dir::copy(&path, &config.out_dir(), &copy_options) {
Ok(_) => {}
Err(e) => {
log::warn!("Error copying dir: {}", e);
}
}
for ignore in &ignore_files {
let ignore = ignore.strip_prefix(&config.asset_dir).unwrap();
let ignore = config.out_dir.join(ignore);
let ignore = ignore.strip_prefix(&config.asset_dir()).unwrap();
let ignore = config.out_dir().join(ignore);
if ignore.is_file() {
std::fs::remove_file(ignore)?;
}
@@ -443,7 +443,7 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
.unwrap()
.tick_chars("/|\\- "),
);
pb.set_message("💼 Waiting to start build the project...");
pb.set_message("💼 Waiting to start building the project...");
let stdout = cmd.detached().stream_stdout()?;
let reader = std::io::BufReader::new(stdout);
@@ -635,7 +635,7 @@ fn build_assets(config: &CrateConfig) -> Result<Vec<PathBuf>> {
if file == "*" {
// if the sass open auto, we need auto-check the assets dir.
let asset_dir = config.asset_dir.clone();
let asset_dir = config.asset_dir().clone();
if asset_dir.is_dir() {
for entry in walkdir::WalkDir::new(&asset_dir)
.into_iter()
@@ -655,7 +655,7 @@ fn build_assets(config: &CrateConfig) -> Result<Vec<PathBuf>> {
temp.file_stem().unwrap().to_str().unwrap()
);
let target_path = config
.out_dir
.out_dir()
.join(
temp.strip_prefix(&asset_dir)
.unwrap()
@@ -685,11 +685,11 @@ fn build_assets(config: &CrateConfig) -> Result<Vec<PathBuf>> {
} else {
file
};
let path = config.asset_dir.join(relative_path);
let path = config.asset_dir().join(relative_path);
let out_file =
format!("{}.css", path.file_stem().unwrap().to_str().unwrap());
let target_path = config
.out_dir
.out_dir()
.join(PathBuf::from(relative_path).parent().unwrap())
.join(out_file);
if path.is_file() {
@@ -719,11 +719,11 @@ fn build_assets(config: &CrateConfig) -> Result<Vec<PathBuf>> {
} else {
path
};
let path = config.asset_dir.join(relative_path);
let path = config.asset_dir().join(relative_path);
let out_file =
format!("{}.css", path.file_stem().unwrap().to_str().unwrap());
let target_path = config
.out_dir
.out_dir()
.join(PathBuf::from(relative_path).parent().unwrap())
.join(out_file);
if path.is_file() {
+1 -1
View File
@@ -1,5 +1,5 @@
use dioxus_autofmt::{IndentOptions, IndentType};
use futures::{stream::FuturesUnordered, StreamExt};
use futures_util::{stream::FuturesUnordered, StreamExt};
use std::{fs, path::Path, process::exit};
use super::*;
+2 -2
View File
@@ -87,7 +87,7 @@ impl Bundle {
build_desktop(&crate_config, false, false)?;
// copy the binary to the out dir
let package = crate_config.manifest.package.unwrap();
let package = crate_config.manifest.package.as_ref().unwrap();
let mut name: PathBuf = match &crate_config.executable {
ExecutableType::Binary(name)
@@ -149,7 +149,7 @@ impl Bundle {
}
let mut settings = SettingsBuilder::new()
.project_out_directory(crate_config.out_dir)
.project_out_directory(crate_config.out_dir())
.package_settings(PackageSettings {
product_name: crate_config.dioxus_config.application.name.clone(),
version: package.version().to_string(),
+3 -1
View File
@@ -78,6 +78,7 @@ impl From<ConfigOptsServe> for ConfigOptsBuild {
}
#[derive(Clone, Debug, Default, Deserialize, Parser)]
#[command(group = clap::ArgGroup::new("release-incompatible").multiple(true).conflicts_with("release"))]
pub struct ConfigOptsServe {
/// Port of dev server
#[clap(long)]
@@ -116,8 +117,9 @@ pub struct ConfigOptsServe {
#[clap(long, value_enum)]
pub platform: Option<Platform>,
/// Build with hot reloading rsx [default: false]
/// Build with hot reloading rsx. Will not work with release builds. [default: false]
#[clap(long)]
#[clap(group = "release-incompatible")]
#[serde(default)]
pub hot_reload: bool,
+1 -1
View File
@@ -1,4 +1,4 @@
use futures::{stream::FuturesUnordered, StreamExt};
use futures_util::{stream::FuturesUnordered, StreamExt};
use std::{path::Path, process::exit};
use super::*;
+26 -24
View File
@@ -1,7 +1,7 @@
use dioxus_cli_config::DioxusConfig;
use std::path::PathBuf;
use anyhow::anyhow;
use anyhow::Context;
use clap::Parser;
use dioxus_cli::*;
@@ -19,24 +19,26 @@ fn get_bin(bin: Option<String>) -> Result<PathBuf> {
.workspace_packages()
.into_iter()
.find(|p| p.name == bin)
.ok_or(format!("no such package: {}", bin))
.map_err(Error::CargoError)?
.ok_or(Error::CargoError(format!("no such package: {}", bin)))?
} else {
metadata
.root_package()
.ok_or("no root package?".into())
.map_err(Error::CargoError)?
.ok_or(Error::CargoError("no root package?".to_string()))?
};
let crate_dir = package
.manifest_path
.parent()
.ok_or("couldn't take parent dir".into())
.map_err(Error::CargoError)?;
.ok_or(Error::CargoError("couldn't take parent dir".to_string()))?;
Ok(crate_dir.into())
}
/// Simplifies error messages that use the same pattern.
fn error_wrapper(message: &str) -> String {
format!("🚫 {message}:")
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = Cli::parse();
@@ -46,35 +48,35 @@ async fn main() -> anyhow::Result<()> {
match args.action {
Translate(opts) => opts
.translate()
.map_err(|e| anyhow!("🚫 Translation of HTML into RSX failed: {}", e)),
.context(error_wrapper("Translation of HTML into RSX failed")),
Create(opts) => opts
.create()
.map_err(|e| anyhow!("🚫 Creating new project failed: {}", e)),
.context(error_wrapper("Creating new project failed")),
Init(opts) => opts
.init()
.map_err(|e| anyhow!("🚫 Initialising a new project failed: {}", e)),
.context(error_wrapper("Initialising a new project failed")),
Config(opts) => opts
.config()
.map_err(|e| anyhow!("🚫 Configuring new project failed: {}", e)),
.context(error_wrapper("Configuring new project failed")),
#[cfg(feature = "plugin")]
Plugin(opts) => opts
.plugin()
.await
.map_err(|e| anyhow!("🚫 Error with plugin: {}", e)),
.context(error_wrapper("Error with plugin")),
Autoformat(opts) => opts
.autoformat()
.await
.map_err(|e| anyhow!("🚫 Error autoformatting RSX: {}", e)),
.context(error_wrapper("Error autoformatting RSX")),
Check(opts) => opts
.check()
.await
.map_err(|e| anyhow!("🚫 Error checking RSX: {}", e)),
.context(error_wrapper("Error checking RSX")),
Version(opt) => {
let version = opt.version();
@@ -85,33 +87,33 @@ async fn main() -> anyhow::Result<()> {
action => {
let bin = get_bin(args.bin)?;
let _dioxus_config = DioxusConfig::load(Some(bin.clone()))
.map_err(|e| anyhow!("Failed to load Dioxus config because: {e}"))?
.unwrap_or_else(|| {
log::info!("You appear to be creating a Dioxus project from scratch; we will use the default config");
DioxusConfig::default()
});
.context("Failed to load Dioxus config because")?
.unwrap_or_else(|| {
log::info!("You appear to be creating a Dioxus project from scratch; we will use the default config");
DioxusConfig::default()
});
#[cfg(feature = "plugin")]
PluginManager::init(_dioxus_config.plugin)
.map_err(|e| anyhow!("🚫 Plugin system initialization failed: {e}"))?;
.context(error_wrapper("Plugin system initialization failed"))?;
match action {
Build(opts) => opts
.build(Some(bin.clone()), None)
.map_err(|e| anyhow!("🚫 Building project failed: {}", e)),
.context(error_wrapper("Building project failed")),
Clean(opts) => opts
.clean(Some(bin.clone()))
.map_err(|e| anyhow!("🚫 Cleaning project failed: {}", e)),
.context(error_wrapper("Cleaning project failed")),
Serve(opts) => opts
.serve(Some(bin.clone()))
.await
.map_err(|e| anyhow!("🚫 Serving project failed: {}", e)),
.context(error_wrapper("Serving project failed")),
Bundle(opts) => opts
.bundle(Some(bin.clone()))
.map_err(|e| anyhow!("🚫 Bundling project failed: {}", e)),
.context(error_wrapper("Bundling project failed")),
_ => unreachable!(),
}
+4 -4
View File
@@ -181,8 +181,8 @@ impl PluginManager {
let args = lua.create_table()?;
args.set("name", crate_config.dioxus_config.application.name.clone())?;
args.set("platform", platform)?;
args.set("out_dir", crate_config.out_dir.to_str().unwrap())?;
args.set("asset_dir", crate_config.asset_dir.to_str().unwrap())?;
args.set("out_dir", crate_config.out_dir().to_str().unwrap())?;
args.set("asset_dir", crate_config.asset_dir().to_str().unwrap())?;
for i in 1..(manager.len()? as i32 + 1) {
let info = manager.get::<i32, PluginInfo>(i)?;
@@ -205,8 +205,8 @@ impl PluginManager {
let args = lua.create_table()?;
args.set("name", crate_config.dioxus_config.application.name.clone())?;
args.set("platform", platform)?;
args.set("out_dir", crate_config.out_dir.to_str().unwrap())?;
args.set("asset_dir", crate_config.asset_dir.to_str().unwrap())?;
args.set("out_dir", crate_config.out_dir().to_str().unwrap())?;
args.set("asset_dir", crate_config.asset_dir().to_str().unwrap())?;
for i in 1..(manager.len()? as i32 + 1) {
let info = manager.get::<i32, PluginInfo>(i)?;
+1 -1
View File
@@ -221,7 +221,7 @@ fn start_desktop(config: &CrateConfig, skip_assets: bool) -> Result<(RAIIChild,
ExecutableType::Binary(name)
| ExecutableType::Lib(name)
| ExecutableType::Example(name) => {
let mut file = config.out_dir.join(name);
let mut file = config.out_dir().join(name);
if cfg!(windows) {
file.set_extension("exe");
}
+88 -78
View File
@@ -31,93 +31,103 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
let mut watcher = notify::recommended_watcher(move |info: notify::Result<notify::Event>| {
let config = watcher_config.clone();
if let Ok(e) = info {
if chrono::Local::now().timestamp() > last_update_time {
let mut needs_full_rebuild;
if let Some(hot_reload) = &hot_reload {
// find changes to the rsx in the file
let mut rsx_file_map = hot_reload.file_map.lock().unwrap();
let mut messages: Vec<Template> = Vec::new();
match e.kind {
notify::EventKind::Create(_)
| notify::EventKind::Remove(_)
| notify::EventKind::Modify(_) => {
if chrono::Local::now().timestamp() > last_update_time {
let mut needs_full_rebuild;
if let Some(hot_reload) = &hot_reload {
// find changes to the rsx in the file
let mut rsx_file_map = hot_reload.file_map.lock().unwrap();
let mut messages: Vec<Template> = Vec::new();
// In hot reload mode, we only need to rebuild if non-rsx code is changed
needs_full_rebuild = false;
// In hot reload mode, we only need to rebuild if non-rsx code is changed
needs_full_rebuild = false;
for path in &e.paths {
// if this is not a rust file, rebuild the whole project
if path.extension().and_then(|p| p.to_str()) != Some("rs") {
for path in &e.paths {
// if this is not a rust file, rebuild the whole project
if path.extension().and_then(|p| p.to_str()) != Some("rs") {
needs_full_rebuild = true;
break;
}
// Workaround for notify and vscode-like editor:
// when edit & save a file in vscode, there will be two notifications,
// the first one is a file with empty content.
// filter the empty file notification to avoid false rebuild during hot-reload
if let Ok(metadata) = fs::metadata(path) {
if metadata.len() == 0 {
continue;
}
}
match rsx_file_map.update_rsx(path, &config.crate_dir) {
Ok(UpdateResult::UpdatedRsx(msgs)) => {
messages.extend(msgs);
needs_full_rebuild = false;
}
Ok(UpdateResult::NeedsRebuild) => {
needs_full_rebuild = true;
}
Err(err) => {
log::error!("{}", err);
}
}
}
if needs_full_rebuild {
// Reset the file map to the new state of the project
let FileMapBuildResult {
map: new_file_map,
errors,
} = FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
for err in errors {
log::error!("{}", err);
}
*rsx_file_map = new_file_map;
} else {
for msg in messages {
let _ = hot_reload.messages.send(msg);
}
}
} else {
needs_full_rebuild = true;
break;
}
// Workaround for notify and vscode-like editor:
// when edit & save a file in vscode, there will be two notifications,
// the first one is a file with empty content.
// filter the empty file notification to avoid false rebuild during hot-reload
if let Ok(metadata) = fs::metadata(path) {
if metadata.len() == 0 {
continue;
if needs_full_rebuild {
match build_with() {
Ok(res) => {
last_update_time = chrono::Local::now().timestamp();
#[allow(clippy::redundant_clone)]
print_console_info(
&config,
PrettierOptions {
changed: e.paths.clone(),
warnings: res.warnings,
elapsed_time: res.elapsed_time,
},
web_info.clone(),
);
#[cfg(feature = "plugin")]
let _ = PluginManager::on_serve_rebuild(
chrono::Local::now().timestamp(),
e.paths,
);
}
Err(e) => {
last_update_time = chrono::Local::now().timestamp();
log::error!("{:?}", e);
}
}
}
match rsx_file_map.update_rsx(path, &config.crate_dir) {
Ok(UpdateResult::UpdatedRsx(msgs)) => {
messages.extend(msgs);
needs_full_rebuild = false;
}
Ok(UpdateResult::NeedsRebuild) => {
needs_full_rebuild = true;
}
Err(err) => {
log::error!("{}", err);
}
}
}
if needs_full_rebuild {
// Reset the file map to the new state of the project
let FileMapBuildResult {
map: new_file_map,
errors,
} = FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
for err in errors {
log::error!("{}", err);
}
*rsx_file_map = new_file_map;
} else {
for msg in messages {
let _ = hot_reload.messages.send(msg);
}
}
} else {
needs_full_rebuild = true;
}
if needs_full_rebuild {
match build_with() {
Ok(res) => {
last_update_time = chrono::Local::now().timestamp();
#[allow(clippy::redundant_clone)]
print_console_info(
&config,
PrettierOptions {
changed: e.paths.clone(),
warnings: res.warnings,
elapsed_time: res.elapsed_time,
},
web_info.clone(),
);
#[cfg(feature = "plugin")]
let _ = crate::plugin::PluginManager::on_serve_rebuild(
chrono::Local::now().timestamp(),
e.paths,
);
}
Err(e) => log::error!("{}", e),
}
}
_ => {}
}
}
})
+2 -2
View File
@@ -290,7 +290,7 @@ async fn setup_router(
std::fs::read_to_string(
file_service_config
.crate_dir
.join(file_service_config.out_dir)
.join(file_service_config.out_dir())
.join("index.html"),
)
.ok()
@@ -315,7 +315,7 @@ async fn setup_router(
Ok(response)
},
)
.service(ServeDir::new(config.crate_dir.join(&config.out_dir)));
.service(ServeDir::new(config.crate_dir.join(config.out_dir())));
// Setup websocket
let mut router = Router::new().route("/_dioxus/ws", get(ws_handler));
+1 -1
View File
@@ -7,7 +7,7 @@ use std::{
use anyhow::Context;
use flate2::read::GzDecoder;
use futures::StreamExt;
use futures_util::StreamExt;
use tar::Archive;
use tokio::io::AsyncWriteExt;