Skip to content

Improve Error Handling / Less Panics #143

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

Merged
merged 9 commits into from
Nov 20, 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
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ clap = { version = "4.3.17", features = ["derive"] }
sysinfo = "0.29.10"
ctrlc = "3.4.4"
clap-verbosity-flag = "2.2.2"
anyhow = "1.0.93"


[profile.release]
Expand Down
86 changes: 31 additions & 55 deletions src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::helpers::emojis::*;
use crate::helpers::{self, get_workspace_root};
use crate::sourcedirs;
use ahash::AHashSet;
use anyhow::{anyhow, Result};
use build_types::*;
use console::style;
use indicatif::{ProgressBar, ProgressStyle};
Expand Down Expand Up @@ -54,15 +55,19 @@ pub struct CompilerArgs {
pub parser_args: Vec<String>,
}

pub fn get_compiler_args(path: &str, rescript_version: Option<String>, bsc_path: Option<String>) -> String {
pub fn get_compiler_args(
path: &str,
rescript_version: Option<String>,
bsc_path: Option<String>,
) -> Result<String> {
let filename = &helpers::get_abs_path(path);
let package_root = helpers::get_abs_path(
&helpers::get_nearest_bsconfig(&std::path::PathBuf::from(path)).expect("Couldn't find package root"),
&helpers::get_nearest_config(&std::path::PathBuf::from(path)).expect("Couldn't find package root"),
);
let workspace_root = get_workspace_root(&package_root).map(|p| helpers::get_abs_path(&p));
let root_rescript_config =
packages::read_bsconfig(&workspace_root.to_owned().unwrap_or(package_root.to_owned()));
let rescript_config = packages::read_bsconfig(&package_root);
packages::read_config(&workspace_root.to_owned().unwrap_or(package_root.to_owned()))?;
let rescript_config = packages::read_config(&package_root)?;
let rescript_version = if let Some(rescript_version) = rescript_version {
rescript_version
} else {
Expand Down Expand Up @@ -111,28 +116,13 @@ pub fn get_compiler_args(path: &str, rescript_version: Option<String>, bsc_path:
&workspace_root,
&None,
);
serde_json::to_string_pretty(&CompilerArgs {

let result = serde_json::to_string_pretty(&CompilerArgs {
compiler_args,
parser_args,
})
.unwrap()
}

#[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,
),
}
}
Ok(result)
}

pub fn initialize_build(
Expand All @@ -141,14 +131,14 @@ pub fn initialize_build(
show_progress: bool,
path: &str,
bsc_path: Option<String>,
) -> Result<BuildState, InitializeBuildError> {
) -> Result<BuildState> {
let project_root = helpers::get_abs_path(path);
let workspace_root = helpers::get_workspace_root(&project_root);
let bsc_path = match bsc_path {
Some(bsc_path) => bsc_path,
None => helpers::get_bsc(&project_root, workspace_root.to_owned()),
};
let root_config_name = packages::get_package_name(&project_root);
let root_config_name = packages::get_package_name(&project_root)?;
let rescript_version = helpers::get_rescript_version(&bsc_path);

if show_progress {
Expand All @@ -157,7 +147,7 @@ pub fn initialize_build(
}

let timing_package_tree = Instant::now();
let packages = packages::make(filter, &project_root, &workspace_root);
let packages = packages::make(filter, &project_root, &workspace_root, show_progress)?;
let timing_package_tree_elapsed = timing_package_tree.elapsed();

if show_progress {
Expand All @@ -173,7 +163,7 @@ pub fn initialize_build(
}

if !packages::validate_packages_dependencies(&packages) {
return Err(InitializeBuildError::PackageDependencyValidation);
return Err(anyhow!("Failed to validate package dependencies"));
}

let timing_source_files = Instant::now();
Expand Down Expand Up @@ -263,14 +253,19 @@ fn format_step(current: usize, total: usize) -> console::StyledObject<String> {
#[derive(Debug, Clone)]
pub enum IncrementalBuildError {
SourceFileParseError,
CompileError,
CompileError(Option<String>),
}

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,),
Self::CompileError(Some(e)) => {
write!(f, "{} {}Failed to Compile. Error: {e}", LINE_CLEAR, CROSS,)
}
Self::CompileError(None) => {
write!(f, "{} {}Failed to Compile. See Errors Above", LINE_CLEAR, CROSS,)
}
}
}
}
Expand Down Expand Up @@ -380,7 +375,9 @@ pub fn incremental_build(
};

let (compile_errors, compile_warnings, num_compiled_modules) =
compile::compile(build_state, || pb.inc(1), |size| pb.set_length(size));
compile::compile(build_state, || pb.inc(1), |size| pb.set_length(size))
.map_err(|e| IncrementalBuildError::CompileError(Some(e.to_string())))?;

let compile_duration = start_compiling.elapsed();

logs::finalize(&build_state.packages);
Expand Down Expand Up @@ -409,7 +406,7 @@ pub fn incremental_build(
module.compile_dirty = true;
}
}
Err(IncrementalBuildError::CompileError)
Err(IncrementalBuildError::CompileError(None))
} else {
if show_progress {
println!(
Expand All @@ -428,27 +425,6 @@ pub fn incremental_build(
}
}

#[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
),
}
}
}

