Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Clippy Warnings + Error Handling #99

Merged
merged 7 commits into from
Apr 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
564 changes: 232 additions & 332 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[toolchain]
channel = "stable"
21 changes: 9 additions & 12 deletions src/bsconfig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,15 +172,13 @@ pub fn flatten_flags(flags: &Option<Vec<OneOrMore<String>>>) -> Vec<String> {
None => vec![],
Some(xs) => xs
.iter()
.map(|x| match x {
.flat_map(|x| match x {
OneOrMore::Single(y) => vec![y.to_owned()],
OneOrMore::Multiple(ys) => ys.to_owned(),
})
.flatten()
.collect::<Vec<String>>()
.iter()
.map(|str| str.split(" "))
.flatten()
.flat_map(|str| str.split(' '))
.map(|str| str.to_string())
.collect::<Vec<String>>(),
}
Expand All @@ -197,9 +195,9 @@ pub fn flatten_ppx_flags(
None => vec![],
Some(xs) => xs
.iter()
.map(|x| match x {
.flat_map(|x| match x {
OneOrMore::Single(y) => {
let first_character = y.chars().nth(0);
let first_character = y.chars().next();
match first_character {
Some('.') => {
vec![
Expand All @@ -210,9 +208,9 @@ pub fn flatten_ppx_flags(
_ => vec!["-ppx".to_string(), node_modules_dir.to_owned() + "/" + y],
}
}
OneOrMore::Multiple(ys) if ys.len() == 0 => vec![],
OneOrMore::Multiple(ys) if ys.is_empty() => vec![],
OneOrMore::Multiple(ys) => {
let first_character = ys[0].chars().nth(0);
let first_character = ys[0].chars().next();
let ppx = match first_character {
Some('.') => node_modules_dir.to_owned() + "/" + package_name + "/" + &ys[0],
_ => node_modules_dir.to_owned() + "/" + &ys[0],
Expand All @@ -227,7 +225,6 @@ pub fn flatten_ppx_flags(
]
}
})
.flatten()
.collect::<Vec<String>>(),
}
}
Expand All @@ -243,14 +240,14 @@ pub fn read(path: String) -> Config {
}

fn check_if_rescript11_or_higher(version: &str) -> bool {
version.split(".").nth(0).unwrap().parse::<usize>().unwrap() >= 11
version.split('.').next().unwrap().parse::<usize>().unwrap() >= 11
}

fn namespace_from_package_name(package_name: &str) -> String {
package_name
.to_owned()
.replace("@", "")
.replace("/", "_")
.replace('@', "")
.replace('/', "_")
.to_case(Case::Pascal)
}

Expand Down
82 changes: 69 additions & 13 deletions src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use build_types::*;
use console::style;
use indicatif::{ProgressBar, ProgressStyle};
use serde::Serialize;
use std::fmt;
use std::io::{stdout, Write};
use std::path::PathBuf;
use std::time::{Duration, Instant};
Expand Down Expand Up @@ -79,7 +80,7 @@ pub fn get_compiler_args(path: &str, rescript_version: Option<String>) -> String
&workspace_root,
workspace_root.as_ref().unwrap_or(&package_root),
);
let is_interface = filename.ends_with("i");
let is_interface = filename.ends_with('i');
let has_interface = if is_interface {
true
} else {
Expand All @@ -106,11 +107,28 @@ pub fn get_compiler_args(path: &str, rescript_version: Option<String>) -> String
.unwrap()
}

pub fn initialize_build<'a>(
#[derive(Debug, Clone)]
pub enum InitializeBuildError {
PackageDependencyValidation,
}

impl fmt::Display for InitializeBuildError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::PackageDependencyValidation => write!(
f,
"{} {}Could not Validate Package Dependencies",
LINE_CLEAR, CROSS,
),
}
}
}

pub fn initialize_build(
default_timing: Option<Duration>,
filter: &Option<regex::Regex>,
path: &str,
) -> Result<BuildState, ()> {
) -> Result<BuildState, InitializeBuildError> {
let project_root = helpers::get_abs_path(path);
let workspace_root = helpers::get_workspace_root(&project_root);
let bsc_path = helpers::get_bsc(&project_root, workspace_root.to_owned());
Expand All @@ -120,7 +138,7 @@ pub fn initialize_build<'a>(
print!("{}{}Building package tree...", style("[1/7]").bold().dim(), TREE);
let _ = stdout().flush();
let timing_package_tree = Instant::now();
let packages = packages::make(&filter, &project_root, &workspace_root);
let packages = packages::make(filter, &project_root, &workspace_root);
let timing_package_tree_elapsed = timing_package_tree.elapsed();

println!(
Expand All @@ -134,7 +152,7 @@ pub fn initialize_build<'a>(
);

if !packages::validate_packages_dependencies(&packages) {
return Err(());
return Err(InitializeBuildError::PackageDependencyValidation);
}

let timing_source_files = Instant::now();
Expand Down Expand Up @@ -208,12 +226,27 @@ fn format_step(current: usize, total: usize) -> console::StyledObject<String> {
style(format!("[{}/{}]", current, total)).bold().dim()
}

#[derive(Debug, Clone)]
pub enum IncrementalBuildError {
SourceFileParseError,
CompileError,
}

impl fmt::Display for IncrementalBuildError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::SourceFileParseError => write!(f, "{} {}Could not parse Source Files", LINE_CLEAR, CROSS,),
Self::CompileError => write!(f, "{} {}Failed to Compile. See Errors Above", LINE_CLEAR, CROSS,),
}
}
}

pub fn incremental_build(
build_state: &mut BuildState,
default_timing: Option<Duration>,
initial_build: bool,
only_incremental: bool,
) -> Result<(), ()> {
) -> Result<(), IncrementalBuildError> {
logs::initialize(&build_state.packages);
let num_dirty_modules = build_state.modules.values().filter(|m| is_dirty(m)).count() as u64;
let pb = ProgressBar::new(num_dirty_modules);
Expand Down Expand Up @@ -254,7 +287,7 @@ pub fn incremental_build(
default_timing.unwrap_or(timing_ast_elapsed).as_secs_f64()
);
print!("{}", &err);
return Err(());
return Err(IncrementalBuildError::SourceFileParseError);
}
}
let timing_deps = Instant::now();
Expand Down Expand Up @@ -307,7 +340,7 @@ pub fn incremental_build(

logs::finalize(&build_state.packages);
pb.finish();
if compile_errors.len() > 0 {
if !compile_errors.is_empty() {
if helpers::contains_ascii_characters(&compile_warnings) {
println!("{}", &compile_warnings);
}
Expand All @@ -326,7 +359,7 @@ pub fn incremental_build(
module.compile_dirty = true;
}
}
return Err(());
Err(IncrementalBuildError::CompileError)
} else {
println!(
"{}{} {}Compiled {} modules in {:.2}s",
Expand All @@ -343,14 +376,37 @@ pub fn incremental_build(
}
}

pub fn build(filter: &Option<regex::Regex>, path: &str, no_timing: bool) -> Result<BuildState, ()> {
#[derive(Debug, Clone)]
pub enum BuildError {
InitializeBuild(InitializeBuildError),
IncrementalBuild(IncrementalBuildError),
}

impl fmt::Display for BuildError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::InitializeBuild(e) => {
write!(f, "{} {}Error Initializing Build: {}", LINE_CLEAR, CROSS, e)
}
Self::IncrementalBuild(e) => write!(
f,
"{} {}Error Running Incremental Build: {}",
LINE_CLEAR, CROSS, e
),
}
}
}

