Merge branch 'master' into feat/inline-attributes-fmt
This commit is contained in:
285 files changed
+26437
-5759
No files matched your search
@@ -0,0 +1,60 @@
|
||||
use std::{fs::File, io::Write, path::PathBuf};
|
||||
|
||||
use crate::Result;
|
||||
use dioxus_cli_config::CrateConfig;
|
||||
use manganis_cli_support::{AssetManifest, AssetManifestExt};
|
||||
|
||||
pub fn asset_manifest(crate_config: &CrateConfig) -> AssetManifest {
|
||||
AssetManifest::load_from_path(
|
||||
crate_config.crate_dir.join("Cargo.toml"),
|
||||
crate_config.workspace_dir.join("Cargo.lock"),
|
||||
)
|
||||
}
|
||||
|
||||
/// Create a head file that contains all of the imports for assets that the user project uses
|
||||
pub fn create_assets_head(config: &CrateConfig) -> Result<()> {
|
||||
let manifest = asset_manifest(config);
|
||||
let mut file = File::create(config.out_dir.join("__assets_head.html"))?;
|
||||
file.write_all(manifest.head().as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Process any assets collected from the binary
|
||||
pub(crate) fn process_assets(config: &CrateConfig) -> anyhow::Result<()> {
|
||||
let manifest = asset_manifest(config);
|
||||
|
||||
let static_asset_output_dir = PathBuf::from(
|
||||
config
|
||||
.dioxus_config
|
||||
.web
|
||||
.app
|
||||
.base_path
|
||||
.clone()
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
let static_asset_output_dir = config.out_dir.join(static_asset_output_dir);
|
||||
|
||||
manifest.copy_static_assets_to(static_asset_output_dir)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A guard that sets up the environment for the web renderer to compile in. This guard sets the location that assets will be served from
|
||||
pub(crate) struct WebAssetConfigDropGuard;
|
||||
|
||||
impl WebAssetConfigDropGuard {
|
||||
pub fn new() -> Self {
|
||||
// Set up the collect asset config
|
||||
manganis_cli_support::Config::default()
|
||||
.with_assets_serve_location("/")
|
||||
.save();
|
||||
Self {}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WebAssetConfigDropGuard {
|
||||
fn drop(&mut self) {
|
||||
// Reset the config
|
||||
manganis_cli_support::Config::default().save();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// Dioxus-CLI
|
||||
// https://github.com/DioxusLabs/cli
|
||||
// https://github.com/DioxusLabs/dioxus/tree/master/packages/cli
|
||||
|
||||
(function () {
|
||||
var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
@@ -22,4 +22,4 @@
|
||||
}
|
||||
};
|
||||
ws.onclose = reload_upon_connect;
|
||||
})()
|
||||
})()
|
||||
+82
-50
@@ -1,11 +1,14 @@
|
||||
use crate::{
|
||||
config::{CrateConfig, ExecutableType},
|
||||
assets::{asset_manifest, create_assets_head, process_assets, WebAssetConfigDropGuard},
|
||||
error::{Error, Result},
|
||||
tools::Tool,
|
||||
DioxusConfig,
|
||||
};
|
||||
use cargo_metadata::{diagnostic::Diagnostic, Message};
|
||||
use dioxus_cli_config::crate_root;
|
||||
use dioxus_cli_config::CrateConfig;
|
||||
use dioxus_cli_config::ExecutableType;
|
||||
use indicatif::{ProgressBar, ProgressStyle};
|
||||
use lazy_static::lazy_static;
|
||||
use serde::Serialize;
|
||||
use std::{
|
||||
fs::{copy, create_dir_all, File},
|
||||
@@ -16,17 +19,20 @@ use std::{
|
||||
};
|
||||
use wasm_bindgen_cli_support::Bindgen;
|
||||
|
||||
lazy_static! {
|
||||
static ref PROGRESS_BARS: indicatif::MultiProgress = indicatif::MultiProgress::new();
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, Clone)]
|
||||
pub struct BuildResult {
|
||||
pub warnings: Vec<Diagnostic>,
|
||||
pub elapsed_time: u128,
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
|
||||
pub fn build(config: &CrateConfig, _: bool, skip_assets: bool) -> Result<BuildResult> {
|
||||
// [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
|
||||
// [3] Wasm-bindgen the .wasm fiile, and move it into the {builddir}/modules/xxxx/xxxx_bg.wasm
|
||||
// [3] Wasm-bindgen the .wasm file, and move it into the {builddir}/modules/xxxx/xxxx_bg.wasm
|
||||
// [4] Wasm-opt the .wasm file with whatever optimizations need to be done
|
||||
// [5][OPTIONAL] Builds the Tailwind CSS file using the Tailwind standalone binary
|
||||
// [6] Link up the html page to the wasm module
|
||||
@@ -41,10 +47,13 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
|
||||
..
|
||||
} = config;
|
||||
|
||||
let _gaurd = WebAssetConfigDropGuard::new();
|
||||
|
||||
// start to build the assets
|
||||
let ignore_files = build_assets(config)?;
|
||||
|
||||
let t_start = std::time::Instant::now();
|
||||
let _guard = dioxus_cli_config::__private::save_config(config);
|
||||
|
||||
// [1] Build the .wasm module
|
||||
log::info!("🚅 Running build command...");
|
||||
@@ -60,8 +69,8 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
|
||||
.output()?;
|
||||
}
|
||||
|
||||
let cmd = subprocess::Exec::cmd("cargo");
|
||||
let cmd = cmd
|
||||
let cmd = subprocess::Exec::cmd("cargo")
|
||||
.env("CARGO_TARGET_DIR", target_dir)
|
||||
.cwd(crate_dir)
|
||||
.arg("build")
|
||||
.arg("--target")
|
||||
@@ -93,6 +102,8 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
|
||||
cmd
|
||||
};
|
||||
|
||||
let cmd = cmd.args(&config.cargo_args);
|
||||
|
||||
let cmd = match executable {
|
||||
ExecutableType::Binary(name) => cmd.arg("--bin").arg(name),
|
||||
ExecutableType::Lib(name) => cmd.arg("--lib").arg(name),
|
||||
@@ -144,7 +155,7 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
|
||||
}
|
||||
|
||||
// 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") {
|
||||
let info = dioxus_tools.get("binaryen").unwrap();
|
||||
let binaryen = crate::tools::Tool::Binaryen;
|
||||
@@ -250,22 +261,31 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
|
||||
}
|
||||
}
|
||||
|
||||
if !skip_assets {
|
||||
process_assets(config)?;
|
||||
}
|
||||
|
||||
Ok(BuildResult {
|
||||
warnings: warning_messages,
|
||||
elapsed_time: t_start.elapsed().as_millis(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResult> {
|
||||
pub fn build_desktop(
|
||||
config: &CrateConfig,
|
||||
_is_serve: bool,
|
||||
skip_assets: bool,
|
||||
) -> Result<BuildResult> {
|
||||
log::info!("🚅 Running build [Desktop] command...");
|
||||
|
||||
let t_start = std::time::Instant::now();
|
||||
let ignore_files = build_assets(config)?;
|
||||
let _guard = dioxus_cli_config::__private::save_config(config);
|
||||
|
||||
let mut cmd = subprocess::Exec::cmd("cargo")
|
||||
.env("CARGO_TARGET_DIR", &config.target_dir)
|
||||
.cwd(&config.crate_dir)
|
||||
.arg("build")
|
||||
.arg("--quiet")
|
||||
.arg("--message-format=json");
|
||||
|
||||
if config.release {
|
||||
@@ -273,6 +293,8 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
|
||||
}
|
||||
if config.verbose {
|
||||
cmd = cmd.arg("--verbose");
|
||||
} else {
|
||||
cmd = cmd.arg("--quiet");
|
||||
}
|
||||
|
||||
if config.custom_profile.is_some() {
|
||||
@@ -285,10 +307,18 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
|
||||
cmd = cmd.arg("--features").arg(features_str);
|
||||
}
|
||||
|
||||
if let Some(target) = &config.target {
|
||||
cmd = cmd.arg("--target").arg(target);
|
||||
}
|
||||
|
||||
let target_platform = config.target.as_deref().unwrap_or("");
|
||||
|
||||
cmd = cmd.args(&config.cargo_args);
|
||||
|
||||
let cmd = match &config.executable {
|
||||
crate::ExecutableType::Binary(name) => cmd.arg("--bin").arg(name),
|
||||
crate::ExecutableType::Lib(name) => cmd.arg("--lib").arg(name),
|
||||
crate::ExecutableType::Example(name) => cmd.arg("--example").arg(name),
|
||||
ExecutableType::Binary(name) => cmd.arg("--bin").arg(name),
|
||||
ExecutableType::Lib(name) => cmd.arg("--lib").arg(name),
|
||||
ExecutableType::Example(name) => cmd.arg("--example").arg(name),
|
||||
};
|
||||
|
||||
let warning_messages = prettier_build(cmd)?;
|
||||
@@ -300,14 +330,19 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
|
||||
|
||||
let file_name: String;
|
||||
let mut res_path = match &config.executable {
|
||||
crate::ExecutableType::Binary(name) | crate::ExecutableType::Lib(name) => {
|
||||
file_name = name.clone();
|
||||
config.target_dir.join(release_type).join(name)
|
||||
}
|
||||
crate::ExecutableType::Example(name) => {
|
||||
ExecutableType::Binary(name) | ExecutableType::Lib(name) => {
|
||||
file_name = name.clone();
|
||||
config
|
||||
.target_dir
|
||||
.join(target_platform)
|
||||
.join(release_type)
|
||||
.join(name)
|
||||
}
|
||||
ExecutableType::Example(name) => {
|
||||
file_name = name.clone();
|
||||
config
|
||||
.target_dir
|
||||
.join(target_platform)
|
||||
.join(release_type)
|
||||
.join("examples")
|
||||
.join(name)
|
||||
@@ -359,15 +394,16 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
|
||||
}
|
||||
}
|
||||
|
||||
if !skip_assets {
|
||||
// Collect assets
|
||||
process_assets(config)?;
|
||||
// Create the __assets_head.html file for bundling
|
||||
create_assets_head(config)?;
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"🚩 Build completed: [./{}]",
|
||||
config
|
||||
.dioxus_config
|
||||
.application
|
||||
.out_dir
|
||||
.clone()
|
||||
.unwrap_or_else(|| PathBuf::from("dist"))
|
||||
.display()
|
||||
config.dioxus_config.application.out_dir.clone().display()
|
||||
);
|
||||
|
||||
println!("build desktop done");
|
||||
@@ -381,8 +417,9 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
|
||||
fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
|
||||
let mut warning_messages: Vec<Diagnostic> = vec![];
|
||||
|
||||
let pb = ProgressBar::new_spinner();
|
||||
let mut pb = ProgressBar::new_spinner();
|
||||
pb.enable_steady_tick(Duration::from_millis(200));
|
||||
pb = PROGRESS_BARS.add(pb);
|
||||
pb.set_style(
|
||||
ProgressStyle::with_template("{spinner:.dim.bold} {wide_msg}")
|
||||
.unwrap()
|
||||
@@ -390,14 +427,6 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
|
||||
);
|
||||
pb.set_message("💼 Waiting to start build the project...");
|
||||
|
||||
struct StopSpinOnDrop(ProgressBar);
|
||||
|
||||
impl Drop for StopSpinOnDrop {
|
||||
fn drop(&mut self) {
|
||||
self.0.finish_and_clear();
|
||||
}
|
||||
}
|
||||
|
||||
let stdout = cmd.detached().stream_stdout()?;
|
||||
let reader = std::io::BufReader::new(stdout);
|
||||
|
||||
@@ -433,14 +462,18 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
_ => (), // Unknown message
|
||||
_ => {
|
||||
// Unknown message
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(warning_messages)
|
||||
}
|
||||
|
||||
pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
|
||||
let crate_root = crate::cargo::crate_root().unwrap();
|
||||
pub fn gen_page(config: &CrateConfig, serve: bool, skip_assets: bool) -> String {
|
||||
let _gaurd = WebAssetConfigDropGuard::new();
|
||||
|
||||
let crate_root = crate_root().unwrap();
|
||||
let custom_html_file = crate_root.join("index.html");
|
||||
let mut html = if custom_html_file.is_file() {
|
||||
let mut buf = String::new();
|
||||
@@ -454,14 +487,14 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
|
||||
String::from(include_str!("./assets/index.html"))
|
||||
};
|
||||
|
||||
let resources = config.web.resource.clone();
|
||||
let resources = config.dioxus_config.web.resource.clone();
|
||||
|
||||
let mut style_list = resources.style.unwrap_or_default();
|
||||
let mut script_list = resources.script.unwrap_or_default();
|
||||
|
||||
if serve {
|
||||
let mut dev_style = resources.dev.style.clone().unwrap_or_default();
|
||||
let mut dev_script = resources.dev.script.unwrap_or_default();
|
||||
let mut dev_style = resources.dev.style.clone();
|
||||
let mut dev_script = resources.dev.script.clone();
|
||||
style_list.append(&mut dev_style);
|
||||
script_list.append(&mut dev_script);
|
||||
}
|
||||
@@ -474,14 +507,18 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
|
||||
))
|
||||
}
|
||||
if config
|
||||
.dioxus_config
|
||||
.application
|
||||
.tools
|
||||
.clone()
|
||||
.unwrap_or_default()
|
||||
.contains_key("tailwindcss")
|
||||
{
|
||||
style_str.push_str("<link rel=\"stylesheet\" href=\"/{base_path}/tailwind.css\">\n");
|
||||
}
|
||||
if !skip_assets {
|
||||
let manifest = asset_manifest(config);
|
||||
style_str.push_str(&manifest.head());
|
||||
}
|
||||
|
||||
replace_or_insert_before("{style_include}", &style_str, "</head", &mut html);
|
||||
|
||||
@@ -502,11 +539,11 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
|
||||
);
|
||||
}
|
||||
|
||||
let base_path = match &config.web.app.base_path {
|
||||
let base_path = match &config.dioxus_config.web.app.base_path {
|
||||
Some(path) => path,
|
||||
None => ".",
|
||||
};
|
||||
let app_name = &config.application.name;
|
||||
let app_name = &config.dioxus_config.application.name;
|
||||
// Check if a script already exists
|
||||
if html.contains("{app_name}") && html.contains("{base_path}") {
|
||||
html = html.replace("{app_name}", app_name);
|
||||
@@ -530,12 +567,7 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
|
||||
);
|
||||
}
|
||||
|
||||
let title = config
|
||||
.web
|
||||
.app
|
||||
.title
|
||||
.clone()
|
||||
.unwrap_or_else(|| "dioxus | ⛺".into());
|
||||
let title = config.dioxus_config.web.app.title.clone();
|
||||
|
||||
replace_or_insert_before("{app_title}", &title, "</title", &mut html);
|
||||
|
||||
@@ -562,7 +594,7 @@ fn build_assets(config: &CrateConfig) -> Result<Vec<PathBuf>> {
|
||||
let mut result = vec![];
|
||||
|
||||
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
|
||||
let sass = Tool::Sass;
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
//! Utilities for working with cargo and rust files
|
||||
use crate::error::{Error, Result};
|
||||
use std::{
|
||||
env, fs,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
str,
|
||||
};
|
||||
|
||||
/// How many parent folders are searched for a `Cargo.toml`
|
||||
const MAX_ANCESTORS: u32 = 10;
|
||||
|
||||
/// Some fields parsed from `cargo metadata` command
|
||||
pub struct Metadata {
|
||||
pub workspace_root: PathBuf,
|
||||
pub target_directory: PathBuf,
|
||||
}
|
||||
|
||||
/// Returns the root of the crate that the command is run from
|
||||
///
|
||||
/// If the command is run from the workspace root, this will return the top-level Cargo.toml
|
||||
pub fn crate_root() -> Result<PathBuf> {
|
||||
// From the current directory we work our way up, looking for `Cargo.toml`
|
||||
env::current_dir()
|
||||
.ok()
|
||||
.and_then(|mut wd| {
|
||||
for _ in 0..MAX_ANCESTORS {
|
||||
if contains_manifest(&wd) {
|
||||
return Some(wd);
|
||||
}
|
||||
if !wd.pop() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
Error::CargoError("Failed to find directory containing Cargo.toml".to_string())
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks if the directory contains `Cargo.toml`
|
||||
fn contains_manifest(path: &Path) -> bool {
|
||||
fs::read_dir(path)
|
||||
.map(|entries| {
|
||||
entries
|
||||
.filter_map(Result::ok)
|
||||
.any(|ent| &ent.file_name() == "Cargo.toml")
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
impl Metadata {
|
||||
/// Returns the struct filled from `cargo metadata` output
|
||||
/// TODO @Jon, find a different way that doesn't rely on the cargo metadata command (it's slow)
|
||||
pub fn get() -> Result<Self> {
|
||||
let output = Command::new("cargo")
|
||||
.args(["metadata"])
|
||||
.output()
|
||||
.map_err(|_| Error::CargoError("Manifset".to_string()))?;
|
||||
|
||||
if !output.status.success() {
|
||||
let mut msg = str::from_utf8(&output.stderr).unwrap().trim();
|
||||
if msg.starts_with("error: ") {
|
||||
msg = &msg[7..];
|
||||
}
|
||||
|
||||
return Err(Error::CargoError(msg.to_string()));
|
||||
}
|
||||
|
||||
let stdout = str::from_utf8(&output.stdout).unwrap();
|
||||
if let Some(line) = stdout.lines().next() {
|
||||
let meta: serde_json::Value = serde_json::from_str(line)
|
||||
.map_err(|_| Error::CargoError("InvalidOutput".to_string()))?;
|
||||
|
||||
let workspace_root = meta["workspace_root"]
|
||||
.as_str()
|
||||
.ok_or_else(|| Error::CargoError("InvalidOutput".to_string()))?
|
||||
.into();
|
||||
|
||||
let target_directory = meta["target_directory"]
|
||||
.as_str()
|
||||
.ok_or_else(|| Error::CargoError("InvalidOutput".to_string()))?
|
||||
.into();
|
||||
|
||||
return Ok(Self {
|
||||
workspace_root,
|
||||
target_directory,
|
||||
});
|
||||
}
|
||||
|
||||
Err(Error::CargoError("InvalidOutput".to_string()))
|
||||
}
|
||||
}
|
||||
@@ -31,15 +31,23 @@ pub struct Autoformat {
|
||||
impl Autoformat {
|
||||
// Todo: autoformat the entire crate
|
||||
pub async fn autoformat(self) -> Result<()> {
|
||||
let Autoformat {
|
||||
check,
|
||||
raw,
|
||||
file,
|
||||
split_line_attributes,
|
||||
..
|
||||
} = self;
|
||||
|
||||
// Default to formatting the project
|
||||
if self.raw.is_none() && self.file.is_none() {
|
||||
if let Err(e) = autoformat_project(self.check, self.split_line_attributes).await {
|
||||
if raw.is_none() && file.is_none() {
|
||||
if let Err(e) = autoformat_project(check, split_line_attributes).await {
|
||||
eprintln!("error formatting project: {}", e);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(raw) = self.raw {
|
||||
if let Some(raw) = raw {
|
||||
let indent = indentation_for(".", self.split_line_attributes)?;
|
||||
if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0, indent) {
|
||||
println!("{}", inner);
|
||||
@@ -51,57 +59,99 @@ impl Autoformat {
|
||||
}
|
||||
|
||||
// Format single file
|
||||
if let Some(file) = self.file {
|
||||
let file_content;
|
||||
let indent;
|
||||
if file == "-" {
|
||||
indent = indentation_for(".", self.split_line_attributes)?;
|
||||
let mut contents = String::new();
|
||||
std::io::stdin().read_to_string(&mut contents)?;
|
||||
file_content = Ok(contents);
|
||||
} else {
|
||||
indent = indentation_for(".", self.split_line_attributes)?;
|
||||
file_content = fs::read_to_string(&file);
|
||||
};
|
||||
|
||||
match file_content {
|
||||
Ok(s) => {
|
||||
let edits = dioxus_autofmt::fmt_file(&s, indent);
|
||||
let out = dioxus_autofmt::apply_formats(&s, edits);
|
||||
if file == "-" {
|
||||
print!("{}", out);
|
||||
} else {
|
||||
match fs::write(&file, out) {
|
||||
Ok(_) => {
|
||||
println!("formatted {}", file);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("failed to write formatted content to file: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("failed to open file: {}", e);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
if let Some(file) = file {
|
||||
refactor_file(file, split_line_attributes)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn refactor_file(file: String, split_line_attributes: bool) -> Result<(), Error> {
|
||||
let indent = indentation_for(".", split_line_attributes)?;
|
||||
let file_content = if file == "-" {
|
||||
let mut contents = String::new();
|
||||
std::io::stdin().read_to_string(&mut contents)?;
|
||||
Ok(contents)
|
||||
} else {
|
||||
fs::read_to_string(&file)
|
||||
};
|
||||
let Ok(s) = file_content else {
|
||||
eprintln!("failed to open file: {}", file_content.unwrap_err());
|
||||
exit(1);
|
||||
};
|
||||
let edits = dioxus_autofmt::fmt_file(&s, indent);
|
||||
let out = dioxus_autofmt::apply_formats(&s, edits);
|
||||
|
||||
if file == "-" {
|
||||
print!("{}", out);
|
||||
} else if let Err(e) = fs::write(&file, out) {
|
||||
eprintln!("failed to write formatted content to file: {e}",);
|
||||
} else {
|
||||
println!("formatted {}", file);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_project_files(config: &CrateConfig) -> Vec<PathBuf> {
|
||||
let mut files = vec![];
|
||||
|
||||
let gitignore_path = config.crate_dir.join(".gitignore");
|
||||
if gitignore_path.is_file() {
|
||||
let gitigno = gitignore::File::new(gitignore_path.as_path()).unwrap();
|
||||
if let Ok(git_files) = gitigno.included_files() {
|
||||
let git_files = git_files
|
||||
.into_iter()
|
||||
.filter(|f| f.ends_with(".rs") && !is_target_dir(f));
|
||||
files.extend(git_files)
|
||||
};
|
||||
} else {
|
||||
collect_rs_files(&config.crate_dir, &mut files);
|
||||
}
|
||||
|
||||
files
|
||||
}
|
||||
|
||||
fn is_target_dir(file: &Path) -> bool {
|
||||
let stripped = if let Ok(cwd) = std::env::current_dir() {
|
||||
file.strip_prefix(cwd).unwrap_or(file)
|
||||
} else {
|
||||
file
|
||||
};
|
||||
if let Some(first) = stripped.components().next() {
|
||||
first.as_os_str() == "target"
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
async fn format_file(
|
||||
path: impl AsRef<Path>,
|
||||
indent: IndentOptions,
|
||||
) -> Result<usize, tokio::io::Error> {
|
||||
let contents = tokio::fs::read_to_string(&path).await?;
|
||||
|
||||
let edits = dioxus_autofmt::fmt_file(&contents, indent);
|
||||
let len = edits.len();
|
||||
|
||||
if !edits.is_empty() {
|
||||
let out = dioxus_autofmt::apply_formats(&contents, edits);
|
||||
tokio::fs::write(path, out).await?;
|
||||
}
|
||||
|
||||
Ok(len)
|
||||
}
|
||||
|
||||
/// Read every .rs file accessible when considering the .gitignore and try to format it
|
||||
///
|
||||
/// Runs using Tokio for multithreading, so it should be really really fast
|
||||
///
|
||||
/// Doesn't do mod-descending, so it will still try to format unreachable files. TODO.
|
||||
async fn autoformat_project(check: bool, split_line_attributes: bool) -> Result<()> {
|
||||
let crate_config = crate::CrateConfig::new(None)?;
|
||||
let crate_config = dioxus_cli_config::CrateConfig::new(None)?;
|
||||
|
||||
let mut files_to_format = vec![];
|
||||
collect_rs_files(&crate_config.crate_dir, &mut files_to_format);
|
||||
let files_to_format = get_project_files(&crate_config);
|
||||
|
||||
if files_to_format.is_empty() {
|
||||
return Ok(());
|
||||
@@ -111,38 +161,17 @@ async fn autoformat_project(check: bool, split_line_attributes: bool) -> Result<
|
||||
|
||||
let counts = files_to_format
|
||||
.into_iter()
|
||||
.filter(|file| {
|
||||
if file.components().any(|f| f.as_os_str() == "target") {
|
||||
return false;
|
||||
}
|
||||
|
||||
true
|
||||
})
|
||||
.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, _indent.clone());
|
||||
let len = edits.len();
|
||||
|
||||
if !edits.is_empty() {
|
||||
let out = dioxus_autofmt::apply_formats(&contents, edits);
|
||||
tokio::fs::write(&path, out).await?;
|
||||
}
|
||||
|
||||
Ok(len) as Result<usize, tokio::io::Error>
|
||||
})
|
||||
.await;
|
||||
let path_clone = path.clone();
|
||||
let res = tokio::spawn(format_file(path, indent.clone())).await;
|
||||
|
||||
match res {
|
||||
Err(err) => {
|
||||
eprintln!("error formatting file: {}\n{err}", _path.display());
|
||||
eprintln!("error formatting file: {}\n{err}", path_clone.display());
|
||||
None
|
||||
}
|
||||
Ok(Err(err)) => {
|
||||
eprintln!("error formatting file: {}\n{err}", _path.display());
|
||||
eprintln!("error formatting file: {}\n{err}", path_clone.display());
|
||||
None
|
||||
}
|
||||
Ok(Ok(res)) => Some(res),
|
||||
@@ -152,13 +181,7 @@ async fn autoformat_project(check: bool, split_line_attributes: bool) -> Result<
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
|
||||
let files_formatted: usize = counts
|
||||
.into_iter()
|
||||
.map(|f| match f {
|
||||
Some(res) => res,
|
||||
_ => 0,
|
||||
})
|
||||
.sum();
|
||||
let files_formatted: usize = counts.into_iter().flatten().sum();
|
||||
|
||||
if files_formatted > 0 && check {
|
||||
eprintln!("{} files needed formatting", files_formatted);
|
||||
@@ -215,26 +238,24 @@ fn indentation_for(
|
||||
))
|
||||
}
|
||||
|
||||
fn collect_rs_files(folder: &Path, files: &mut Vec<PathBuf>) {
|
||||
let Ok(folder) = folder.read_dir() else {
|
||||
fn collect_rs_files(folder: &impl AsRef<Path>, files: &mut Vec<PathBuf>) {
|
||||
if is_target_dir(folder.as_ref()) {
|
||||
return;
|
||||
}
|
||||
let Ok(folder) = folder.as_ref().read_dir() else {
|
||||
return;
|
||||
};
|
||||
|
||||
// load the gitignore
|
||||
|
||||
for entry in folder {
|
||||
let Ok(entry) = entry else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let path = entry.path();
|
||||
|
||||
if path.is_dir() {
|
||||
collect_rs_files(&path, files);
|
||||
}
|
||||
|
||||
if let Some(ext) = path.extension() {
|
||||
if ext == "rs" {
|
||||
if ext == "rs" && !is_target_dir(&path) {
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
use crate::cfg::Platform;
|
||||
use crate::assets::WebAssetConfigDropGuard;
|
||||
#[cfg(feature = "plugin")]
|
||||
use crate::plugin::PluginManager;
|
||||
use crate::server::fullstack::FullstackServerEnvGuard;
|
||||
use crate::server::fullstack::FullstackWebEnvGuard;
|
||||
use dioxus_cli_config::Platform;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -13,23 +16,26 @@ pub struct Build {
|
||||
}
|
||||
|
||||
impl Build {
|
||||
pub fn build(self, bin: Option<PathBuf>) -> Result<()> {
|
||||
let mut crate_config = crate::CrateConfig::new(bin)?;
|
||||
pub fn build(self, bin: Option<PathBuf>, target_dir: Option<&std::path::Path>) -> Result<()> {
|
||||
let mut crate_config = dioxus_cli_config::CrateConfig::new(bin)?;
|
||||
if let Some(target_dir) = target_dir {
|
||||
crate_config.target_dir = target_dir.to_path_buf();
|
||||
}
|
||||
|
||||
// change the release state.
|
||||
crate_config.with_release(self.build.release);
|
||||
crate_config.with_verbose(self.build.verbose);
|
||||
|
||||
if self.build.example.is_some() {
|
||||
crate_config.as_example(self.build.example.unwrap());
|
||||
crate_config.as_example(self.build.example.clone().unwrap());
|
||||
}
|
||||
|
||||
if self.build.profile.is_some() {
|
||||
crate_config.set_profile(self.build.profile.unwrap());
|
||||
crate_config.set_profile(self.build.profile.clone().unwrap());
|
||||
}
|
||||
|
||||
if self.build.features.is_some() {
|
||||
crate_config.set_features(self.build.features.unwrap());
|
||||
crate_config.set_features(self.build.features.clone().unwrap());
|
||||
}
|
||||
|
||||
let platform = self
|
||||
@@ -37,31 +43,61 @@ impl Build {
|
||||
.platform
|
||||
.unwrap_or(crate_config.dioxus_config.application.default_platform);
|
||||
|
||||
if let Some(target) = self.build.target.clone() {
|
||||
crate_config.set_target(target);
|
||||
}
|
||||
|
||||
crate_config.set_cargo_args(self.build.cargo_args.clone());
|
||||
|
||||
// #[cfg(feature = "plugin")]
|
||||
// let _ = PluginManager::on_build_start(&crate_config, &platform);
|
||||
|
||||
match platform {
|
||||
Platform::Web => {
|
||||
crate::builder::build(&crate_config, true)?;
|
||||
crate::builder::build(&crate_config, false, self.build.skip_assets)?;
|
||||
}
|
||||
Platform::Desktop => {
|
||||
crate::builder::build_desktop(&crate_config, false)?;
|
||||
crate::builder::build_desktop(&crate_config, false, self.build.skip_assets)?;
|
||||
}
|
||||
Platform::Fullstack => {
|
||||
// Fullstack mode must be built with web configs on the desktop (server) binary as well as the web binary
|
||||
let _config = WebAssetConfigDropGuard::new();
|
||||
{
|
||||
let mut web_config = crate_config.clone();
|
||||
let _gaurd = FullstackWebEnvGuard::new(&self.build);
|
||||
let web_feature = self.build.client_feature;
|
||||
let features = &mut web_config.features;
|
||||
match features {
|
||||
Some(features) => {
|
||||
features.push(web_feature);
|
||||
}
|
||||
None => web_config.features = Some(vec![web_feature]),
|
||||
};
|
||||
crate::builder::build(&crate_config, false, self.build.skip_assets)?;
|
||||
}
|
||||
{
|
||||
let mut desktop_config = crate_config.clone();
|
||||
let desktop_feature = self.build.server_feature;
|
||||
let features = &mut desktop_config.features;
|
||||
match features {
|
||||
Some(features) => {
|
||||
features.push(desktop_feature);
|
||||
}
|
||||
None => desktop_config.features = Some(vec![desktop_feature]),
|
||||
};
|
||||
let _gaurd =
|
||||
FullstackServerEnvGuard::new(self.build.force_debug, self.build.release);
|
||||
crate::builder::build_desktop(&desktop_config, false, self.build.skip_assets)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let temp = gen_page(&crate_config.dioxus_config, false);
|
||||
let temp = gen_page(&crate_config, false, self.build.skip_assets);
|
||||
|
||||
let mut file = std::fs::File::create(
|
||||
crate_config
|
||||
.crate_dir
|
||||
.join(
|
||||
crate_config
|
||||
.dioxus_config
|
||||
.application
|
||||
.out_dir
|
||||
.clone()
|
||||
.unwrap_or_else(|| PathBuf::from("dist")),
|
||||
)
|
||||
.join(crate_config.dioxus_config.application.out_dir.clone())
|
||||
.join("index.html"),
|
||||
)?;
|
||||
file.write_all(temp.as_bytes())?;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use core::panic;
|
||||
use dioxus_cli_config::ExecutableType;
|
||||
use std::{fs::create_dir_all, str::FromStr};
|
||||
|
||||
use tauri_bundler::{BundleSettings, PackageSettings, SettingsBuilder};
|
||||
@@ -62,7 +63,7 @@ impl From<PackageType> for tauri_bundler::PackageType {
|
||||
|
||||
impl Bundle {
|
||||
pub fn bundle(self, bin: Option<PathBuf>) -> Result<()> {
|
||||
let mut crate_config = crate::CrateConfig::new(bin)?;
|
||||
let mut crate_config = dioxus_cli_config::CrateConfig::new(bin)?;
|
||||
|
||||
// change the release state.
|
||||
crate_config.with_release(self.build.release);
|
||||
@@ -76,16 +77,22 @@ impl Bundle {
|
||||
crate_config.set_profile(self.build.profile.unwrap());
|
||||
}
|
||||
|
||||
if let Some(target) = &self.build.target {
|
||||
crate_config.set_target(target.to_string());
|
||||
}
|
||||
|
||||
crate_config.set_cargo_args(self.build.cargo_args);
|
||||
|
||||
// build the desktop app
|
||||
build_desktop(&crate_config, false)?;
|
||||
build_desktop(&crate_config, false, false)?;
|
||||
|
||||
// copy the binary to the out dir
|
||||
let package = crate_config.manifest.package.unwrap();
|
||||
|
||||
let mut name: PathBuf = match &crate_config.executable {
|
||||
crate::ExecutableType::Binary(name)
|
||||
| crate::ExecutableType::Lib(name)
|
||||
| crate::ExecutableType::Example(name) => name,
|
||||
ExecutableType::Binary(name)
|
||||
| ExecutableType::Lib(name)
|
||||
| ExecutableType::Example(name) => name,
|
||||
}
|
||||
.into();
|
||||
if cfg!(windows) {
|
||||
@@ -128,6 +135,20 @@ impl Bundle {
|
||||
}
|
||||
}
|
||||
|
||||
// Add all assets from collect assets to the bundle
|
||||
#[cfg(feature = "collect-assets")]
|
||||
{
|
||||
let config = manganis_cli_support::Config::current();
|
||||
let location = config.assets_serve_location().to_string();
|
||||
let location = format!("./{}", location);
|
||||
println!("Adding assets from {} to bundle", location);
|
||||
if let Some(resources) = &mut bundle_settings.resources {
|
||||
resources.push(location);
|
||||
} else {
|
||||
bundle_settings.resources = Some(vec![location]);
|
||||
}
|
||||
}
|
||||
|
||||
let mut settings = SettingsBuilder::new()
|
||||
.project_out_directory(crate_config.out_dir)
|
||||
.package_settings(PackageSettings {
|
||||
@@ -148,6 +169,11 @@ impl Bundle {
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(target) = &self.build.target {
|
||||
settings = settings.target(target.to_string());
|
||||
}
|
||||
|
||||
let settings = settings.build();
|
||||
|
||||
// on macos we need to set CI=true (https://github.com/tauri-apps/tauri/issues/2567)
|
||||
@@ -156,9 +182,9 @@ impl Bundle {
|
||||
|
||||
tauri_bundler::bundle::bundle_project(settings.unwrap()).unwrap_or_else(|err|{
|
||||
#[cfg(target_os = "macos")]
|
||||
panic!("Failed to bundle project: {}\nMake sure you have automation enabled in your terminal (https://github.com/tauri-apps/tauri/issues/3055#issuecomment-1624389208) and full disk access enabled for your terminal (https://github.com/tauri-apps/tauri/issues/3055#issuecomment-1624389208)", err);
|
||||
panic!("Failed to bundle project: {:#?}\nMake sure you have automation enabled in your terminal (https://github.com/tauri-apps/tauri/issues/3055#issuecomment-1624389208) and full disk access enabled for your terminal (https://github.com/tauri-apps/tauri/issues/3055#issuecomment-1624389208)", err);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
panic!("Failed to bundle project: {}", err);
|
||||
panic!("Failed to bundle project: {:#?}", err);
|
||||
});
|
||||
|
||||
Ok(())
|
||||
|
||||
+80
-20
@@ -1,20 +1,20 @@
|
||||
use clap::ValueEnum;
|
||||
use serde::Serialize;
|
||||
use dioxus_cli_config::Platform;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Config options for the build system.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Parser)]
|
||||
pub struct ConfigOptsBuild {
|
||||
/// The index HTML file to drive the bundling process [default: index.html]
|
||||
#[arg(long)]
|
||||
pub target: Option<PathBuf>,
|
||||
|
||||
/// Build in release mode [default: false]
|
||||
#[clap(long)]
|
||||
#[serde(default)]
|
||||
pub release: bool,
|
||||
|
||||
/// This flag only applies to fullstack builds. By default fullstack builds will run with something in between debug and release mode. This flag will force the build to run in debug mode. [default: false]
|
||||
#[clap(long)]
|
||||
#[serde(default)]
|
||||
pub force_debug: bool,
|
||||
|
||||
// Use verbose output [default: false]
|
||||
#[clap(long)]
|
||||
#[serde(default)]
|
||||
@@ -32,17 +32,53 @@ pub struct ConfigOptsBuild {
|
||||
#[clap(long, value_enum)]
|
||||
pub platform: Option<Platform>,
|
||||
|
||||
/// Skip collecting assets from dependencies [default: false]
|
||||
#[clap(long)]
|
||||
#[serde(default)]
|
||||
pub skip_assets: bool,
|
||||
|
||||
/// Space separated list of features to activate
|
||||
#[clap(long)]
|
||||
pub features: Option<Vec<String>>,
|
||||
|
||||
/// The feature to use for the client in a fullstack app [default: "web"]
|
||||
#[clap(long, default_value_t = { "web".to_string() })]
|
||||
pub client_feature: String,
|
||||
|
||||
/// The feature to use for the server in a fullstack app [default: "ssr"]
|
||||
#[clap(long, default_value_t = { "ssr".to_string() })]
|
||||
pub server_feature: String,
|
||||
|
||||
/// Rustc platform triple
|
||||
#[clap(long)]
|
||||
pub target: Option<String>,
|
||||
|
||||
/// Extra arguments passed to cargo build
|
||||
#[clap(last = true)]
|
||||
pub cargo_args: Vec<String>,
|
||||
}
|
||||
|
||||
impl From<ConfigOptsServe> for ConfigOptsBuild {
|
||||
fn from(serve: ConfigOptsServe) -> Self {
|
||||
Self {
|
||||
target: serve.target,
|
||||
release: serve.release,
|
||||
verbose: serve.verbose,
|
||||
example: serve.example,
|
||||
profile: serve.profile,
|
||||
platform: serve.platform,
|
||||
features: serve.features,
|
||||
client_feature: serve.client_feature,
|
||||
server_feature: serve.server_feature,
|
||||
skip_assets: serve.skip_assets,
|
||||
force_debug: serve.force_debug,
|
||||
cargo_args: serve.cargo_args,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Parser)]
|
||||
pub struct ConfigOptsServe {
|
||||
/// The index HTML file to drive the bundling process [default: index.html]
|
||||
#[arg(short, long)]
|
||||
pub target: Option<PathBuf>,
|
||||
|
||||
/// Port of dev server
|
||||
#[clap(long)]
|
||||
#[clap(default_value_t = 8080)]
|
||||
@@ -62,6 +98,11 @@ pub struct ConfigOptsServe {
|
||||
#[serde(default)]
|
||||
pub release: bool,
|
||||
|
||||
/// This flag only applies to fullstack builds. By default fullstack builds will run with something in between debug and release mode. This flag will force the build to run in debug mode. [default: false]
|
||||
#[clap(long)]
|
||||
#[serde(default)]
|
||||
pub force_debug: bool,
|
||||
|
||||
// Use verbose output [default: false]
|
||||
#[clap(long)]
|
||||
#[serde(default)]
|
||||
@@ -71,7 +112,7 @@ pub struct ConfigOptsServe {
|
||||
#[clap(long)]
|
||||
pub profile: Option<String>,
|
||||
|
||||
/// Build platform: support Web & Desktop [default: "default_platform"]
|
||||
/// Build platform: support Web, Desktop, and Fullstack [default: "default_platform"]
|
||||
#[clap(long, value_enum)]
|
||||
pub platform: Option<Platform>,
|
||||
|
||||
@@ -89,16 +130,27 @@ pub struct ConfigOptsServe {
|
||||
/// Space separated list of features to activate
|
||||
#[clap(long)]
|
||||
pub features: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize, Debug)]
|
||||
pub enum Platform {
|
||||
#[clap(name = "web")]
|
||||
#[serde(rename = "web")]
|
||||
Web,
|
||||
#[clap(name = "desktop")]
|
||||
#[serde(rename = "desktop")]
|
||||
Desktop,
|
||||
/// Skip collecting assets from dependencies [default: false]
|
||||
#[clap(long)]
|
||||
#[serde(default)]
|
||||
pub skip_assets: bool,
|
||||
|
||||
/// The feature to use for the client in a fullstack app [default: "web"]
|
||||
#[clap(long, default_value_t = { "web".to_string() })]
|
||||
pub client_feature: String,
|
||||
|
||||
/// The feature to use for the server in a fullstack app [default: "ssr"]
|
||||
#[clap(long, default_value_t = { "ssr".to_string() })]
|
||||
pub server_feature: String,
|
||||
|
||||
/// Rustc platform triple
|
||||
#[clap(long)]
|
||||
pub target: Option<String>,
|
||||
|
||||
/// Extra arguments passed to cargo build
|
||||
#[clap(last = true)]
|
||||
pub cargo_args: Vec<String>,
|
||||
}
|
||||
|
||||
/// Config options for the bundling system.
|
||||
@@ -129,4 +181,12 @@ pub struct ConfigOptsBundle {
|
||||
/// Space separated list of features to activate
|
||||
#[clap(long)]
|
||||
pub features: Option<Vec<String>>,
|
||||
|
||||
/// Rustc platform triple
|
||||
#[clap(long)]
|
||||
pub target: Option<String>,
|
||||
|
||||
/// Extra arguments passed to cargo build
|
||||
#[clap(last = true)]
|
||||
pub cargo_args: Vec<String>,
|
||||
}
|
||||
@@ -47,7 +47,7 @@ async fn check_file_and_report(path: PathBuf) -> Result<()> {
|
||||
///
|
||||
/// Doesn't do mod-descending, so it will still try to check unreachable files. TODO.
|
||||
async fn check_project_and_report() -> Result<()> {
|
||||
let crate_config = crate::CrateConfig::new(None)?;
|
||||
let crate_config = dioxus_cli_config::CrateConfig::new(None)?;
|
||||
|
||||
let mut files_to_check = vec![];
|
||||
collect_rs_files(&crate_config.crate_dir, &mut files_to_check);
|
||||
|
||||
@@ -7,7 +7,7 @@ pub struct Clean {}
|
||||
|
||||
impl Clean {
|
||||
pub fn clean(self, bin: Option<PathBuf>) -> Result<()> {
|
||||
let crate_config = crate::CrateConfig::new(bin)?;
|
||||
let crate_config = dioxus_cli_config::CrateConfig::new(bin)?;
|
||||
|
||||
let output = Command::new("cargo")
|
||||
.arg("clean")
|
||||
@@ -19,15 +19,17 @@ impl Clean {
|
||||
return custom_error!("Cargo clean failed.");
|
||||
}
|
||||
|
||||
let out_dir = crate_config
|
||||
.dioxus_config
|
||||
.application
|
||||
.out_dir
|
||||
.unwrap_or_else(|| PathBuf::from("dist"));
|
||||
let out_dir = crate_config.dioxus_config.application.out_dir;
|
||||
if crate_config.crate_dir.join(&out_dir).is_dir() {
|
||||
remove_dir_all(crate_config.crate_dir.join(&out_dir))?;
|
||||
}
|
||||
|
||||
let fullstack_out_dir = crate_config.crate_dir.join(".dioxus");
|
||||
|
||||
if fullstack_out_dir.is_dir() {
|
||||
remove_dir_all(fullstack_out_dir)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
use dioxus_cli_config::crate_root;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Dioxus config file controls
|
||||
@@ -26,7 +28,7 @@ pub enum Config {
|
||||
|
||||
impl Config {
|
||||
pub fn config(self) -> Result<()> {
|
||||
let crate_root = crate::cargo::crate_root()?;
|
||||
let crate_root = crate_root()?;
|
||||
match self {
|
||||
Config::Init {
|
||||
name,
|
||||
@@ -48,7 +50,10 @@ impl Config {
|
||||
log::info!("🚩 Init config file completed.");
|
||||
}
|
||||
Config::FormatPrint {} => {
|
||||
println!("{:#?}", crate::CrateConfig::new(None)?.dioxus_config);
|
||||
println!(
|
||||
"{:#?}",
|
||||
dioxus_cli_config::CrateConfig::new(None)?.dioxus_config
|
||||
);
|
||||
}
|
||||
Config::CustomHtml {} => {
|
||||
let html_path = crate_root.join("index.html");
|
||||
|
||||
@@ -15,9 +15,10 @@ use crate::{
|
||||
cfg::{ConfigOptsBuild, ConfigOptsServe},
|
||||
custom_error,
|
||||
error::Result,
|
||||
gen_page, server, CrateConfig, Error,
|
||||
gen_page, server, Error,
|
||||
};
|
||||
use clap::{Parser, Subcommand};
|
||||
use dioxus_cli_config::CrateConfig;
|
||||
use html_parser::Dom;
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use dioxus_cli_config::Platform;
|
||||
|
||||
use super::*;
|
||||
use std::{fs::create_dir_all, io::Write, path::PathBuf};
|
||||
|
||||
@@ -11,7 +13,8 @@ pub struct Serve {
|
||||
|
||||
impl Serve {
|
||||
pub async fn serve(self, bin: Option<PathBuf>) -> Result<()> {
|
||||
let mut crate_config = crate::CrateConfig::new(bin)?;
|
||||
let mut crate_config = dioxus_cli_config::CrateConfig::new(bin)?;
|
||||
let serve_cfg = self.serve.clone();
|
||||
|
||||
// change the relase state.
|
||||
crate_config.with_hot_reload(self.serve.hot_reload);
|
||||
@@ -31,8 +34,11 @@ impl Serve {
|
||||
crate_config.set_features(self.serve.features.unwrap());
|
||||
}
|
||||
|
||||
// Subdirectories don't work with the server
|
||||
crate_config.dioxus_config.web.app.base_path = None;
|
||||
if let Some(target) = self.serve.target {
|
||||
crate_config.set_target(target);
|
||||
}
|
||||
|
||||
crate_config.set_cargo_args(self.serve.cargo_args);
|
||||
|
||||
let platform = self
|
||||
.serve
|
||||
@@ -40,32 +46,35 @@ impl Serve {
|
||||
.unwrap_or(crate_config.dioxus_config.application.default_platform);
|
||||
|
||||
match platform {
|
||||
cfg::Platform::Web => {
|
||||
Platform::Web => {
|
||||
// generate dev-index page
|
||||
Serve::regen_dev_page(&crate_config)?;
|
||||
Serve::regen_dev_page(&crate_config, self.serve.skip_assets)?;
|
||||
|
||||
// start the develop server
|
||||
server::web::startup(self.serve.port, crate_config.clone(), self.serve.open)
|
||||
.await?;
|
||||
server::web::startup(
|
||||
self.serve.port,
|
||||
crate_config.clone(),
|
||||
self.serve.open,
|
||||
self.serve.skip_assets,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
cfg::Platform::Desktop => {
|
||||
server::desktop::startup(crate_config.clone()).await?;
|
||||
Platform::Desktop => {
|
||||
server::desktop::startup(crate_config.clone(), &serve_cfg).await?;
|
||||
}
|
||||
Platform::Fullstack => {
|
||||
server::fullstack::startup(crate_config.clone(), &serve_cfg).await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn regen_dev_page(crate_config: &CrateConfig) -> Result<()> {
|
||||
let serve_html = gen_page(&crate_config.dioxus_config, true);
|
||||
pub fn regen_dev_page(crate_config: &CrateConfig, skip_assets: bool) -> Result<()> {
|
||||
let serve_html = gen_page(crate_config, true, skip_assets);
|
||||
|
||||
let dist_path = crate_config.crate_dir.join(
|
||||
crate_config
|
||||
.dioxus_config
|
||||
.application
|
||||
.out_dir
|
||||
.clone()
|
||||
.unwrap_or_else(|| PathBuf::from("dist")),
|
||||
);
|
||||
let dist_path = crate_config
|
||||
.crate_dir
|
||||
.join(crate_config.dioxus_config.application.out_dir.clone());
|
||||
if !dist_path.is_dir() {
|
||||
create_dir_all(&dist_path)?;
|
||||
}
|
||||
|
||||
@@ -1,582 +0,0 @@
|
||||
use crate::{cfg::Platform, error::Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DioxusConfig {
|
||||
pub application: ApplicationConfig,
|
||||
|
||||
pub web: WebConfig,
|
||||
|
||||
#[serde(default)]
|
||||
pub bundle: BundleConfig,
|
||||
|
||||
#[serde(default = "default_plugin")]
|
||||
pub plugin: toml::Value,
|
||||
}
|
||||
|
||||
fn default_plugin() -> toml::Value {
|
||||
toml::Value::Boolean(true)
|
||||
}
|
||||
|
||||
impl DioxusConfig {
|
||||
pub fn load(bin: Option<PathBuf>) -> crate::error::Result<Option<DioxusConfig>> {
|
||||
let crate_dir = crate::cargo::crate_root();
|
||||
|
||||
let crate_dir = match crate_dir {
|
||||
Ok(dir) => {
|
||||
if let Some(bin) = bin {
|
||||
dir.join(bin)
|
||||
} else {
|
||||
dir
|
||||
}
|
||||
}
|
||||
Err(_) => return Ok(None),
|
||||
};
|
||||
let crate_dir = crate_dir.as_path();
|
||||
|
||||
let Some(dioxus_conf_file) = acquire_dioxus_toml(crate_dir) else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let dioxus_conf_file = dioxus_conf_file.as_path();
|
||||
let cfg = toml::from_str::<DioxusConfig>(&std::fs::read_to_string(dioxus_conf_file)?)
|
||||
.map_err(|err| {
|
||||
let error_location = dioxus_conf_file
|
||||
.strip_prefix(crate_dir)
|
||||
.unwrap_or(dioxus_conf_file)
|
||||
.display();
|
||||
crate::Error::Unique(format!("{error_location} {err}"))
|
||||
})
|
||||
.map(Some);
|
||||
match cfg {
|
||||
Ok(Some(mut cfg)) => {
|
||||
let name = cfg.application.name.clone();
|
||||
if cfg.bundle.identifier.is_none() {
|
||||
cfg.bundle.identifier = Some(format!("io.github.{name}"));
|
||||
}
|
||||
if cfg.bundle.publisher.is_none() {
|
||||
cfg.bundle.publisher = Some(name);
|
||||
}
|
||||
Ok(Some(cfg))
|
||||
}
|
||||
cfg => cfg,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn acquire_dioxus_toml(dir: &Path) -> Option<PathBuf> {
|
||||
// prefer uppercase
|
||||
let uppercase_conf = dir.join("Dioxus.toml");
|
||||
if uppercase_conf.is_file() {
|
||||
return Some(uppercase_conf);
|
||||
}
|
||||
|
||||
// lowercase is fine too
|
||||
let lowercase_conf = dir.join("dioxus.toml");
|
||||
if lowercase_conf.is_file() {
|
||||
return Some(lowercase_conf);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
impl Default for DioxusConfig {
|
||||
fn default() -> Self {
|
||||
let name = "name";
|
||||
Self {
|
||||
application: ApplicationConfig {
|
||||
name: name.into(),
|
||||
default_platform: Platform::Web,
|
||||
out_dir: Some(PathBuf::from("dist")),
|
||||
asset_dir: Some(PathBuf::from("public")),
|
||||
|
||||
tools: None,
|
||||
|
||||
sub_package: None,
|
||||
},
|
||||
web: WebConfig {
|
||||
app: WebAppConfig {
|
||||
title: Some("dioxus | ⛺".into()),
|
||||
base_path: None,
|
||||
},
|
||||
proxy: Some(vec![]),
|
||||
watcher: WebWatcherConfig {
|
||||
watch_path: Some(vec![PathBuf::from("src"), PathBuf::from("examples")]),
|
||||
reload_html: Some(false),
|
||||
index_on_404: Some(true),
|
||||
},
|
||||
resource: WebResourceConfig {
|
||||
dev: WebDevResourceConfig {
|
||||
style: Some(vec![]),
|
||||
script: Some(vec![]),
|
||||
},
|
||||
style: Some(vec![]),
|
||||
script: Some(vec![]),
|
||||
},
|
||||
https: WebHttpsConfig {
|
||||
enabled: None,
|
||||
mkcert: None,
|
||||
key_path: None,
|
||||
cert_path: None,
|
||||
},
|
||||
},
|
||||
bundle: BundleConfig {
|
||||
identifier: Some(format!("io.github.{name}")),
|
||||
publisher: Some(name.into()),
|
||||
..Default::default()
|
||||
},
|
||||
plugin: toml::Value::Table(toml::map::Map::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ApplicationConfig {
|
||||
pub name: String,
|
||||
pub default_platform: Platform,
|
||||
pub out_dir: Option<PathBuf>,
|
||||
pub asset_dir: Option<PathBuf>,
|
||||
|
||||
pub tools: Option<HashMap<String, toml::Value>>,
|
||||
|
||||
pub sub_package: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct WebConfig {
|
||||
pub app: WebAppConfig,
|
||||
pub proxy: Option<Vec<WebProxyConfig>>,
|
||||
pub watcher: WebWatcherConfig,
|
||||
pub resource: WebResourceConfig,
|
||||
#[serde(default)]
|
||||
pub https: WebHttpsConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct WebAppConfig {
|
||||
pub title: Option<String>,
|
||||
pub base_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct WebProxyConfig {
|
||||
pub backend: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct WebWatcherConfig {
|
||||
pub watch_path: Option<Vec<PathBuf>>,
|
||||
pub reload_html: Option<bool>,
|
||||
pub index_on_404: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct WebResourceConfig {
|
||||
pub dev: WebDevResourceConfig,
|
||||
pub style: Option<Vec<PathBuf>>,
|
||||
pub script: Option<Vec<PathBuf>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct WebDevResourceConfig {
|
||||
pub style: Option<Vec<PathBuf>>,
|
||||
pub script: Option<Vec<PathBuf>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
|
||||
pub struct WebHttpsConfig {
|
||||
pub enabled: Option<bool>,
|
||||
pub mkcert: Option<bool>,
|
||||
pub key_path: Option<String>,
|
||||
pub cert_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CrateConfig {
|
||||
pub out_dir: PathBuf,
|
||||
pub crate_dir: PathBuf,
|
||||
pub workspace_dir: PathBuf,
|
||||
pub target_dir: PathBuf,
|
||||
pub asset_dir: PathBuf,
|
||||
pub manifest: cargo_toml::Manifest<cargo_toml::Value>,
|
||||
pub executable: ExecutableType,
|
||||
pub dioxus_config: DioxusConfig,
|
||||
pub release: bool,
|
||||
pub hot_reload: bool,
|
||||
pub cross_origin_policy: bool,
|
||||
pub verbose: bool,
|
||||
pub custom_profile: Option<String>,
|
||||
pub features: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ExecutableType {
|
||||
Binary(String),
|
||||
Lib(String),
|
||||
Example(String),
|
||||
}
|
||||
|
||||
impl CrateConfig {
|
||||
pub fn new(bin: Option<PathBuf>) -> Result<Self> {
|
||||
let dioxus_config = DioxusConfig::load(bin.clone())?.unwrap_or_default();
|
||||
|
||||
let crate_root = crate::cargo::crate_root()?;
|
||||
|
||||
let crate_dir = if let Some(package) = &dioxus_config.application.sub_package {
|
||||
crate_root.join(package)
|
||||
} else if let Some(bin) = bin {
|
||||
crate_root.join(bin)
|
||||
} else {
|
||||
crate_root
|
||||
};
|
||||
|
||||
let meta = crate::cargo::Metadata::get()?;
|
||||
let workspace_dir = meta.workspace_root;
|
||||
let target_dir = meta.target_directory;
|
||||
|
||||
let out_dir = match 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 asset_dir = match 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 mut output_filename = String::from("dioxus_app");
|
||||
if let Some(package) = &manifest.package.as_ref() {
|
||||
output_filename = match &package.default_run {
|
||||
Some(default_run_target) => default_run_target.to_owned(),
|
||||
None => manifest
|
||||
.bin
|
||||
.iter()
|
||||
.find(|b| b.name == manifest.package.as_ref().map(|pkg| pkg.name.clone()))
|
||||
.or(manifest
|
||||
.bin
|
||||
.iter()
|
||||
.find(|b| b.path == Some("src/main.rs".to_owned())))
|
||||
.or(manifest.bin.first())
|
||||
.or(manifest.lib.as_ref())
|
||||
.and_then(|prod| prod.name.clone())
|
||||
.unwrap_or(String::from("dioxus_app")),
|
||||
};
|
||||
}
|
||||
|
||||
let executable = ExecutableType::Binary(output_filename);
|
||||
|
||||
let release = false;
|
||||
let hot_reload = false;
|
||||
let verbose = false;
|
||||
let custom_profile = None;
|
||||
let features = None;
|
||||
|
||||
Ok(Self {
|
||||
out_dir,
|
||||
crate_dir,
|
||||
workspace_dir,
|
||||
target_dir,
|
||||
asset_dir,
|
||||
manifest,
|
||||
executable,
|
||||
release,
|
||||
dioxus_config,
|
||||
hot_reload,
|
||||
cross_origin_policy: false,
|
||||
custom_profile,
|
||||
features,
|
||||
verbose,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn as_example(&mut self, example_name: String) -> &mut Self {
|
||||
self.executable = ExecutableType::Example(example_name);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_release(&mut self, release: bool) -> &mut Self {
|
||||
self.release = release;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_hot_reload(&mut self, hot_reload: bool) -> &mut Self {
|
||||
self.hot_reload = hot_reload;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_cross_origin_policy(&mut self, cross_origin_policy: bool) -> &mut Self {
|
||||
self.cross_origin_policy = cross_origin_policy;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_verbose(&mut self, verbose: bool) -> &mut Self {
|
||||
self.verbose = verbose;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn set_profile(&mut self, profile: String) -> &mut Self {
|
||||
self.custom_profile = Some(profile);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn set_features(&mut self, features: Vec<String>) -> &mut Self {
|
||||
self.features = Some(features);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct BundleConfig {
|
||||
pub identifier: Option<String>,
|
||||
pub publisher: Option<String>,
|
||||
pub icon: Option<Vec<String>>,
|
||||
pub resources: Option<Vec<String>>,
|
||||
pub copyright: Option<String>,
|
||||
pub category: Option<String>,
|
||||
pub short_description: Option<String>,
|
||||
pub long_description: Option<String>,
|
||||
pub external_bin: Option<Vec<String>>,
|
||||
pub deb: Option<DebianSettings>,
|
||||
pub macos: Option<MacOsSettings>,
|
||||
pub windows: Option<WindowsSettings>,
|
||||
}
|
||||
|
||||
impl From<BundleConfig> for tauri_bundler::BundleSettings {
|
||||
fn from(val: BundleConfig) -> Self {
|
||||
tauri_bundler::BundleSettings {
|
||||
identifier: val.identifier,
|
||||
publisher: val.publisher,
|
||||
icon: val.icon,
|
||||
resources: val.resources,
|
||||
copyright: val.copyright,
|
||||
category: val.category.and_then(|c| c.parse().ok()),
|
||||
short_description: val.short_description,
|
||||
long_description: val.long_description,
|
||||
external_bin: val.external_bin,
|
||||
deb: val.deb.map(Into::into).unwrap_or_default(),
|
||||
macos: val.macos.map(Into::into).unwrap_or_default(),
|
||||
windows: val.windows.map(Into::into).unwrap_or_default(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct DebianSettings {
|
||||
pub depends: Option<Vec<String>>,
|
||||
pub files: HashMap<PathBuf, PathBuf>,
|
||||
pub nsis: Option<NsisSettings>,
|
||||
}
|
||||
|
||||
impl From<DebianSettings> for tauri_bundler::DebianSettings {
|
||||
fn from(val: DebianSettings) -> Self {
|
||||
tauri_bundler::DebianSettings {
|
||||
depends: val.depends,
|
||||
files: val.files,
|
||||
desktop_template: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct WixSettings {
|
||||
pub language: Vec<(String, Option<PathBuf>)>,
|
||||
pub template: Option<PathBuf>,
|
||||
pub fragment_paths: Vec<PathBuf>,
|
||||
pub component_group_refs: Vec<String>,
|
||||
pub component_refs: Vec<String>,
|
||||
pub feature_group_refs: Vec<String>,
|
||||
pub feature_refs: Vec<String>,
|
||||
pub merge_refs: Vec<String>,
|
||||
pub skip_webview_install: bool,
|
||||
pub license: Option<PathBuf>,
|
||||
pub enable_elevated_update_task: bool,
|
||||
pub banner_path: Option<PathBuf>,
|
||||
pub dialog_image_path: Option<PathBuf>,
|
||||
pub fips_compliant: bool,
|
||||
}
|
||||
|
||||
impl From<WixSettings> for tauri_bundler::WixSettings {
|
||||
fn from(val: WixSettings) -> Self {
|
||||
tauri_bundler::WixSettings {
|
||||
language: tauri_bundler::bundle::WixLanguage({
|
||||
let mut languages: Vec<_> = val
|
||||
.language
|
||||
.iter()
|
||||
.map(|l| {
|
||||
(
|
||||
l.0.clone(),
|
||||
tauri_bundler::bundle::WixLanguageConfig {
|
||||
locale_path: l.1.clone(),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
if languages.is_empty() {
|
||||
languages.push(("en-US".into(), Default::default()));
|
||||
}
|
||||
languages
|
||||
}),
|
||||
template: val.template,
|
||||
fragment_paths: val.fragment_paths,
|
||||
component_group_refs: val.component_group_refs,
|
||||
component_refs: val.component_refs,
|
||||
feature_group_refs: val.feature_group_refs,
|
||||
feature_refs: val.feature_refs,
|
||||
merge_refs: val.merge_refs,
|
||||
skip_webview_install: val.skip_webview_install,
|
||||
license: val.license,
|
||||
enable_elevated_update_task: val.enable_elevated_update_task,
|
||||
banner_path: val.banner_path,
|
||||
dialog_image_path: val.dialog_image_path,
|
||||
fips_compliant: val.fips_compliant,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct MacOsSettings {
|
||||
pub frameworks: Option<Vec<String>>,
|
||||
pub minimum_system_version: Option<String>,
|
||||
pub license: Option<String>,
|
||||
pub exception_domain: Option<String>,
|
||||
pub signing_identity: Option<String>,
|
||||
pub provider_short_name: Option<String>,
|
||||
pub entitlements: Option<String>,
|
||||
pub info_plist_path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl From<MacOsSettings> for tauri_bundler::MacOsSettings {
|
||||
fn from(val: MacOsSettings) -> Self {
|
||||
tauri_bundler::MacOsSettings {
|
||||
frameworks: val.frameworks,
|
||||
minimum_system_version: val.minimum_system_version,
|
||||
license: val.license,
|
||||
exception_domain: val.exception_domain,
|
||||
signing_identity: val.signing_identity,
|
||||
provider_short_name: val.provider_short_name,
|
||||
entitlements: val.entitlements,
|
||||
info_plist_path: val.info_plist_path,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct WindowsSettings {
|
||||
pub digest_algorithm: Option<String>,
|
||||
pub certificate_thumbprint: Option<String>,
|
||||
pub timestamp_url: Option<String>,
|
||||
pub tsp: bool,
|
||||
pub wix: Option<WixSettings>,
|
||||
pub icon_path: Option<PathBuf>,
|
||||
pub webview_install_mode: WebviewInstallMode,
|
||||
pub webview_fixed_runtime_path: Option<PathBuf>,
|
||||
pub allow_downgrades: bool,
|
||||
pub nsis: Option<NsisSettings>,
|
||||
}
|
||||
|
||||
impl From<WindowsSettings> for tauri_bundler::WindowsSettings {
|
||||
fn from(val: WindowsSettings) -> Self {
|
||||
tauri_bundler::WindowsSettings {
|
||||
digest_algorithm: val.digest_algorithm,
|
||||
certificate_thumbprint: val.certificate_thumbprint,
|
||||
timestamp_url: val.timestamp_url,
|
||||
tsp: val.tsp,
|
||||
wix: val.wix.map(Into::into),
|
||||
icon_path: val.icon_path.unwrap_or("icons/icon.ico".into()),
|
||||
webview_install_mode: val.webview_install_mode.into(),
|
||||
webview_fixed_runtime_path: val.webview_fixed_runtime_path,
|
||||
allow_downgrades: val.allow_downgrades,
|
||||
nsis: val.nsis.map(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct NsisSettings {
|
||||
pub template: Option<PathBuf>,
|
||||
pub license: Option<PathBuf>,
|
||||
pub header_image: Option<PathBuf>,
|
||||
pub sidebar_image: Option<PathBuf>,
|
||||
pub installer_icon: Option<PathBuf>,
|
||||
pub install_mode: NSISInstallerMode,
|
||||
pub languages: Option<Vec<String>>,
|
||||
pub custom_language_files: Option<HashMap<String, PathBuf>>,
|
||||
pub display_language_selector: bool,
|
||||
}
|
||||
|
||||
impl From<NsisSettings> for tauri_bundler::NsisSettings {
|
||||
fn from(val: NsisSettings) -> Self {
|
||||
tauri_bundler::NsisSettings {
|
||||
license: val.license,
|
||||
header_image: val.header_image,
|
||||
sidebar_image: val.sidebar_image,
|
||||
installer_icon: val.installer_icon,
|
||||
install_mode: val.install_mode.into(),
|
||||
languages: val.languages,
|
||||
display_language_selector: val.display_language_selector,
|
||||
custom_language_files: None,
|
||||
template: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum NSISInstallerMode {
|
||||
CurrentUser,
|
||||
PerMachine,
|
||||
Both,
|
||||
}
|
||||
|
||||
impl From<NSISInstallerMode> for tauri_utils::config::NSISInstallerMode {
|
||||
fn from(val: NSISInstallerMode) -> Self {
|
||||
match val {
|
||||
NSISInstallerMode::CurrentUser => tauri_utils::config::NSISInstallerMode::CurrentUser,
|
||||
NSISInstallerMode::PerMachine => tauri_utils::config::NSISInstallerMode::PerMachine,
|
||||
NSISInstallerMode::Both => tauri_utils::config::NSISInstallerMode::Both,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum WebviewInstallMode {
|
||||
Skip,
|
||||
DownloadBootstrapper { silent: bool },
|
||||
EmbedBootstrapper { silent: bool },
|
||||
OfflineInstaller { silent: bool },
|
||||
FixedRuntime { path: PathBuf },
|
||||
}
|
||||
|
||||
impl WebviewInstallMode {
|
||||
fn into(self) -> tauri_utils::config::WebviewInstallMode {
|
||||
match self {
|
||||
Self::Skip => tauri_utils::config::WebviewInstallMode::Skip,
|
||||
Self::DownloadBootstrapper { silent } => {
|
||||
tauri_utils::config::WebviewInstallMode::DownloadBootstrapper { silent }
|
||||
}
|
||||
Self::EmbedBootstrapper { silent } => {
|
||||
tauri_utils::config::WebviewInstallMode::EmbedBootstrapper { silent }
|
||||
}
|
||||
Self::OfflineInstaller { silent } => {
|
||||
tauri_utils::config::WebviewInstallMode::OfflineInstaller { silent }
|
||||
}
|
||||
Self::FixedRuntime { path } => {
|
||||
tauri_utils::config::WebviewInstallMode::FixedRuntime { path }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for WebviewInstallMode {
|
||||
fn default() -> Self {
|
||||
Self::OfflineInstaller { silent: false }
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,24 @@ impl From<hyper::Error> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<dioxus_cli_config::LoadDioxusConfigError> for Error {
|
||||
fn from(e: dioxus_cli_config::LoadDioxusConfigError) -> Self {
|
||||
Self::RuntimeError(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<dioxus_cli_config::CargoError> for Error {
|
||||
fn from(e: dioxus_cli_config::CargoError) -> Self {
|
||||
Self::CargoError(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<dioxus_cli_config::CrateConfigError> for Error {
|
||||
fn from(e: dioxus_cli_config::CrateConfigError) -> Self {
|
||||
Self::RuntimeError(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! custom_error {
|
||||
($msg:literal $(,)?) => {
|
||||
|
||||
@@ -4,21 +4,16 @@
|
||||
|
||||
pub const DIOXUS_CLI_VERSION: &str = "0.4.1";
|
||||
|
||||
mod assets;
|
||||
pub mod builder;
|
||||
pub mod server;
|
||||
pub mod tools;
|
||||
|
||||
pub use builder::*;
|
||||
|
||||
pub mod cargo;
|
||||
pub use cargo::*;
|
||||
|
||||
pub mod cli;
|
||||
pub use cli::*;
|
||||
|
||||
pub mod config;
|
||||
pub use config::*;
|
||||
|
||||
pub mod error;
|
||||
pub use error::*;
|
||||
|
||||
|
||||
+17
-13
@@ -1,3 +1,4 @@
|
||||
use dioxus_cli_config::DioxusConfig;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::anyhow;
|
||||
@@ -42,34 +43,36 @@ async fn main() -> anyhow::Result<()> {
|
||||
|
||||
set_up_logging();
|
||||
|
||||
let bin = get_bin(args.bin)?;
|
||||
let bin = get_bin(args.bin);
|
||||
|
||||
let _dioxus_config = DioxusConfig::load(Some(bin.clone()))
|
||||
if let Ok(bin) = &bin {
|
||||
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");
|
||||
DioxusConfig::default()
|
||||
});
|
||||
|
||||
#[cfg(feature = "plugin")]
|
||||
PluginManager::init(_dioxus_config.plugin)
|
||||
.map_err(|e| anyhow!("🚫 Plugin system initialization failed: {e}"))?;
|
||||
#[cfg(feature = "plugin")]
|
||||
PluginManager::init(_dioxus_config.plugin)
|
||||
.map_err(|e| anyhow!("🚫 Plugin system initialization failed: {e}"))?;
|
||||
}
|
||||
|
||||
match args.action {
|
||||
Translate(opts) => opts
|
||||
.translate()
|
||||
.map_err(|e| anyhow!("🚫 Translation of HTML into RSX failed: {}", e)),
|
||||
|
||||
Build(opts) => opts
|
||||
.build(Some(bin.clone()))
|
||||
Build(opts) if bin.is_ok() => opts
|
||||
.build(Some(bin.unwrap().clone()), None)
|
||||
.map_err(|e| anyhow!("🚫 Building project failed: {}", e)),
|
||||
|
||||
Clean(opts) => opts
|
||||
.clean(Some(bin.clone()))
|
||||
Clean(opts) if bin.is_ok() => opts
|
||||
.clean(Some(bin.unwrap().clone()))
|
||||
.map_err(|e| anyhow!("🚫 Cleaning project failed: {}", e)),
|
||||
|
||||
Serve(opts) => opts
|
||||
.serve(Some(bin.clone()))
|
||||
Serve(opts) if bin.is_ok() => opts
|
||||
.serve(Some(bin.unwrap().clone()))
|
||||
.await
|
||||
.map_err(|e| anyhow!("🚫 Serving project failed: {}", e)),
|
||||
|
||||
@@ -81,8 +84,8 @@ async fn main() -> anyhow::Result<()> {
|
||||
.config()
|
||||
.map_err(|e| anyhow!("🚫 Configuring new project failed: {}", e)),
|
||||
|
||||
Bundle(opts) => opts
|
||||
.bundle(Some(bin.clone()))
|
||||
Bundle(opts) if bin.is_ok() => opts
|
||||
.bundle(Some(bin.unwrap().clone()))
|
||||
.map_err(|e| anyhow!("🚫 Bundling project failed: {}", e)),
|
||||
|
||||
#[cfg(feature = "plugin")]
|
||||
@@ -107,5 +110,6 @@ async fn main() -> anyhow::Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(anyhow::anyhow!(bin.unwrap_err())),
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
use crate::server::Platform;
|
||||
use crate::{
|
||||
cfg::ConfigOptsServe,
|
||||
server::{
|
||||
output::{print_console_info, PrettierOptions},
|
||||
setup_file_watcher,
|
||||
},
|
||||
BuildResult, CrateConfig, Result,
|
||||
BuildResult, Result,
|
||||
};
|
||||
use dioxus_cli_config::CrateConfig;
|
||||
use dioxus_cli_config::ExecutableType;
|
||||
|
||||
use dioxus_hot_reload::HotReloadMsg;
|
||||
use dioxus_html::HtmlCtx;
|
||||
@@ -21,7 +25,14 @@ use plugin::PluginManager;
|
||||
|
||||
use super::HotReloadState;
|
||||
|
||||
pub async fn startup(config: CrateConfig) -> Result<()> {
|
||||
pub async fn startup(config: CrateConfig, serve: &ConfigOptsServe) -> Result<()> {
|
||||
startup_with_platform::<DesktopPlatform>(config, serve).await
|
||||
}
|
||||
|
||||
pub(crate) async fn startup_with_platform<P: Platform + Send + 'static>(
|
||||
config: CrateConfig,
|
||||
serve_cfg: &ConfigOptsServe,
|
||||
) -> Result<()> {
|
||||
// ctrl-c shutdown checker
|
||||
let _crate_config = config.clone();
|
||||
let _ = ctrlc::set_handler(move || {
|
||||
@@ -51,15 +62,18 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
|
||||
false => None,
|
||||
};
|
||||
|
||||
serve(config, hot_reload_state).await?;
|
||||
serve::<P>(config, serve_cfg, hot_reload_state).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start the server without hot reload
|
||||
pub async fn serve(config: CrateConfig, hot_reload_state: Option<HotReloadState>) -> Result<()> {
|
||||
let (child, first_build_result) = start_desktop(&config)?;
|
||||
let currently_running_child: RwLock<Child> = RwLock::new(child);
|
||||
async fn serve<P: Platform + Send + 'static>(
|
||||
config: CrateConfig,
|
||||
serve: &ConfigOptsServe,
|
||||
hot_reload_state: Option<HotReloadState>,
|
||||
) -> Result<()> {
|
||||
let platform = RwLock::new(P::start(&config, serve)?);
|
||||
|
||||
log::info!("🚀 Starting development server...");
|
||||
|
||||
@@ -68,15 +82,7 @@ pub async fn serve(config: CrateConfig, hot_reload_state: Option<HotReloadState>
|
||||
let _watcher = setup_file_watcher(
|
||||
{
|
||||
let config = config.clone();
|
||||
|
||||
move || {
|
||||
let mut current_child = currently_running_child.write().unwrap();
|
||||
log::trace!("Killing old process");
|
||||
current_child.kill()?;
|
||||
let (child, result) = start_desktop(&config)?;
|
||||
*current_child = child;
|
||||
Ok(result)
|
||||
}
|
||||
move || platform.write().unwrap().rebuild(&config)
|
||||
},
|
||||
&config,
|
||||
None,
|
||||
@@ -84,19 +90,9 @@ pub async fn serve(config: CrateConfig, hot_reload_state: Option<HotReloadState>
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Print serve info
|
||||
print_console_info(
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: vec![],
|
||||
warnings: first_build_result.warnings,
|
||||
elapsed_time: first_build_result.elapsed_time,
|
||||
},
|
||||
None,
|
||||
);
|
||||
|
||||
match hot_reload_state {
|
||||
Some(hot_reload_state) => {
|
||||
// The open interprocess sockets
|
||||
start_desktop_hot_reload(hot_reload_state).await?;
|
||||
}
|
||||
None => {
|
||||
@@ -154,7 +150,11 @@ async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()
|
||||
println!("Connected to hot reloading 🚀");
|
||||
}
|
||||
Err(err) => {
|
||||
if err.kind() != std::io::ErrorKind::WouldBlock {
|
||||
let error_string = err.to_string();
|
||||
// Filter out any error messages about a operation that may block and an error message that triggers on some operating systems that says "Waiting for a process to open the other end of the pipe" without WouldBlock being set
|
||||
let display_error = err.kind() != std::io::ErrorKind::WouldBlock
|
||||
&& !error_string.contains("Waiting for a process");
|
||||
if display_error {
|
||||
println!("Error connecting to hot reloading: {} (Hot reloading is a feature of the dioxus-cli. If you are not using the CLI, this error can be ignored)", err);
|
||||
}
|
||||
}
|
||||
@@ -188,7 +188,7 @@ async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()
|
||||
}
|
||||
|
||||
fn clear_paths(file_socket_path: &std::path::Path) {
|
||||
if cfg!(target_os = "macos") {
|
||||
if cfg!(unix) {
|
||||
// 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
|
||||
@@ -213,23 +213,70 @@ fn send_msg(msg: HotReloadMsg, channel: &mut impl std::io::Write) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_desktop(config: &CrateConfig) -> Result<(Child, BuildResult)> {
|
||||
fn start_desktop(config: &CrateConfig, skip_assets: bool) -> Result<(RAIIChild, BuildResult)> {
|
||||
// Run the desktop application
|
||||
log::trace!("Building application");
|
||||
let result = crate::builder::build_desktop(config, true)?;
|
||||
let result = crate::builder::build_desktop(config, true, skip_assets)?;
|
||||
|
||||
match &config.executable {
|
||||
crate::ExecutableType::Binary(name)
|
||||
| crate::ExecutableType::Lib(name)
|
||||
| crate::ExecutableType::Example(name) => {
|
||||
ExecutableType::Binary(name)
|
||||
| ExecutableType::Lib(name)
|
||||
| ExecutableType::Example(name) => {
|
||||
let mut file = config.out_dir.join(name);
|
||||
if cfg!(windows) {
|
||||
file.set_extension("exe");
|
||||
}
|
||||
log::trace!("Running application from {:?}", file);
|
||||
let child = Command::new(file.to_str().unwrap()).spawn()?;
|
||||
let active = "DIOXUS_ACTIVE";
|
||||
let child = RAIIChild(
|
||||
Command::new(file.to_str().unwrap())
|
||||
.env(active, "true")
|
||||
.spawn()?,
|
||||
);
|
||||
|
||||
Ok((child, result))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct DesktopPlatform {
|
||||
currently_running_child: RAIIChild,
|
||||
skip_assets: bool,
|
||||
}
|
||||
|
||||
impl Platform for DesktopPlatform {
|
||||
fn start(config: &CrateConfig, serve: &ConfigOptsServe) -> Result<Self> {
|
||||
let (child, first_build_result) = start_desktop(config, serve.skip_assets)?;
|
||||
|
||||
log::info!("🚀 Starting development server...");
|
||||
|
||||
// Print serve info
|
||||
print_console_info(
|
||||
config,
|
||||
PrettierOptions {
|
||||
changed: vec![],
|
||||
warnings: first_build_result.warnings,
|
||||
elapsed_time: first_build_result.elapsed_time,
|
||||
},
|
||||
None,
|
||||
);
|
||||
|
||||
Ok(Self {
|
||||
currently_running_child: child,
|
||||
skip_assets: serve.skip_assets,
|
||||
})
|
||||
}
|
||||
|
||||
fn rebuild(&mut self, config: &CrateConfig) -> Result<BuildResult> {
|
||||
self.currently_running_child.0.kill()?;
|
||||
let (child, result) = start_desktop(config, self.skip_assets)?;
|
||||
self.currently_running_child = child;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
struct RAIIChild(Child);
|
||||
|
||||
impl Drop for RAIIChild {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
use dioxus_cli_config::CrateConfig;
|
||||
|
||||
use crate::{
|
||||
assets::WebAssetConfigDropGuard,
|
||||
cfg::{ConfigOptsBuild, ConfigOptsServe},
|
||||
Result,
|
||||
};
|
||||
|
||||
use super::{desktop, Platform};
|
||||
|
||||
pub async fn startup(config: CrateConfig, serve: &ConfigOptsServe) -> Result<()> {
|
||||
desktop::startup_with_platform::<FullstackPlatform>(config, serve).await
|
||||
}
|
||||
|
||||
fn start_web_build_thread(
|
||||
config: &CrateConfig,
|
||||
serve: &ConfigOptsServe,
|
||||
) -> std::thread::JoinHandle<Result<()>> {
|
||||
let serve = serve.clone();
|
||||
let target_directory = config.crate_dir.join(".dioxus").join("web");
|
||||
std::fs::create_dir_all(&target_directory).unwrap();
|
||||
std::thread::spawn(move || build_web(serve, &target_directory))
|
||||
}
|
||||
|
||||
struct FullstackPlatform {
|
||||
serve: ConfigOptsServe,
|
||||
desktop: desktop::DesktopPlatform,
|
||||
_config: WebAssetConfigDropGuard,
|
||||
}
|
||||
|
||||
impl Platform for FullstackPlatform {
|
||||
fn start(config: &CrateConfig, serve: &ConfigOptsServe) -> Result<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
let thread_handle = start_web_build_thread(config, serve);
|
||||
|
||||
let mut desktop_config = config.clone();
|
||||
let desktop_feature = serve.server_feature.clone();
|
||||
let features = &mut desktop_config.features;
|
||||
match features {
|
||||
Some(features) => {
|
||||
features.push(desktop_feature);
|
||||
}
|
||||
None => desktop_config.features = Some(vec![desktop_feature]),
|
||||
};
|
||||
let config = WebAssetConfigDropGuard::new();
|
||||
let desktop = desktop::DesktopPlatform::start(&desktop_config, serve)?;
|
||||
thread_handle
|
||||
.join()
|
||||
.map_err(|_| anyhow::anyhow!("Failed to join thread"))??;
|
||||
|
||||
Ok(Self {
|
||||
desktop,
|
||||
serve: serve.clone(),
|
||||
_config: config,
|
||||
})
|
||||
}
|
||||
|
||||
fn rebuild(&mut self, crate_config: &CrateConfig) -> Result<crate::BuildResult> {
|
||||
let thread_handle = start_web_build_thread(crate_config, &self.serve);
|
||||
let result = {
|
||||
let mut desktop_config = crate_config.clone();
|
||||
let desktop_feature = self.serve.server_feature.clone();
|
||||
let features = &mut desktop_config.features;
|
||||
match features {
|
||||
Some(features) => {
|
||||
features.push(desktop_feature);
|
||||
}
|
||||
None => desktop_config.features = Some(vec![desktop_feature]),
|
||||
};
|
||||
let _gaurd = FullstackServerEnvGuard::new(self.serve.force_debug, self.serve.release);
|
||||
self.desktop.rebuild(&desktop_config)
|
||||
};
|
||||
thread_handle
|
||||
.join()
|
||||
.map_err(|_| anyhow::anyhow!("Failed to join thread"))??;
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
fn build_web(serve: ConfigOptsServe, target_directory: &std::path::Path) -> Result<()> {
|
||||
let mut web_config: ConfigOptsBuild = serve.into();
|
||||
let web_feature = web_config.client_feature.clone();
|
||||
let features = &mut web_config.features;
|
||||
match features {
|
||||
Some(features) => {
|
||||
features.push(web_feature);
|
||||
}
|
||||
None => web_config.features = Some(vec![web_feature]),
|
||||
};
|
||||
web_config.platform = Some(dioxus_cli_config::Platform::Web);
|
||||
|
||||
let _gaurd = FullstackWebEnvGuard::new(&web_config);
|
||||
crate::cli::build::Build { build: web_config }.build(None, Some(target_directory))
|
||||
}
|
||||
|
||||
// Debug mode web builds have a very large size by default. If debug mode is not enabled, we strip some of the debug info by default
|
||||
// This reduces a hello world from ~40MB to ~2MB
|
||||
pub(crate) struct FullstackWebEnvGuard {
|
||||
old_rustflags: Option<String>,
|
||||
}
|
||||
|
||||
impl FullstackWebEnvGuard {
|
||||
pub fn new(serve: &ConfigOptsBuild) -> Self {
|
||||
Self {
|
||||
old_rustflags: (!serve.force_debug).then(|| {
|
||||
let old_rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
|
||||
let debug_assertions = if serve.release {
|
||||
""
|
||||
} else {
|
||||
" -C debug-assertions"
|
||||
};
|
||||
|
||||
std::env::set_var(
|
||||
"RUSTFLAGS",
|
||||
format!(
|
||||
"{old_rustflags} -C debuginfo=none -C strip=debuginfo{debug_assertions}"
|
||||
),
|
||||
);
|
||||
old_rustflags
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FullstackWebEnvGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(old_rustflags) = self.old_rustflags.take() {
|
||||
std::env::set_var("RUSTFLAGS", old_rustflags);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Debug mode web builds have a very large size by default. If debug mode is not enabled, we strip some of the debug info by default
|
||||
// This reduces a hello world from ~40MB to ~2MB
|
||||
pub(crate) struct FullstackServerEnvGuard {
|
||||
old_rustflags: Option<String>,
|
||||
}
|
||||
|
||||
impl FullstackServerEnvGuard {
|
||||
pub fn new(debug: bool, release: bool) -> Self {
|
||||
Self {
|
||||
old_rustflags: (!debug).then(|| {
|
||||
let old_rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
|
||||
let debug_assertions = if release { "" } else { " -C debug-assertions" };
|
||||
|
||||
std::env::set_var(
|
||||
"RUSTFLAGS",
|
||||
format!("{old_rustflags} -C opt-level=2 {debug_assertions}"),
|
||||
);
|
||||
old_rustflags
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FullstackServerEnvGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(old_rustflags) = self.old_rustflags.take() {
|
||||
std::env::set_var("RUSTFLAGS", old_rustflags);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,18 @@
|
||||
use crate::{BuildResult, CrateConfig, Result};
|
||||
use crate::{cfg::ConfigOptsServe, BuildResult, Result};
|
||||
use dioxus_cli_config::CrateConfig;
|
||||
|
||||
use cargo_metadata::diagnostic::Diagnostic;
|
||||
use dioxus_core::Template;
|
||||
use dioxus_html::HtmlCtx;
|
||||
use dioxus_rsx::hot_reload::*;
|
||||
use notify::{RecommendedWatcher, Watcher};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::sync::broadcast::{self};
|
||||
|
||||
mod output;
|
||||
use output::*;
|
||||
pub mod desktop;
|
||||
pub mod fullstack;
|
||||
pub mod web;
|
||||
|
||||
/// Sets up a file watcher
|
||||
@@ -26,13 +25,7 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
|
||||
let mut last_update_time = chrono::Local::now().timestamp();
|
||||
|
||||
// file watcher: check file change
|
||||
let allow_watch_path = config
|
||||
.dioxus_config
|
||||
.web
|
||||
.watcher
|
||||
.watch_path
|
||||
.clone()
|
||||
.unwrap_or_else(|| vec![PathBuf::from("src"), PathBuf::from("examples")]);
|
||||
let allow_watch_path = config.dioxus_config.web.watcher.watch_path.clone();
|
||||
|
||||
let watcher_config = config.clone();
|
||||
let mut watcher = notify::recommended_watcher(move |info: notify::Result<notify::Event>| {
|
||||
@@ -141,6 +134,13 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
|
||||
Ok(watcher)
|
||||
}
|
||||
|
||||
pub(crate) trait Platform {
|
||||
fn start(config: &CrateConfig, serve: &ConfigOptsServe) -> Result<Self>
|
||||
where
|
||||
Self: Sized;
|
||||
fn rebuild(&mut self, config: &CrateConfig) -> Result<BuildResult>;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HotReloadState {
|
||||
pub messages: broadcast::Sender<Template<'static>>,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::server::Diagnostic;
|
||||
use crate::CrateConfig;
|
||||
use colored::Colorize;
|
||||
use dioxus_cli_config::crate_root;
|
||||
use dioxus_cli_config::CrateConfig;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
@@ -43,25 +44,19 @@ pub fn print_console_info(
|
||||
profile = config.custom_profile.as_ref().unwrap().to_string();
|
||||
}
|
||||
let hot_reload = if config.hot_reload { "RSX" } else { "Normal" };
|
||||
let crate_root = crate::cargo::crate_root().unwrap();
|
||||
let crate_root = crate_root().unwrap();
|
||||
let custom_html_file = if crate_root.join("index.html").is_file() {
|
||||
"Custom [index.html]"
|
||||
} else {
|
||||
"Default"
|
||||
};
|
||||
let url_rewrite = if config
|
||||
.dioxus_config
|
||||
.web
|
||||
.watcher
|
||||
.index_on_404
|
||||
.unwrap_or(false)
|
||||
{
|
||||
let url_rewrite = if config.dioxus_config.web.watcher.index_on_404 {
|
||||
"True"
|
||||
} else {
|
||||
"False"
|
||||
};
|
||||
|
||||
let proxies = config.dioxus_config.web.proxy.as_ref();
|
||||
let proxies = &config.dioxus_config.web.proxy;
|
||||
|
||||
if options.changed.is_empty() {
|
||||
println!(
|
||||
@@ -109,12 +104,10 @@ pub fn print_console_info(
|
||||
println!();
|
||||
println!("\t> Profile : {}", profile.green());
|
||||
println!("\t> Hot Reload : {}", hot_reload.cyan());
|
||||
if let Some(proxies) = proxies {
|
||||
if !proxies.is_empty() {
|
||||
println!("\t> Proxies :");
|
||||
for proxy in proxies {
|
||||
println!("\t\t- {}", proxy.backend.blue());
|
||||
}
|
||||
if !proxies.is_empty() {
|
||||
println!("\t> Proxies :");
|
||||
for proxy in proxies {
|
||||
println!("\t\t- {}", proxy.backend.blue());
|
||||
}
|
||||
}
|
||||
println!("\t> Index Template : {}", custom_html_file.green());
|
||||
|
||||
@@ -5,12 +5,13 @@ use crate::{
|
||||
output::{print_console_info, PrettierOptions, WebServerInfo},
|
||||
setup_file_watcher, HotReloadState,
|
||||
},
|
||||
BuildResult, CrateConfig, Result, WebHttpsConfig,
|
||||
BuildResult, Result,
|
||||
};
|
||||
use axum::{
|
||||
body::{Full, HttpBody},
|
||||
extract::{ws::Message, Extension, TypedHeader, WebSocketUpgrade},
|
||||
http::{
|
||||
self,
|
||||
header::{HeaderName, HeaderValue},
|
||||
Method, Response, StatusCode,
|
||||
},
|
||||
@@ -19,6 +20,8 @@ use axum::{
|
||||
Router,
|
||||
};
|
||||
use axum_server::tls_rustls::RustlsConfig;
|
||||
use dioxus_cli_config::CrateConfig;
|
||||
use dioxus_cli_config::WebHttpsConfig;
|
||||
|
||||
use dioxus_html::HtmlCtx;
|
||||
use dioxus_rsx::hot_reload::*;
|
||||
@@ -47,7 +50,12 @@ struct WsReloadState {
|
||||
update: broadcast::Sender<()>,
|
||||
}
|
||||
|
||||
pub async fn startup(port: u16, config: CrateConfig, start_browser: bool) -> Result<()> {
|
||||
pub async fn startup(
|
||||
port: u16,
|
||||
config: CrateConfig,
|
||||
start_browser: bool,
|
||||
skip_assets: bool,
|
||||
) -> Result<()> {
|
||||
// ctrl-c shutdown checker
|
||||
let _crate_config = config.clone();
|
||||
let _ = ctrlc::set_handler(move || {
|
||||
@@ -79,7 +87,15 @@ pub async fn startup(port: u16, config: CrateConfig, start_browser: bool) -> Res
|
||||
false => None,
|
||||
};
|
||||
|
||||
serve(ip, port, config, start_browser, hot_reload_state).await?;
|
||||
serve(
|
||||
ip,
|
||||
port,
|
||||
config,
|
||||
start_browser,
|
||||
skip_assets,
|
||||
hot_reload_state,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -90,9 +106,10 @@ pub async fn serve(
|
||||
port: u16,
|
||||
config: CrateConfig,
|
||||
start_browser: bool,
|
||||
skip_assets: bool,
|
||||
hot_reload_state: Option<HotReloadState>,
|
||||
) -> Result<()> {
|
||||
let first_build_result = crate::builder::build(&config, true)?;
|
||||
let first_build_result = crate::builder::build(&config, false, skip_assets)?;
|
||||
|
||||
log::info!("🚀 Starting development server...");
|
||||
|
||||
@@ -105,7 +122,7 @@ pub async fn serve(
|
||||
{
|
||||
let config = config.clone();
|
||||
let reload_tx = reload_tx.clone();
|
||||
move || build(&config, &reload_tx)
|
||||
move || build(&config, &reload_tx, skip_assets)
|
||||
},
|
||||
&config,
|
||||
Some(WebServerInfo {
|
||||
@@ -262,12 +279,7 @@ async fn setup_router(
|
||||
.override_response_header(HeaderName::from_static("cross-origin-opener-policy"), coop)
|
||||
.and_then(
|
||||
move |response: Response<ServeFileSystemResponseBody>| async move {
|
||||
let response = if file_service_config
|
||||
.dioxus_config
|
||||
.web
|
||||
.watcher
|
||||
.index_on_404
|
||||
.unwrap_or(false)
|
||||
let mut response = if file_service_config.dioxus_config.web.watcher.index_on_404
|
||||
&& response.status() == StatusCode::NOT_FOUND
|
||||
{
|
||||
let body = Full::from(
|
||||
@@ -290,6 +302,13 @@ async fn setup_router(
|
||||
} else {
|
||||
response.map(|body| body.boxed())
|
||||
};
|
||||
let headers = response.headers_mut();
|
||||
headers.insert(
|
||||
http::header::CACHE_CONTROL,
|
||||
HeaderValue::from_static("no-cache"),
|
||||
);
|
||||
headers.insert(http::header::PRAGMA, HeaderValue::from_static("no-cache"));
|
||||
headers.insert(http::header::EXPIRES, HeaderValue::from_static("0"));
|
||||
Ok(response)
|
||||
},
|
||||
)
|
||||
@@ -299,7 +318,7 @@ async fn setup_router(
|
||||
let mut router = Router::new().route("/_dioxus/ws", get(ws_handler));
|
||||
|
||||
// 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)?;
|
||||
}
|
||||
|
||||
@@ -313,6 +332,18 @@ async fn setup_router(
|
||||
},
|
||||
));
|
||||
|
||||
router = if let Some(base_path) = config.dioxus_config.web.app.base_path.clone() {
|
||||
let base_path = format!("/{}", base_path.trim_matches('/'));
|
||||
Router::new()
|
||||
.nest(&base_path, axum::routing::any_service(router))
|
||||
.fallback(get(move || {
|
||||
let base_path = base_path.clone();
|
||||
async move { format!("Outside of the base path: {}", base_path) }
|
||||
}))
|
||||
} else {
|
||||
router
|
||||
};
|
||||
|
||||
// Setup routes
|
||||
router = router
|
||||
.route("/_dioxus/hot_reload", get(hot_reload_handler))
|
||||
@@ -412,18 +443,12 @@ async fn ws_handler(
|
||||
})
|
||||
}
|
||||
|
||||
fn build(config: &CrateConfig, reload_tx: &Sender<()>) -> Result<BuildResult> {
|
||||
let result = builder::build(config, true)?;
|
||||
fn build(config: &CrateConfig, reload_tx: &Sender<()>, skip_assets: bool) -> Result<BuildResult> {
|
||||
let result = builder::build(config, true, skip_assets)?;
|
||||
// change the websocket reload state to true;
|
||||
// the page will auto-reload.
|
||||
if config
|
||||
.dioxus_config
|
||||
.web
|
||||
.watcher
|
||||
.reload_html
|
||||
.unwrap_or(false)
|
||||
{
|
||||
let _ = Serve::regen_dev_page(config);
|
||||
if config.dioxus_config.web.watcher.reload_html {
|
||||
let _ = Serve::regen_dev_page(config, skip_assets);
|
||||
}
|
||||
let _ = reload_tx.send(());
|
||||
Ok(result)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::{Result, WebProxyConfig};
|
||||
use crate::Result;
|
||||
use dioxus_cli_config::WebProxyConfig;
|
||||
|
||||
use anyhow::Context;
|
||||
use axum::{http::StatusCode, routing::any, Router};
|
||||
|
||||
Reference in new issue
Block a user