فهرست منبع

Fix compiler errors

Aster 3 سال پیش
والد
کامیت
ce628e1197
13فایلهای تغییر یافته به همراه100 افزوده شده و 63 حذف شده
  1. 2 0
      Cargo.toml
  2. 4 5
      src/cli/build/mod.rs
  3. 8 8
      src/cli/cfg.rs
  4. 2 2
      src/cli/clean/mod.rs
  5. 5 4
      src/cli/config/mod.rs
  6. 8 12
      src/cli/create/mod.rs
  7. 16 15
      src/cli/mod.rs
  8. 5 5
      src/cli/serve/mod.rs
  9. 5 5
      src/cli/translate/mod.rs
  10. 37 0
      src/error.rs
  11. 2 2
      src/main.rs
  12. 2 1
      src/server/mod.rs
  13. 4 4
      tests/main.rs

+ 2 - 0
Cargo.toml

@@ -31,6 +31,8 @@ tokio = { version = "1.16.1", features = ["full"] }
 atty = "0.2.14"
 regex = "1.5.4"
 chrono = "0.4.19"
+anyhow = "1.0.53"
+hyper = "0.14.17"
 
 axum = { version = "0.4.5", features = ["ws", "headers"] }
 tower-http = { version = "0.2.2", features = ["fs", "trace"] }

+ 4 - 5
src/cli/build/mod.rs

@@ -1,16 +1,15 @@
 use super::*;
 
-
 /// Build the Rust WASM app and all of its assets.
 #[derive(Clone, Debug, Parser)]
