From 304540592a5d504778465fa075cdc3ab66fad6c6 Mon Sep 17 00:00:00 2001 From: Li Junchen Date: Fri, 27 Sep 2024 16:18:05 +0800 Subject: [PATCH] internal: clean up unused code (#349) --- crates/moonbuild/src/fmt.rs | 45 +------------- crates/moonbuild/src/gen/mod.rs | 12 ---- crates/moonbuild/src/lib.rs | 20 ------- crates/moonutil/src/common.rs | 103 ++------------------------------ 4 files changed, 5 insertions(+), 175 deletions(-) diff --git a/crates/moonbuild/src/fmt.rs b/crates/moonbuild/src/fmt.rs index fceade76..3671c518 100644 --- a/crates/moonbuild/src/fmt.rs +++ b/crates/moonbuild/src/fmt.rs @@ -16,13 +16,9 @@ // // For inquiries, you can contact us via e-mail at jichuruanjian@idea.edu.cn. -use std::path::{Path, PathBuf}; -use std::process::Command; +use std::path::PathBuf; -use anyhow::Context; -use moonutil::common::IGNORE_DIRS; use moonutil::module::ModuleDB; -use walkdir::WalkDir; use moonutil::common::{MoonbuildOpt, MooncOpt}; @@ -34,45 +30,6 @@ use std::rc::Rc; use crate::gen::cmd_builder::CommandBuilder; use crate::gen::n2_errors::{N2Error, N2ErrorKind}; -pub fn format_package(dir: &Path) -> anyhow::Result { - let mut errors = vec![]; - let result = walk_dir(dir, &mut errors); - if result.is_ok() { - if errors.is_empty() { - return Ok(0); - } else { - for (p, e) in errors { - eprintln!("Error while formatting {}:\n{}", p.display(), e); - } - return Ok(1); - } - } - anyhow::bail!(result.err().unwrap()) -} - -fn walk_dir(dir: &Path, errors: &mut Vec<(PathBuf, String)>) -> anyhow::Result<()> { - let walker = WalkDir::new(dir).into_iter(); - for entry in walker.filter_entry(|e| !IGNORE_DIRS.contains(&e.file_name().to_str().unwrap())) { - let entry = entry.context("failed to read entry")?; - if entry.file_type().is_dir() { - continue; - } - - let p = entry.path(); - - if let Some(ext) = p.extension() { - if ext == "mbt" { - let out = Command::new("moonfmt").arg("-w").arg(p).output()?; - if !out.status.success() { - let stderr = String::from_utf8_lossy(&out.stderr).to_string(); - errors.push((p.to_path_buf(), stderr)); - } - } - } - } - Ok(()) -} - pub fn load_moon_proj( m: &ModuleDB, moonc_opt: &MooncOpt, diff --git a/crates/moonbuild/src/gen/mod.rs b/crates/moonbuild/src/gen/mod.rs index 17d84720..e6dbd9fd 100644 --- a/crates/moonbuild/src/gen/mod.rs +++ b/crates/moonbuild/src/gen/mod.rs @@ -79,15 +79,3 @@ pub struct MiAlias { pub name: String, pub alias: String, } - -impl PartialOrd for MiAlias { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.name.cmp(&other.name)) - } -} - -impl Ord for MiAlias { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.name.cmp(&other.name) - } -} diff --git a/crates/moonbuild/src/lib.rs b/crates/moonbuild/src/lib.rs index ca5c4816..447abe8b 100644 --- a/crates/moonbuild/src/lib.rs +++ b/crates/moonbuild/src/lib.rs @@ -18,8 +18,6 @@ #![warn(clippy::clone_on_ref_ptr)] -use std::io::Write; - pub mod bench; pub mod build; pub mod bundle; @@ -41,24 +39,6 @@ use sysinfo::{ProcessExt, System, SystemExt}; pub const MOON_PID_NAME: &str = ".moon.pid"; -pub fn bail_moon_check_is_running(p: &std::path::Path) -> anyhow::Result { - anyhow::bail!( - "`moon check` is already running. If you are certain it is not running, you may want to manually delete `{}` and try again.", - p.to_str().unwrap_or(MOON_PID_NAME) - ) -} - -pub fn write_current_pid( - target_dir: &std::path::Path, - pid_path: &std::path::Path, -) -> anyhow::Result<()> { - std::fs::create_dir_all(target_dir)?; - let pid = std::process::id(); - let mut pid_file = std::fs::File::create(pid_path)?; - pid_file.write_all(pid.to_string().as_bytes())?; - Ok(()) -} - pub fn watcher_is_running(pid_path: &std::path::Path) -> anyhow::Result { if !pid_path.exists() { return Ok(false); diff --git a/crates/moonutil/src/common.rs b/crates/moonutil/src/common.rs index e5ecefe3..6977a0b6 100644 --- a/crates/moonutil/src/common.rs +++ b/crates/moonutil/src/common.rs @@ -31,7 +31,6 @@ use std::fs::File; use std::io::ErrorKind; use std::io::{BufReader, BufWriter}; use std::path::{Path, PathBuf}; -use std::str::FromStr; pub const MOON_MOD_JSON: &str = "moon.mod.json"; pub const MOON_PKG_JSON: &str = "moon.pkg.json"; @@ -53,14 +52,6 @@ pub const MOON_SNAPSHOT_DELIMITER_END: &str = "----- END MOONBIT SNAPSHOT TESTIN pub const TEST_INFO_FILE: &str = "test_info.json"; -pub fn startswith_and_trim(s: &str, t: &str) -> String { - if s.starts_with(t) { - s.replacen(t, "", 1) - } else { - s.into() - } -} - #[derive(Debug, thiserror::Error)] pub enum SourceError { #[error("`source` should not contain invalid chars `{0:?}`")] @@ -164,9 +155,10 @@ pub fn read_package_desc_file_in_dir(dir: &Path) -> anyhow::Result { .context(format!("Failed to load {:?}", dir.join(MOON_PKG_JSON))) } -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Default)] #[repr(u8)] pub enum OutputFormat { + #[default] Wat, Wasm, Js, @@ -275,24 +267,7 @@ impl TargetBackend { } } -impl FromStr for TargetBackend { - type Err = &'static str; - - fn from_str(s: &str) -> Result { - match s { - "wasm" => Ok(Self::Wasm), - "wasm-gc" => Ok(Self::WasmGC), - "js" => Ok(Self::Js), - _ => Err("invalid target backend"), - } - } -} - -pub fn is_slash(c: char) -> bool { - c == '/' || c == '\\' -} - -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default)] pub struct BuildPackageFlags { pub debug_flag: bool, pub source_map: bool, @@ -305,12 +280,6 @@ pub struct BuildPackageFlags { pub target_backend: TargetBackend, } -impl Default for BuildPackageFlags { - fn default() -> Self { - Self::new() - } -} - impl BuildPackageFlags { pub fn new() -> Self { Self { @@ -325,7 +294,7 @@ impl BuildPackageFlags { } } -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, Default)] pub struct LinkCoreFlags { pub debug_flag: bool, pub source_map: bool, @@ -333,12 +302,6 @@ pub struct LinkCoreFlags { pub target_backend: TargetBackend, } -impl Default for LinkCoreFlags { - fn default() -> Self { - Self::new() - } -} - impl LinkCoreFlags { pub fn new() -> Self { Self { @@ -384,24 +347,6 @@ pub struct TestOpt { } impl TestOpt { - pub fn to_command(&self) -> Vec { - let mut command_str = Vec::new(); - if let Some(filter_package) = &self.filter_package { - command_str.push("--package".into()); - filter_package.iter().for_each(|pkg| { - command_str.push(pkg.display().to_string()); - }); - } - if let Some(filter_file) = &self.filter_file { - command_str.push("--file".into()); - command_str.push(filter_file.into()); - } - if let Some(filter_index) = self.filter_index { - command_str.push("--index".into()); - command_str.push(filter_index.to_string()); - } - command_str - } pub fn get_package_filter(&self) -> impl Fn(&Package) -> bool + '_ { move |pkg| { if let Some(ref filter_package) = self.filter_package { @@ -479,11 +424,6 @@ pub struct VersionItem { // Copy from https://github.com/rust-lang/cargo/blob/e52e360/crates/cargo-test-support/src/paths.rs#L113 pub trait CargoPathExt { fn rm_rf(&self); - fn mkdir_p(&self); - - /// Returns a list of all files and directories underneath the given - /// directory, recursively, including the starting path. - fn ls_r(&self) -> Vec; } impl CargoPathExt for Path { @@ -508,41 +448,6 @@ impl CargoPathExt for Path { panic!("failed to remove {:?}: {:?}", self, e) } } - - fn mkdir_p(&self) { - fs::create_dir_all(self) - .unwrap_or_else(|e| panic!("failed to mkdir_p {}: {}", self.display(), e)) - } - - fn ls_r(&self) -> Vec { - walkdir::WalkDir::new(self) - .sort_by_file_name() - .into_iter() - .filter_map(|e| e.map(|e| e.path().to_owned()).ok()) - .collect() - } -} - -pub fn get_src_dst_dir(matches: &clap::ArgMatches) -> anyhow::Result<(PathBuf, PathBuf)> { - let default_source_dir = dunce::canonicalize(PathBuf::from(".")).unwrap(); - let source_dir = matches - .get_one::("source-dir") - .unwrap_or(&default_source_dir); - let default_target_dir = source_dir.join("target"); - - if !check_moon_mod_exists(source_dir) { - bail!("could not find `{}`", MOON_MOD_JSON); - } - - let target_dir = matches - .get_one::("target-dir") - .unwrap_or(&default_target_dir); - if !target_dir.exists() { - std::fs::create_dir_all(target_dir).context("failed to create target directory")?; - } - - let target_dir = dunce::canonicalize(target_dir).context("failed to set target directory")?; - Ok((source_dir.into(), target_dir)) } #[derive(Debug, Clone, PartialEq, Eq, Copy, Default)]