Skip to content

Commit

Permalink
CLI Fixes & Tweaks (#2846)
Browse files Browse the repository at this point in the history
 Fixes scrolling on vscode using simple fix
 Adds scroll modifier, scroll at 5 lines per scroll while holding shift key.
 Adds error handling for manganis failure that still lets the build run.
 Revises TUI rendering code.
 Move TUI "info bars" to the bottom of the terminal.
 Revised logging system with tracing
 Working [c] clear keybind. This has been removed.
 Removal of [h] hide keybind text (it does nothing)
 Some opinionated cleanups and renames to make tui logic easier to understand.
 Rolling log file & maybe add some more "internal" logging. Closes CLI Rolling Log File #2764
 Removes log tabs. Closes CLI: Color-code logs and get rid of tabs #2857
 Combines info bars.
 Working and good text selection.
 Print launch URL in console.
 Handle log lines properly and add formatting.
 Move MessageSource to a more reasonable location.
 Add some background styling to powerline (info bar) - Tried this and it doesn't look the greatest.
 Log Filtering
 Final Cleaning & Changes - I could do this forever
 Test Linux

---------

Co-authored-by: Jonathan Kelley <jkelleyrtp@gmail.com>
  • Loading branch information
DogeDark and jkelleyrtp authored Sep 13, 2024
1 parent 87c2f64 commit 8d68886
Show file tree
Hide file tree
Showing 22 changed files with 1,293 additions and 709 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ console = "0.15.8"
ctrlc = "3.2.3"
futures-channel = { workspace = true }
krates = { version = "0.17.0" }
regex = "1.10.6"

axum = { workspace = true, features = ["ws"] }
axum-server = { workspace = true, features = ["tls-rustls"] }
Expand Down
30 changes: 10 additions & 20 deletions packages/cli/src/assets.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::builder::{
BuildMessage, BuildRequest, MessageSource, MessageType, Stage, UpdateBuildProgress, UpdateStage,
};
use crate::builder::{BuildRequest, Stage, UpdateBuildProgress, UpdateStage};
use crate::Result;
use crate::TraceSrc;
use anyhow::Context;
use brotli::enc::BrotliEncoderParams;
use futures_channel::mpsc::UnboundedSender;
Expand All @@ -13,19 +12,18 @@ use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
use std::{ffi::OsString, path::PathBuf};
use std::{fs::File, io::Write};
use tracing::Level;
use walkdir::WalkDir;

/// The temp file name for passing manganis json from linker to current exec.
pub const MG_JSON_OUT: &str = "mg-out";

pub fn asset_manifest(build: &BuildRequest) -> AssetManifest {
pub fn asset_manifest(build: &BuildRequest) -> Option<AssetManifest> {
let file_path = build.target_out_dir().join(MG_JSON_OUT);
let read = fs::read_to_string(&file_path).unwrap();
let read = fs::read_to_string(&file_path).ok()?;
_ = fs::remove_file(file_path);
let json: Vec<String> = serde_json::from_str(&read).unwrap();

AssetManifest::load(json)
Some(AssetManifest::load(json))
}

/// Create a head file that contains all of the imports for assets that the user project uses
Expand Down Expand Up @@ -58,17 +56,7 @@ pub(crate) fn process_assets(
match process_file(file_asset, &static_asset_output_dir) {
Ok(_) => {
// Update the progress
_ = progress.start_send(UpdateBuildProgress {
stage: Stage::OptimizingAssets,
update: UpdateStage::AddMessage(BuildMessage {
level: Level::INFO,
message: MessageType::Text(format!(
"Optimized static asset {}",
file_asset
)),
source: MessageSource::Build,
}),
});
tracing::info!(dx_src = ?TraceSrc::Build, "Optimized static asset {file_asset}");
let assets_finished =
assets_finished.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
_ = progress.start_send(UpdateBuildProgress {
Expand All @@ -79,7 +67,7 @@ pub(crate) fn process_assets(
});
}
Err(err) => {
tracing::error!("Failed to copy static asset: {}", err);
tracing::error!(dx_src = ?TraceSrc::Build, "Failed to copy static asset: {}", err);
return Err(err);
}
}
Expand Down Expand Up @@ -134,6 +122,7 @@ pub(crate) fn copy_dir_to(
copy_dir_to(entry_path.clone(), output_file_location, pre_compress)
{
tracing::error!(
dx_src = ?TraceSrc::Build,
"Failed to pre-compress directory {}: {}",
entry_path.display(),
err
Expand All @@ -149,6 +138,7 @@ pub(crate) fn copy_dir_to(
if pre_compress {
if let Err(err) = pre_compress_file(&output_file_location) {
tracing::error!(
dx_src = ?TraceSrc::Build,
"Failed to pre-compress static assets {}: {}",
output_file_location.display(),
err
Expand Down Expand Up @@ -206,7 +196,7 @@ pub(crate) fn pre_compress_folder(path: &Path, pre_compress: bool) -> std::io::R
if entry_path.is_file() {
if pre_compress {
if let Err(err) = pre_compress_file(entry_path) {
tracing::error!("Failed to pre-compress file {entry_path:?}: {err}");
tracing::error!(dx_src = ?TraceSrc::Build, "Failed to pre-compress file {entry_path:?}: {err}");
}
}
// If pre-compression isn't enabled, we should remove the old compressed file if it exists
Expand Down
20 changes: 15 additions & 5 deletions packages/cli/src/builder/cargo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ use crate::builder::progress::UpdateBuildProgress;
use crate::builder::progress::UpdateStage;
use crate::link::LinkCommand;
use crate::Result;
use crate::TraceSrc;
use anyhow::Context;
use dioxus_cli_config::Platform;
use futures_channel::mpsc::UnboundedSender;
use manganis_cli_support::AssetManifest;
use manganis_cli_support::ManganisSupportGuard;
use std::fs::create_dir_all;
use std::path::PathBuf;
use tracing::error;

impl BuildRequest {
/// Create a list of arguments for cargo builds
Expand Down Expand Up @@ -101,7 +103,11 @@ impl BuildRequest {
&self,
mut progress: UnboundedSender<UpdateBuildProgress>,
) -> Result<BuildResult> {
tracing::info!("🚅 Running build [Desktop] command...");
tracing::info!(
dx_src = ?TraceSrc::Build,
"Running build [{}] command...",
self.target_platform,
);

// Set up runtime guards
let mut dioxus_version = crate::dx_build_info::PKG_VERSION.to_string();
Expand Down Expand Up @@ -136,8 +142,9 @@ impl BuildRequest {
.context("Failed to post process build")?;

tracing::info!(
"🚩 Build completed: [{}]",
self.dioxus_crate.out_dir().display()
dx_src = ?TraceSrc::Build,
"Build completed: [{}]",
self.dioxus_crate.out_dir().display(),
);

_ = progress.start_send(UpdateBuildProgress {
Expand Down Expand Up @@ -222,7 +229,10 @@ impl BuildRequest {
cargo_args,
Some(linker_args),
)?;
let assets = asset_manifest(&build);
let Some(assets) = asset_manifest(&build) else {
error!(dx_src = ?TraceSrc::Build, "the asset manifest was not provided by manganis and we were not able to collect assets");
return Err(anyhow::anyhow!("asset manifest was not provided by manganis"));
};
// Collect assets from the asset manifest the linker intercept created
process_assets(&build, &assets, &mut progress)?;
// Create the __assets_head.html file for bundling
Expand All @@ -235,7 +245,7 @@ impl BuildRequest {
}

pub fn copy_assets_dir(&self) -> anyhow::Result<()> {
tracing::info!("Copying public assets to the output directory...");
tracing::info!(dx_src = ?TraceSrc::Build, "Copying public assets to the output directory...");
let out_dir = self.target_out_dir();
let asset_dir = self.dioxus_crate.asset_dir();

Expand Down
39 changes: 30 additions & 9 deletions packages/cli/src/builder/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::build::Build;
use crate::cli::serve::ServeArguments;
use crate::dioxus_crate::DioxusCrate;
use crate::Result;
use crate::{build::Build, TraceSrc};
use dioxus_cli_config::{Platform, RuntimeCLIArguments};
use futures_util::stream::select_all;
use futures_util::StreamExt;
Expand All @@ -15,9 +15,7 @@ mod fullstack;
mod prepare_html;
mod progress;
mod web;
pub use progress::{
BuildMessage, MessageSource, MessageType, Stage, UpdateBuildProgress, UpdateStage,
};
pub use progress::{Stage, UpdateBuildProgress, UpdateStage};

/// The target platform for the build
/// This is very similar to the Platform enum, but we need to be able to differentiate between the
Expand Down Expand Up @@ -167,13 +165,36 @@ impl BuildResult {
fullstack_address: Option<SocketAddr>,
workspace: &std::path::Path,
) -> std::io::Result<Option<Child>> {
if self.target_platform == TargetPlatform::Web {
return Ok(None);
}
if self.target_platform == TargetPlatform::Server {
tracing::trace!("Proxying fullstack server from port {fullstack_address:?}");
match self.target_platform {
TargetPlatform::Web => {
tracing::info!(dx_src = ?TraceSrc::Dev, "Serving web app on http://{} 🎉", serve.address.address());
return Ok(None);
}
TargetPlatform::Desktop => {
tracing::info!(dx_src = ?TraceSrc::Dev, "Launching desktop app at {} 🎉", self.executable.display());
}
TargetPlatform::Server => {
if let Some(fullstack_address) = fullstack_address {
tracing::info!(
dx_src = ?TraceSrc::Dev,
"Launching fullstack server on http://{:?} 🎉",
fullstack_address
);
}
}
TargetPlatform::Liveview => {
if let Some(fullstack_address) = fullstack_address {
tracing::info!(
dx_src = ?TraceSrc::Dev,
"Launching liveview server on http://{:?} 🎉",
fullstack_address
);
}
}
}

tracing::info!(dx_src = ?TraceSrc::Dev, "Press [o] to open the app manually.");

let arguments = RuntimeCLIArguments::new(serve.address.address(), fullstack_address);
let executable = self.executable.canonicalize()?;
let mut cmd = Command::new(executable);
Expand Down
37 changes: 9 additions & 28 deletions packages/cli/src/builder/prepare_html.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
//! Build the HTML file to load a web application. The index.html file may be created from scratch or modified from the `index.html` file in the crate root.
use super::{BuildRequest, UpdateBuildProgress};
use crate::builder::progress::MessageSource;
use crate::builder::Stage;
use crate::Result;
use crate::TraceSrc;
use futures_channel::mpsc::UnboundedSender;
use manganis_cli_support::AssetManifest;
use std::fmt::Write;
use std::path::{Path, PathBuf};
use tracing::Level;

const DEFAULT_HTML: &str = include_str!("../../assets/index.html");
const TOAST_HTML: &str = include_str!("../../assets/toast.html");
Expand All @@ -17,12 +15,12 @@ impl BuildRequest {
pub(crate) fn prepare_html(
&self,
assets: Option<&AssetManifest>,
progress: &mut UnboundedSender<UpdateBuildProgress>,
_progress: &mut UnboundedSender<UpdateBuildProgress>,
) -> Result<String> {
let mut html = html_or_default(&self.dioxus_crate.crate_dir());

// Inject any resources from the config into the html
self.inject_resources(&mut html, assets, progress)?;
self.inject_resources(&mut html, assets)?;

// Inject loading scripts if they are not already present
self.inject_loading_scripts(&mut html);
Expand All @@ -38,12 +36,7 @@ impl BuildRequest {
}

// Inject any resources from the config into the html
fn inject_resources(
&self,
html: &mut String,
assets: Option<&AssetManifest>,
progress: &mut UnboundedSender<UpdateBuildProgress>,
) -> Result<()> {
fn inject_resources(&self, html: &mut String, assets: Option<&AssetManifest>) -> Result<()> {
// Collect all resources into a list of styles and scripts
let resources = &self.dioxus_crate.dioxus_config.web.resource;
let mut style_list = resources.style.clone().unwrap_or_default();
Expand All @@ -65,7 +58,7 @@ impl BuildRequest {
}

if !style_list.is_empty() {
self.send_resource_deprecation_warning(progress, style_list, ResourceType::Style);
self.send_resource_deprecation_warning(style_list, ResourceType::Style);
}

// Add all scripts to the head
Expand All @@ -78,7 +71,7 @@ impl BuildRequest {
}

if !script_list.is_empty() {
self.send_resource_deprecation_warning(progress, script_list, ResourceType::Script);
self.send_resource_deprecation_warning(script_list, ResourceType::Script);
}

// Inject any resources from manganis into the head
Expand Down Expand Up @@ -139,13 +132,8 @@ impl BuildRequest {
*html = html.replace("{app_name}", app_name);
}

fn send_resource_deprecation_warning(
&self,
progress: &mut UnboundedSender<UpdateBuildProgress>,
paths: Vec<PathBuf>,
variant: ResourceType,
) {
const RESOURCE_DEPRECATION_MESSAGE: &str = r#"The `web.resource` config has been deprecated in favor of head components and will be removed in a future release. Instead of including assets in the config, you can include assets with the `asset!` macro and add them to the head with `head::Link` and `Script` components."#;
fn send_resource_deprecation_warning(&self, paths: Vec<PathBuf>, variant: ResourceType) {
const RESOURCE_DEPRECATION_MESSAGE: &str = r#"The `web.resource` config has been deprecated in favor of head components and will be removed in a future release."#;

let replacement_components = paths
.iter()
Expand Down Expand Up @@ -187,14 +175,7 @@ impl BuildRequest {
"{RESOURCE_DEPRECATION_MESSAGE}\nTo migrate to head components, remove `{section_name}` and include the following rsx in your root component:\n```rust\n{replacement_components}\n```"
);

_ = progress.unbounded_send(UpdateBuildProgress {
stage: Stage::OptimizingWasm,
update: super::UpdateStage::AddMessage(super::BuildMessage {
level: Level::WARN,
message: super::MessageType::Text(message),
source: MessageSource::Build,
}),
});
tracing::warn!(dx_src = ?TraceSrc::Build, "{}", message);
}
}

Expand Down
Loading

0 comments on commit 8d68886

Please sign in to comment.