// write build.ninja files in the packages after a non-incremental build
// this is necessary to bust the editor tooling cache. The editor tooling
// is watching this file.
Expand All @@ -470,15 +446,15 @@ pub fn build(
no_timing: bool,
create_sourcedirs: bool,
bsc_path: Option<String>,
) -> Result<BuildState, BuildError> {
) -> Result<BuildState> {
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, show_progress, path, bsc_path)
.map_err(BuildError::InitializeBuild)?;
.map_err(|e| anyhow!("Could not initialize build. Error: {e}"))?;

match incremental_build(
&mut build_state,
Expand All @@ -505,7 +481,7 @@ pub fn build(
Err(e) => {
clean::cleanup_after_build(&build_state);
write_build_ninja(&build_state);
Err(BuildError::IncrementalBuild(e))
Err(anyhow!("Incremental build failed. Error: {e}"))
}
}
}
12 changes: 11 additions & 1 deletion src/build/build_types.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::build::packages::{Namespace, Package};
use ahash::{AHashMap, AHashSet};
use std::time::SystemTime;
use std::{fmt::Display, time::SystemTime};

#[derive(Debug, Clone, PartialEq)]
pub enum ParseState {
Expand Down Expand Up @@ -52,6 +52,15 @@ pub enum SourceType {
MlMap(MlMap),
}

impl Display for SourceType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SourceType::SourceFile(_) => write!(f, "SourceFile"),
SourceType::MlMap(_) => write!(f, "MlMap"),
}
}
}

#[derive(Debug, Clone)]
pub struct Module {
pub source_type: SourceType,
Expand Down Expand Up @@ -119,6 +128,7 @@ impl BuildState {
deps_initialized: false,
}
}

pub fn insert_module(&mut self, module_name: &str, module: Module) {
self.modules.insert(module_name.to_owned(), module);
self.module_names.insert(module_name.to_owned());
Expand Down
11 changes: 7 additions & 4 deletions src/build/clean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use super::packages;
use crate::helpers;
use crate::helpers::emojis::*;
use ahash::AHashSet;
use anyhow::Result;
use console::style;
use rayon::prelude::*;
use std::io::Write;
Expand Down Expand Up @@ -74,7 +75,7 @@ pub fn clean_mjs_files(build_state: &BuildState) {
.join(&source_file.implementation.path)
.to_string_lossy()
.to_string(),
root_package.bsconfig.get_suffix(),
root_package.config.get_suffix(),
))
}
_ => None,
Expand Down Expand Up @@ -318,11 +319,11 @@ pub fn cleanup_after_build(build_state: &BuildState) {
});
}

pub fn clean(path: &str, show_progress: bool, bsc_path: Option<String>) {
pub fn clean(path: &str, show_progress: bool, bsc_path: Option<String>) -> Result<()> {
let project_root = helpers::get_abs_path(path);
let workspace_root = helpers::get_workspace_root(&project_root);
let packages = packages::make(&None, &project_root, &workspace_root);
let root_config_name = packages::get_package_name(&project_root);
let packages = packages::make(&None, &project_root, &workspace_root, show_progress)?;
let root_config_name = packages::get_package_name(&project_root)?;
let bsc_path = match bsc_path {
Some(bsc_path) => bsc_path,
None => helpers::get_bsc(&project_root, workspace_root.to_owned()),
Expand Down Expand Up @@ -399,4 +400,6 @@ pub fn clean(path: &str, show_progress: bool, bsc_path: Option<String>) {
);
let _ = std::io::stdout().flush();
}

Ok(())
}
Loading
Loading