-#[structopt(name = "build")]
+#[clap(name = "build")]
 pub struct Build {
-    #[structopt(flatten)]
+    #[clap(flatten)]
     pub build: ConfigOptsBuild,
 }
 
 impl Build {
-    pub fn build(self) -> anyhow::Result<()> {
+    pub fn build(self) -> Result<()> {
         let mut crate_config = crate::CrateConfig::new()?;
 
         // change the release state.
@@ -28,7 +27,7 @@ impl Build {
                 crate::builder::build_desktop(&crate_config)?;
             }
             _ => {
-                return Err(anyhow::anyhow!("Unsoppurt platform target."));
+                return custom_error!("Unsoppurt platform target.");
             }
         }
 

+ 8 - 8
src/cli/cfg.rs

@@ -4,40 +4,40 @@ use super::*;
 #[derive(Clone, Debug, Default, Deserialize, Parser)]
 pub struct ConfigOptsBuild {
     /// The index HTML file to drive the bundling process [default: index.html]
-    #[structopt(parse(from_os_str))]
+    #[clap(parse(from_os_str))]
     pub target: Option<PathBuf>,
 
     /// Build in release mode [default: false]
-    #[structopt(long)]
+    #[clap(long)]
     #[serde(default)]
     pub release: bool,
 
     /// Build a example [default: ""]
-    #[structopt(long)]
+    #[clap(long)]
     pub example: Option<String>,
 
     /// Build platform: support Web & Desktop [default: "web"]
-    #[structopt(long, default_value = "web")]
+    #[clap(long, default_value = "web")]
     pub platform: String,
 }
 
 #[derive(Clone, Debug, Default, Deserialize, Parser)]
 pub struct ConfigOptsServe {
     /// The index HTML file to drive the bundling process [default: index.html]
-    #[structopt(parse(from_os_str))]
+    #[clap(parse(from_os_str))]
     pub target: Option<PathBuf>,
 
     /// Build a example [default: ""]
-    #[structopt(long)]
+    #[clap(long)]
     pub example: Option<String>,
 
     /// Build in release mode [default: false]
-    #[structopt(long)]
+    #[clap(long)]
     #[serde(default)]
     pub release: bool,
 
     /// Build platform: support Web & Desktop [default: "web"]
-    #[structopt(long, default_value = "web")]
+    #[clap(long, default_value = "web")]
     pub platform: String,
 }
 

+ 2 - 2
src/cli/clean/mod.rs

@@ -2,11 +2,11 @@ use super::*;
 
 /// Build the Rust WASM app and all of its assets.
 #[derive(Clone, Debug, Parser)]
-#[structopt(name = "clean")]
+#[clap(name = "clean")]
 pub struct Clean {}
 
 impl Clean {
-    pub fn clean(self) -> anyhow::Result<()> {
+    pub fn clean(self) -> Result<()> {
         let crate_config = crate::CrateConfig::new()?;
 
         let output = Command::new("cargo")

+ 5 - 4
src/cli/config/mod.rs

@@ -1,8 +1,9 @@
 use super::*;
 
+
 /// Build the Rust WASM app and all of its assets.
-#[derive(Clone, Debug, Deserialize, Parser)]
-#[structopt(name = "config")]
+#[derive(Clone, Debug, Deserialize, Subcommand)]
+#[clap(name = "config")]
 pub enum Config {
     /// Init `Dioxus.toml` for project/folder.
     Init {
@@ -10,14 +11,14 @@ pub enum Config {
         name: String,
 
         /// Cover old config
-        #[structopt(long)]
+        #[clap(long)]
         #[serde(default)]
         force: bool,
     },
 }
 
 impl Config {
-    pub fn config(self) -> anyhow::Result<()> {
+    pub fn config(self) -> Result<()> {
         let crate_root = crate::cargo::crate_root()?;
         match self {
             Config::Init { name, force } => {

+ 8 - 12
src/cli/create/mod.rs

@@ -1,15 +1,16 @@
 use super::*;
+use crate::custom_error;
 
 /// Build the Rust WASM app and all of its assets.
-#[derive(Clone, Debug, Default, Deserialize, StructOpt)]
-#[structopt(name = "create")]
+#[derive(Clone, Debug, Default, Deserialize, Parser)]
+#[clap(name = "create")]
 pub struct Create {
     /// Init project name
-    #[structopt(default_value = ".")]
+    #[clap(default_value = ".")]
     name: String,
 
     /// Template path
-    #[structopt(default_value = "gh:dioxuslabs/dioxus-template", long)]
+    #[clap(default_value = "gh:dioxuslabs/dioxus-template", long)]
     template: String,
 }
 
@@ -23,10 +24,7 @@ impl Create {
         let project_path = PathBuf::from(&self.name);
 
         if project_path.join("Dioxus.toml").is_file() || project_path.join("Cargo.toml").is_file() {
-            return Err(Error::Other(anyhow::anyhow!(
-                "🧨 Folder '{}' is initialized.",
-                &self.name
-            )));
+            return custom_error!("🧨 Folder '{}' is initialized.", &self.name);
         }
 
         log::info!("🔧 Start to create a new project '{}'.", self.name);
@@ -47,9 +45,7 @@ impl Create {
                 .stderr(Stdio::inherit())
                 .output()?;
             if !install_output.status.success() {
-                return Err(Error::Other(anyhow::anyhow!(
-                    "Try to install cargo-generate failed."
-                )));
+                return custom_error!("Try to install cargo-generate failed.");
             }
         }
 
@@ -63,7 +59,7 @@ impl Create {
             .output()?;
 
         if !generate_output.status.success() {
-            return Err(Error::Other(anyhow::anyhow!("Generate project failed.")));
+            return custom_error!("Generate project failed.");
         }
 
         let mut dioxus_file = File::open(project_path.join("Dioxus.toml"))?;

+ 16 - 15
src/cli/mod.rs

@@ -6,31 +6,31 @@ pub mod create;
 pub mod serve;
 pub mod translate;
 
-use std::{io::Write, path::PathBuf};
+use crate::custom_error;
 use crate::{cfg::ConfigOptsBuild, gen_page};
-use clap::{Parser};
-use serde::Deserialize;
-use std::{
-    fs::remove_dir_all,
-    process::{Command, Stdio},
-};
-use std::{fs::File};
-use std::{
-    io::{Read},
-};
-use regex::Regex;
-use crate::{error::Result, Error};
 use crate::{cfg::ConfigOptsServe, server, CrateConfig};
+use crate::{error::Result, Error};
+use clap::Parser;
 use html_parser::Dom;
 use html_parser::Element;
 use html_parser::Node;
+use regex::Regex;
+use serde::Deserialize;
 use std::fmt::{Display, Formatter};
+use std::fs::File;
+use std::io::Read;
 use std::process::exit;
+use std::{
+    fs::remove_dir_all,
+    process::{Command, Stdio},
+};
+use std::{io::Write, path::PathBuf};
+use clap::{Subcommand};
 
 /// Build, bundle, & ship your Dioxus app.
 ///
 ///
-#[derive(Parser, Debug)]
+#[derive(Parser)]
 #[clap(name = "dioxus")]
 pub struct Cli {
     #[clap(subcommand)]
@@ -42,7 +42,7 @@ pub struct Cli {
     //
     // // note: dioxus is still roughly compatible with trunk
     // /// Path to the Trunk config file [default: Trunk.toml]
-    // #[structopt(long, parse(from_os_str), env = "TRUNK_CONFIG")]
+    // #[clap(long, parse(from_os_str), env = "TRUNK_CONFIG")]
     // pub config: Option<PathBuf>,
 }
 
@@ -59,5 +59,6 @@ pub enum Commands {
     /// Clean output artifacts.
     Clean(clean::Clean),
     /// Dioxus config file controls.
+    #[clap(subcommand)]
     Config(config::Config),
 }

+ 5 - 5
src/cli/serve/mod.rs

@@ -2,14 +2,14 @@ use super::*;
 
 /// Run the WASM project on dev-server
 #[derive(Clone, Debug, Parser)]
-#[structopt(name = "serve")]
+#[clap(name = "serve")]
 pub struct Serve {
-    #[structopt(flatten)]
+    #[clap(flatten)]
     pub serve: ConfigOptsServe,
 }
 
 impl Serve {
-    pub async fn serve(self) -> anyhow::Result<()> {
+    pub async fn serve(self) -> Result<()> {
         let mut crate_config = crate::CrateConfig::new()?;
 
         // change the relase state.
@@ -49,7 +49,7 @@ impl Serve {
                 return Ok(());
             }
             _ => {
-                return Err(anyhow::anyhow!("Unsoppurt platform target."));
+                return custom_error!("Unsoppurt platform target.");
             }
         }
 
@@ -62,7 +62,7 @@ impl Serve {
         Ok(())
     }
 
-    pub fn regen_dev_page(crate_config: &CrateConfig) -> anyhow::Result<()> {
+    pub fn regen_dev_page(crate_config: &CrateConfig) -> Result<()> {
         let serve_html = gen_page(&crate_config.dioxus_config, true);
 
         let mut file = std::fs::File::create(

+ 5 - 5
src/cli/translate/mod.rs

@@ -2,24 +2,24 @@ use super::*;
 
 /// Build the Rust WASM app and all of its assets.
 #[derive(Clone, Debug, Parser)]
-#[structopt(name = "translate")]
+#[clap(name = "translate")]
 pub struct Translate {
     /// Activate debug mode
     // short and long flags (-d, --debug) will be deduced from the field's name
-    #[structopt(short, long)]
+    #[clap(short, long)]
     pub component: bool,
 
     /// Input file
-    #[structopt(short, long)]
+    #[clap(short, long)]
     pub file: Option<String>,
 
     /// Output file, stdout if not present
-    #[structopt(parse(from_os_str))]
+    #[clap(parse(from_os_str))]
     pub output: Option<PathBuf>,
 }
 
 impl Translate {
-    pub fn translate(self) -> anyhow::Result<()> {
+    pub fn translate(self) -> Result<()> {
         let Translate {
             component,
             output,

+ 37 - 0
src/error.rs

@@ -11,6 +11,15 @@ pub enum Error {
     #[error("I/O Error: {0}")]
     IO(#[from] std::io::Error),
 
+    #[error("Format Error: {0}")]
+    FormatError(#[from] std::fmt::Error),
+
+    #[error("Format failed: {0}")]
+    ParseError(String),
+
+    #[error("Runtime Error: {0}")]
+    RuntimeError(String),
+
     #[error("Failed to write error")]
     FailedToWrite,
 
@@ -20,6 +29,9 @@ pub enum Error {
     #[error("Failed to write error")]
     CargoError(String),
 
+    #[error("{0}")]
+    CustomError(String),
+
     #[error(transparent)]
     Other(#[from] anyhow::Error),
 }
@@ -35,3 +47,28 @@ impl From<String> for Error {
         Error::Unique(s)
     }
 }
+
+impl From<html_parser::Error> for Error {
+    fn from(e: html_parser::Error) -> Self {
+        Self::ParseError(e.to_string())
+    }
+}
+
+impl From<hyper::Error> for Error {
+    fn from(e: hyper::Error) -> Self {
+        Self::RuntimeError(e.to_string())
+    }
+}
+
+#[macro_export]
+macro_rules! custom_error {
+    ($msg:literal $(,)?) => {
+        Err(Error::CustomError($msg.to_string()))
+    };
+    ($err:expr $(,)?) => {
+        Err(Error::from($err))
+    };
+    ($fmt:expr, $($arg:tt)*) => {
+        Err(Error::CustomError(format!($fmt, $($arg)*)))
+    };
+}

+ 2 - 2
src/main.rs

@@ -1,9 +1,9 @@
+use clap::Parser;
 use dioxus_cli::*;
-use structopt::StructOpt;
 
 #[tokio::main]
 async fn main() -> Result<()> {
-    let args = Cli::from_args();
+    let args = Cli::parse();
     set_up_logging();
 
     match args.action {

+ 2 - 1
src/server/mod.rs

@@ -10,6 +10,7 @@ use notify::{RecommendedWatcher, Watcher};
 use std::{path::PathBuf, sync::Arc};
 use tower_http::services::ServeDir;
 
+use crate::Result;
 use crate::{builder, serve::Serve, CrateConfig};
 use tokio::sync::broadcast;
 
@@ -17,7 +18,7 @@ struct WsRelodState {
     update: broadcast::Sender<String>,
 }
 
-pub async fn startup(config: CrateConfig) -> anyhow::Result<()> {
+pub async fn startup(config: CrateConfig) -> Result<()> {
     log::info!("🚀 Starting development server...");
 
     let dist_path = config.out_dir.clone();

+ 4 - 4
tests/main.rs

@@ -1,4 +1,4 @@
-#[test]
-fn ready() {
-    println!("Compiled successfully!")
-}
+#[test]
+fn ready() {
+    println!("Compiled successfully!")
+}