Merge branch 'master' into intigrate-collect-assets

This commit is contained in:
Evan Almloff committed 2023-12-08 08:49:17 -06:00
commit 66e2c02bf7
168 files changed
+3727 -858

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "dioxus-cli"
version = "0.4.1"
version = "0.4.3"
authors = ["Jonathan Kelley"]
edition = "2021"
description = "CLI tool for developing, testing, and publishing Dioxus apps"
+1 -1
View File
@@ -11,7 +11,7 @@ It handles building, bundling, development and publishing to simplify developmen
### Install the stable version (recommended)
```
cargo install dioxus-cli --locked
cargo install dioxus-cli
```
### Install the latest development build through git
+1 -1
View File
@@ -23,7 +23,7 @@ title = "Dioxus | An elegant GUI library for Rust"
index_on_404 = true
watch_path = ["src"]
watch_path = ["src", "examples"]
# include `assets` in web platform
[web.resource]
+16 -4
View File
@@ -49,14 +49,25 @@ pub fn build(config: &CrateConfig, _: bool, skip_assets: bool) -> Result<BuildRe
// [1] Build the .wasm module
log::info!("🚅 Running build command...");
let wasm_check_command = std::process::Command::new("rustup")
.args(["show"])
.output()?;
let wasm_check_output = String::from_utf8(wasm_check_command.stdout).unwrap();
if !wasm_check_output.contains("wasm32-unknown-unknown") {
log::info!("wasm32-unknown-unknown target not detected, installing..");
let _ = std::process::Command::new("rustup")
.args(["target", "add", "wasm32-unknown-unknown"])
.output()?;
}
let cmd = subprocess::Exec::cmd("cargo");
let cmd = cmd
.cwd(crate_dir)
.arg("build")
.arg("--target")
.arg("wasm32-unknown-unknown")
.arg("--message-format=json")
.arg("--quiet");
.arg("--message-format=json");
let cmd = if config.release {
cmd.arg("--release")
@@ -66,7 +77,7 @@ pub fn build(config: &CrateConfig, _: bool, skip_assets: bool) -> Result<BuildRe
let cmd = if config.verbose {
cmd.arg("--verbose")
} else {
cmd
cmd.arg("--quiet")
};
let cmd = if config.custom_profile.is_some() {
@@ -263,6 +274,7 @@ pub fn build_desktop(
let mut cmd = subprocess::Exec::cmd("cargo")
.cwd(&config.crate_dir)
.arg("build")
.arg("--quiet")
.arg("--message-format=json");
if config.release {
@@ -494,7 +506,7 @@ pub fn gen_page(config: &CrateConfig, serve: bool, skip_assets: bool) -> String
.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=\"/{base_path}/tailwind.css\">\n");
}
if !skip_assets {
let manifest = config.asset_manifest();
+62 -6
View File
@@ -1,3 +1,4 @@
use dioxus_autofmt::{IndentOptions, IndentType};
use futures::{stream::FuturesUnordered, StreamExt};
use std::{fs, path::Path, process::exit};
@@ -35,7 +36,8 @@ impl Autoformat {
}
if let Some(raw) = self.raw {
if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0) {
let indent = indentation_for(".")?;
if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0, indent) {
println!("{}", inner);
} else {
// exit process with error
@@ -46,17 +48,21 @@ impl Autoformat {
// Format single file
if let Some(file) = self.file {
let file_content = if file == "-" {
let file_content;
let indent;
if file == "-" {
indent = indentation_for(".")?;
let mut contents = String::new();
std::io::stdin().read_to_string(&mut contents)?;
Ok(contents)
file_content = Ok(contents);
} else {
fs::read_to_string(&file)
indent = indentation_for(".")?;
file_content = fs::read_to_string(&file);
};
match file_content {
Ok(s) => {
let edits = dioxus_autofmt::fmt_file(&s);
let edits = dioxus_autofmt::fmt_file(&s, indent);
let out = dioxus_autofmt::apply_formats(&s, edits);
if file == "-" {
print!("{}", out);
@@ -93,6 +99,12 @@ async fn autoformat_project(check: bool) -> Result<()> {
let mut files_to_format = vec![];
collect_rs_files(&crate_config.crate_dir, &mut files_to_format);
if files_to_format.is_empty() {
return Ok(());
}
let indent = indentation_for(&files_to_format[0])?;
let counts = files_to_format
.into_iter()
.filter(|file| {
@@ -104,10 +116,11 @@ async fn autoformat_project(check: bool) -> Result<()> {
})
.map(|path| async {
let _path = path.clone();
let _indent = indent.clone();
let res = tokio::spawn(async move {
let contents = tokio::fs::read_to_string(&path).await?;
let edits = dioxus_autofmt::fmt_file(&contents);
let edits = dioxus_autofmt::fmt_file(&contents, _indent.clone());
let len = edits.len();
if !edits.is_empty() {
@@ -151,6 +164,49 @@ async fn autoformat_project(check: bool) -> Result<()> {
Ok(())
}
fn indentation_for(file_or_dir: impl AsRef<Path>) -> Result<IndentOptions> {
let out = std::process::Command::new("cargo")
.args(["fmt", "--", "--print-config", "current"])
.arg(file_or_dir.as_ref())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit())
.output()?;
if !out.status.success() {
return Err(Error::CargoError("cargo fmt failed".into()));
}
let config = String::from_utf8_lossy(&out.stdout);
let hard_tabs = config
.lines()
.find(|line| line.starts_with("hard_tabs "))
.and_then(|line| line.split_once('='))
.map(|(_, value)| value.trim() == "true")
.ok_or_else(|| {
Error::RuntimeError("Could not find hard_tabs option in rustfmt config".into())
})?;
let tab_spaces = config
.lines()
.find(|line| line.starts_with("tab_spaces "))
.and_then(|line| line.split_once('='))
.map(|(_, value)| value.trim().parse::<usize>())
.ok_or_else(|| {
Error::RuntimeError("Could not find tab_spaces option in rustfmt config".into())
})?
.map_err(|_| {
Error::RuntimeError("Could not parse tab_spaces option in rustfmt config".into())
})?;
Ok(IndentOptions::new(
if hard_tabs {
IndentType::Tabs
} else {
IndentType::Spaces
},
tab_spaces,
))
}
fn collect_rs_files(folder: &Path, files: &mut Vec<PathBuf>) {
let Ok(folder) = folder.read_dir() else {
return;
+4 -4
View File
@@ -39,8 +39,8 @@ impl Build {
.platform
.unwrap_or(crate_config.dioxus_config.application.default_platform);
#[cfg(feature = "plugin")]
let _ = PluginManager::on_build_start(&crate_config, &platform);
// #[cfg(feature = "plugin")]
// let _ = PluginManager::on_build_start(&crate_config, &platform);
match platform {
Platform::Web => {
@@ -98,8 +98,8 @@ impl Build {
)?;
file.write_all(temp.as_bytes())?;
#[cfg(feature = "plugin")]
let _ = PluginManager::on_build_finish(&crate_config, &platform);
// #[cfg(feature = "plugin")]
// let _ = PluginManager::on_build_finish(&crate_config, &platform);
Ok(())
}
+1 -1
View File
@@ -107,7 +107,7 @@ impl Default for DioxusConfig {
},
proxy: Some(vec![]),
watcher: WebWatcherConfig {
watch_path: Some(vec![PathBuf::from("src")]),
watch_path: Some(vec![PathBuf::from("src"), PathBuf::from("examples")]),
reload_html: Some(false),
index_on_404: Some(true),
},
+3
View File
@@ -29,6 +29,9 @@ pub enum Error {
#[error("Cargo Error: {0}")]
CargoError(String),
#[error("Couldn't retrieve cargo metadata")]
CargoMetadata(#[source] cargo_metadata::Error),
#[error("{0}")]
CustomError(String),
+13 -1
View File
@@ -28,7 +28,19 @@ pub fn set_up_logging() {
message = message,
));
})
.level(log::LevelFilter::Info)
.level(match std::env::var("DIOXUS_LOG") {
Ok(level) => match level.to_lowercase().as_str() {
"error" => log::LevelFilter::Error,
"warn" => log::LevelFilter::Warn,
"info" => log::LevelFilter::Info,
"debug" => log::LevelFilter::Debug,
"trace" => log::LevelFilter::Trace,
_ => {
panic!("Invalid log level: {}", level)
}
},
Err(_) => log::LevelFilter::Info,
})
.chain(std::io::stdout())
.apply()
.unwrap();
+28 -39
View File
@@ -9,42 +9,31 @@ use dioxus_cli::plugin::PluginManager;
use Commands::*;
fn get_bin(bin: Option<String>) -> Result<Option<PathBuf>> {
const ERR_MESSAGE: &str = "The `--bin` flag has to be ran in a Cargo workspace.";
fn get_bin(bin: Option<String>) -> Result<PathBuf> {
let metadata = cargo_metadata::MetadataCommand::new()
.exec()
.map_err(Error::CargoMetadata)?;
let package = if let Some(bin) = bin {
metadata
.workspace_packages()
.into_iter()
.find(|p| p.name == bin)
.ok_or(format!("no such package: {}", bin))
.map_err(Error::CargoError)?
} else {
metadata
.root_package()
.ok_or("no root package?".into())
.map_err(Error::CargoError)?
};
if let Some(ref bin) = bin {
let manifest = cargo_toml::Manifest::from_path("./Cargo.toml")
.map_err(|_| Error::CargoError(ERR_MESSAGE.to_string()))?;
let crate_dir = package
.manifest_path
.parent()
.ok_or("couldn't take parent dir".into())
.map_err(Error::CargoError)?;
if let Some(workspace) = manifest.workspace {
for item in workspace.members.iter() {
let path = PathBuf::from(item);
if !path.exists() {
continue;
}
if !path.is_dir() {
continue;
}
if path.ends_with(bin.clone()) {
return Ok(Some(path));
}
}
} else {
return Err(Error::CargoError(ERR_MESSAGE.to_string()));
}
}
// If the bin exists but we couldn't find it
if bin.is_some() {
return Err(Error::CargoError(
"The specified bin does not exist.".to_string(),
));
}
Ok(None)
Ok(crate_dir.into())
}
#[tokio::main]
@@ -55,7 +44,7 @@ async fn main() -> anyhow::Result<()> {
let bin = get_bin(args.bin)?;
let _dioxus_config = DioxusConfig::load(bin.clone())
let _dioxus_config = DioxusConfig::load(Some(bin.clone()))
.map_err(|e| anyhow!("Failed to load Dioxus config because: {e}"))?
.unwrap_or_else(|| {
log::warn!("You appear to be creating a Dioxus project from scratch; we will use the default config");
@@ -72,15 +61,15 @@ async fn main() -> anyhow::Result<()> {
.map_err(|e| anyhow!("🚫 Translation of HTML into RSX failed: {}", e)),
Build(opts) => opts
.build(bin.clone())
.build(Some(bin.clone()))
.map_err(|e| anyhow!("🚫 Building project failed: {}", e)),
Clean(opts) => opts
.clean(bin.clone())
.clean(Some(bin.clone()))
.map_err(|e| anyhow!("🚫 Cleaning project failed: {}", e)),
Serve(opts) => opts
.serve(bin.clone())
.serve(Some(bin.clone()))
.await
.map_err(|e| anyhow!("🚫 Serving project failed: {}", e)),
@@ -93,7 +82,7 @@ async fn main() -> anyhow::Result<()> {
.map_err(|e| anyhow!("🚫 Configuring new project failed: {}", e)),
Bundle(opts) => opts
.bundle(bin.clone())
.bundle(Some(bin.clone()))
.map_err(|e| anyhow!("🚫 Bundling project failed: {}", e)),
#[cfg(feature = "plugin")]
+13 -11
View File
@@ -51,8 +51,6 @@ pub(crate) async fn startup_with_platform<P: Platform + Send + 'static>(
let hot_reload_tx = broadcast::channel(100).0;
clear_paths();
Some(HotReloadState {
messages: hot_reload_tx.clone(),
file_map: file_map.clone(),
@@ -103,7 +101,14 @@ async fn serve<P: Platform + Send + 'static>(
}
async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()> {
match LocalSocketListener::bind("@dioxusin") {
let metadata = cargo_metadata::MetadataCommand::new()
.no_deps()
.exec()
.unwrap();
let target_dir = metadata.target_directory.as_std_path();
let path = target_dir.join("dioxusin");
clear_paths(&path);
match LocalSocketListener::bind(path) {
Ok(local_socket_stream) => {
let aborted = Arc::new(Mutex::new(false));
// States
@@ -115,9 +120,9 @@ async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()
let file_map = hot_reload_state.file_map.clone();
let channels = channels.clone();
let aborted = aborted.clone();
let _ = local_socket_stream.set_nonblocking(true);
move || {
loop {
//accept() will block the thread when local_socket_stream is in blocking mode (default)
match local_socket_stream.accept() {
Ok(mut connection) => {
// send any templates than have changed before the socket connected
@@ -175,17 +180,14 @@ async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()
Ok(())
}
fn clear_paths() {
fn clear_paths(file_socket_path: &std::path::Path) {
if cfg!(target_os = "macos") {
// On unix, if you force quit the application, it can leave the file socket open
// This will cause the local socket listener to fail to open
// We check if the file socket is already open from an old session and then delete it
let paths = ["./dioxusin", "./@dioxusin"];
for path in paths {
let path = std::path::PathBuf::from(path);
if path.exists() {
let _ = std::fs::remove_file(path);
}
if file_socket_path.exists() {
let _ = std::fs::remove_file(file_socket_path);
}
}
}
+17 -7
View File
@@ -33,7 +33,7 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
.watcher
.watch_path
.clone()
.unwrap_or_else(|| vec![PathBuf::from("src")]);
.unwrap_or_else(|| vec![PathBuf::from("src"), PathBuf::from("examples")]);
let watcher_config = config.clone();
let mut watcher = notify::recommended_watcher(move |info: notify::Result<notify::Event>| {
@@ -56,6 +56,16 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
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);
@@ -122,12 +132,12 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
.unwrap();
for sub_path in allow_watch_path {
watcher
.watch(
&config.crate_dir.join(sub_path),
notify::RecursiveMode::Recursive,
)
.unwrap();
if let Err(err) = watcher.watch(
&config.crate_dir.join(sub_path),
notify::RecursiveMode::Recursive,
) {
log::error!("Failed to watch path: {}", err);
}
}
Ok(watcher)
}
+14 -11
View File
@@ -22,17 +22,20 @@ pub fn print_console_info(
options: PrettierOptions,
web_info: Option<WebServerInfo>,
) {
if let Ok(native_clearseq) = Command::new(if cfg!(target_os = "windows") {
"cls"
} else {
"clear"
})
.output()
{
print!("{}", String::from_utf8_lossy(&native_clearseq.stdout));
} else {
// Try ANSI-Escape characters
print!("\x1b[2J\x1b[H");
// Don't clear the screen if the user has set the DIOXUS_LOG environment variable to "trace" so that we can see the logs
if Some("trace") != std::env::var("DIOXUS_LOG").ok().as_deref() {
if let Ok(native_clearseq) = Command::new(if cfg!(target_os = "windows") {
"cls"
} else {
"clear"
})
.output()
{
print!("{}", String::from_utf8_lossy(&native_clearseq.stdout));
} else {
// Try ANSI-Escape characters
print!("\x1b[2J\x1b[H");
}
}
let mut profile = if config.release { "Release" } else { "Debug" }.to_string();