pub fn build(filter: &Option<regex::Regex>, path: &str, no_timing: bool) -> Result<BuildState, BuildError> {
let default_timing: Option<std::time::Duration> = if no_timing {
Some(std::time::Duration::new(0.0 as u64, 0.0 as u32))
} else {
None
};
let timing_total = Instant::now();
let mut build_state = initialize_build(default_timing, filter, path)?;
let mut build_state =
initialize_build(default_timing, filter, path).map_err(BuildError::InitializeBuild)?;

match incremental_build(&mut build_state, default_timing, true, false) {
Ok(_) => {
let timing_total_elapsed = timing_total.elapsed();
Expand All @@ -363,9 +419,9 @@ pub fn build(filter: &Option<regex::Regex>, path: &str, no_timing: bool) -> Resu
clean::cleanup_after_build(&build_state);
Ok(build_state)
}
Err(_) => {
Err(e) => {
clean::cleanup_after_build(&build_state);
Err(())
Err(BuildError::IncrementalBuild(e))
}
}
}
8 changes: 3 additions & 5 deletions src/build/build_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,10 @@ pub struct Module {

impl Module {
pub fn is_mlmap(&self) -> bool {
match self.source_type {
SourceType::MlMap(_) => true,
_ => false,
}
matches!(self.source_type, SourceType::MlMap(_))
}
pub fn get_interface<'a>(&'a self) -> &'a Option<Interface> {

pub fn get_interface(&self) -> &Option<Interface> {
match &self.source_type {
SourceType::SourceFile(source_file) => &source_file.interface,
_ => &None,
Expand Down
Loading
Loading