Skip to content

Commit

Permalink
internal: clean up unused code (#349)
Browse files Browse the repository at this point in the history
  • Loading branch information
lijunchen authored Sep 27, 2024
1 parent 6cc8cf0 commit 3045405
Show file tree
Hide file tree
Showing 4 changed files with 5 additions and 175 deletions.
45 changes: 1 addition & 44 deletions crates/moonbuild/src/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -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<i32> {
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,
Expand Down
12 changes: 0 additions & 12 deletions crates/moonbuild/src/gen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,3 @@ pub struct MiAlias {
pub name: String,
pub alias: String,
}

impl PartialOrd for MiAlias {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.name.cmp(&other.name))
}
}

impl Ord for MiAlias {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.name.cmp(&other.name)
}
}
20 changes: 0 additions & 20 deletions crates/moonbuild/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@

#![warn(clippy::clone_on_ref_ptr)]

use std::io::Write;

pub mod bench;
pub mod build;
pub mod bundle;
Expand All @@ -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<i32> {
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<bool> {
if !pid_path.exists() {
return Ok(false);
Expand Down
103 changes: 4 additions & 99 deletions crates/moonutil/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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:?}`")]
Expand Down Expand Up @@ -164,9 +155,10 @@ pub fn read_package_desc_file_in_dir(dir: &Path) -> anyhow::Result<MoonPkg> {
.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,
Expand Down Expand Up @@ -275,24 +267,7 @@ impl TargetBackend {
}
}

impl FromStr for TargetBackend {
type Err = &'static str;

fn from_str(s: &str) -> Result<Self, Self::Err> {
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,
Expand All @@ -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 {
Expand All @@ -325,20 +294,14 @@ impl BuildPackageFlags {
}
}

#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone, Copy, Default)]
pub struct LinkCoreFlags {
pub debug_flag: bool,
pub source_map: bool,
pub output_format: OutputFormat,
pub target_backend: TargetBackend,
}

impl Default for LinkCoreFlags {
fn default() -> Self {
Self::new()
}
}

impl LinkCoreFlags {
pub fn new() -> Self {
Self {
Expand Down Expand Up @@ -384,24 +347,6 @@ pub struct TestOpt {
}

impl TestOpt {
pub fn to_command(&self) -> Vec<String> {
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 {
Expand Down Expand Up @@ -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<PathBuf>;
}

impl CargoPathExt for Path {
Expand All @@ -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<PathBuf> {
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::<PathBuf>("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::<PathBuf>("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)]
Expand Down

0 comments on commit 3045405

Please sign in to comment.