pull out the CLI config data into a separate library

This commit is contained in:
Evan Almloff committed 2023-11-08 12:48:25 -06:00
1 parent 8ea7f076e5
commit 8a2d170d96
18 files changed
+919 -36

No files matched your search

+1
View File
@@ -14,6 +14,7 @@ clap = { version = "4.2", features = ["derive"] }
thiserror = { workspace = true }
wasm-bindgen-cli-support = "0.2"
colored = "2.0.0"
dioxus-cli-config = { workspace = true }
# features
log = "0.4.14"
+2 -1
View File
@@ -5,6 +5,7 @@ use crate::{
DioxusConfig,
};
use cargo_metadata::{diagnostic::Diagnostic, Message};
use dioxus_cli_config::crate_root;
use indicatif::{ProgressBar, ProgressStyle};
use serde::Serialize;
use std::{
@@ -429,7 +430,7 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
}
pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
let crate_root = crate::cargo::crate_root().unwrap();
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();
-94
View File
@@ -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()))
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
use crate::cfg::Platform;
#[cfg(feature = "plugin")]
use crate::plugin::PluginManager;
use dioxus_cli_config::Platform;
use super::*;
+1 -12
View File
@@ -1,5 +1,4 @@
use clap::ValueEnum;
use serde::Serialize;
use dioxus_cli_config::Platform;
use super::*;
@@ -91,16 +90,6 @@ pub struct ConfigOptsServe {
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,
}
/// Config options for the bundling system.
#[derive(Clone, Debug, Default, Deserialize, Parser)]
pub struct ConfigOptsBundle {
+3 -1
View File
@@ -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,
+4 -2
View File
@@ -1,3 +1,5 @@
use dioxus_cli_config::Platform;
use super::*;
use std::{fs::create_dir_all, io::Write, path::PathBuf};
@@ -40,7 +42,7 @@ 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)?;
@@ -48,7 +50,7 @@ impl Serve {
server::web::startup(self.serve.port, crate_config.clone(), self.serve.open)
.await?;
}
cfg::Platform::Desktop => {
Platform::Desktop => {
server::desktop::startup(crate_config.clone()).await?;
}
}
+5 -4
View File
@@ -1,4 +1,5 @@
use crate::{cfg::Platform, error::Result};
use crate::error::Result;
use dioxus_cli_config::{crate_root, Metadata, Platform};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
@@ -24,7 +25,7 @@ fn default_plugin() -> toml::Value {
impl DioxusConfig {
pub fn load(bin: Option<PathBuf>) -> crate::error::Result<Option<DioxusConfig>> {
let crate_dir = crate::cargo::crate_root();
let crate_dir = crate_root();
let crate_dir = match crate_dir {
Ok(dir) => {
@@ -224,7 +225,7 @@ 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_root = crate_root()?;
let crate_dir = if let Some(package) = &dioxus_config.application.sub_package {
crate_root.join(package)
@@ -234,7 +235,7 @@ impl CrateConfig {
crate_root
};
let meta = crate::cargo::Metadata::get()?;
let meta = Metadata::get()?;
let workspace_dir = meta.workspace_root;
let target_dir = meta.target_directory;
+14
View File
@@ -69,6 +69,20 @@ 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())
}
}
#[macro_export]
macro_rules! custom_error {
($msg:literal $(,)?) => {
-3
View File
@@ -10,9 +10,6 @@ pub mod tools;
pub use builder::*;
pub mod cargo;
pub use cargo::*;
pub mod cli;
pub use cli::*;
+2 -1
View File
@@ -1,6 +1,7 @@
use crate::server::Diagnostic;
use crate::CrateConfig;
use colored::Colorize;
use dioxus_cli_config::crate_root;
use std::path::PathBuf;
use std::process::Command;
@@ -40,7 +41,7 @@ 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 {