diff --git a/src/lib/cli.rs b/src/lib/cli.rs index b4768fb2..dfa6c3a5 100644 --- a/src/lib/cli.rs +++ b/src/lib/cli.rs @@ -96,15 +96,8 @@ pub fn run(cli_args: &CliArgs, global_config: &GlobalConfig) -> Result<(), Cargo let env = cli_args.env.clone(); let experimental = cli_args.experimental; - let descriptor_load_result = descriptor::load(&build_file, force_makefile, env, experimental); - - let config = match descriptor_load_result { - Ok(config) => config, - Err(ref error) => { - error!("{}", error); - panic!("{}", error); - } - }; + let config = descriptor::load(&build_file, force_makefile, env, experimental)?; + let mut time_summary_vec = vec![]; time_summary::add( &mut time_summary_vec, @@ -141,7 +134,7 @@ pub fn run(cli_args: &CliArgs, global_config: &GlobalConfig) -> Result<(), Cargo cli_args.hide_uninteresting, ) } else if cli_args.diff_execution_plan { - let default_config = descriptor::load_internal_descriptors(true, experimental, None); + let default_config = descriptor::load_internal_descriptors(true, experimental, None)?; cli_commands::diff_steps::run( &default_config, &config, diff --git a/src/lib/cli_commands/diff_steps.rs b/src/lib/cli_commands/diff_steps.rs index ecf31d9e..f2b0c21b 100644 --- a/src/lib/cli_commands/diff_steps.rs +++ b/src/lib/cli_commands/diff_steps.rs @@ -64,11 +64,11 @@ pub(crate) fn run( let internal_file = create_file( &move |file: &mut File| write_as_string(&internal_execution_plan, &file), "toml", - ); + )?; let external_file = create_file( &move |file: &mut File| write_as_string(&external_execution_plan, &file), "toml", - ); + )?; info!("Printing diff..."); command::run_command( diff --git a/src/lib/cli_commands/list_steps_test.rs b/src/lib/cli_commands/list_steps_test.rs index 1ddbb4a2..4432c4b6 100644 --- a/src/lib/cli_commands/list_steps_test.rs +++ b/src/lib/cli_commands/list_steps_test.rs @@ -27,7 +27,7 @@ fn check( let mut path = PathBuf::new(); path.push(&file); - let actual = io::read_text_file(&path); + let actual = io::read_text_file(&path).unwrap(); io::delete_file(&file); expect.assert_eq(&actual); diff --git a/src/lib/descriptor/cargo_alias.rs b/src/lib/descriptor/cargo_alias.rs index e7a5653d..a18402d1 100644 --- a/src/lib/descriptor/cargo_alias.rs +++ b/src/lib/descriptor/cargo_alias.rs @@ -7,6 +7,7 @@ #[path = "cargo_alias_test.rs"] mod cargo_alias_test; +use crate::error::CargoMakeError; use crate::io; use crate::types::{InstallCrate, Task}; use std::collections::HashMap; @@ -24,13 +25,13 @@ struct CargoConfig { alias: Option>, } -fn load_from_file(file: &str) -> Vec<(String, Task)> { +fn load_from_file(file: &str) -> Result, CargoMakeError> { let file_path = Path::new(file); let mut tasks = vec![]; if file_path.exists() { if file_path.is_file() { - let text = io::read_text_file(&file_path.to_path_buf()); + let text = io::read_text_file(&file_path.to_path_buf())?; if !text.is_empty() { let cargo_config: CargoConfig = match toml::from_str(&text) { @@ -57,9 +58,9 @@ fn load_from_file(file: &str) -> Vec<(String, Task)> { } } - tasks + Ok(tasks) } -pub(crate) fn load() -> Vec<(String, Task)> { +pub(crate) fn load() -> Result, CargoMakeError> { load_from_file("./.cargo/config.toml") } diff --git a/src/lib/descriptor/cargo_alias_test.rs b/src/lib/descriptor/cargo_alias_test.rs index 6eb05f08..0a258043 100644 --- a/src/lib/descriptor/cargo_alias_test.rs +++ b/src/lib/descriptor/cargo_alias_test.rs @@ -2,28 +2,28 @@ use super::*; #[test] fn load_from_file_no_file() { - let tasks = load_from_file("./badfile.toml"); + let tasks = load_from_file("./badfile.toml").unwrap(); assert!(tasks.is_empty()); } #[test] fn load_from_file_parse_error() { - let tasks = load_from_file("./src/lib/test/cargo/invalid_config.toml"); + let tasks = load_from_file("./src/lib/test/cargo/invalid_config.toml").unwrap(); assert!(tasks.is_empty()); } #[test] fn load_from_file_no_alias_data() { - let tasks = load_from_file("./Cargo.toml"); + let tasks = load_from_file("./Cargo.toml").unwrap(); assert!(tasks.is_empty()); } #[test] fn load_from_file_aliases_found() { - let tasks = load_from_file("./src/lib/test/cargo/config.toml"); + let tasks = load_from_file("./src/lib/test/cargo/config.toml").unwrap(); assert_eq!(tasks.len(), 4); diff --git a/src/lib/descriptor/descriptor_deserializer.rs b/src/lib/descriptor/descriptor_deserializer.rs index b7bf4a65..02d741a8 100644 --- a/src/lib/descriptor/descriptor_deserializer.rs +++ b/src/lib/descriptor/descriptor_deserializer.rs @@ -6,9 +6,13 @@ #[path = "descriptor_deserializer_test.rs"] mod descriptor_deserializer_test; +use crate::error::CargoMakeError; use crate::types::{Config, ExternalConfig}; -pub(crate) fn load_config(descriptor_string: &str, validate: bool) -> Config { +pub(crate) fn load_config( + descriptor_string: &str, + validate: bool, +) -> Result { let config: Config = if validate { let deserializer = toml::de::Deserializer::new(descriptor_string); @@ -18,7 +22,7 @@ pub(crate) fn load_config(descriptor_string: &str, validate: bool) -> Config { Ok(value) => value, Err(error) => { error!("Unable to parse internal descriptor: {}", error); - panic!("Unable to parse internal descriptor: {}", error); + return Err(CargoMakeError::DescriptorParseFailed(error.to_string())); } } } else { @@ -26,26 +30,30 @@ pub(crate) fn load_config(descriptor_string: &str, validate: bool) -> Config { Ok(value) => value, Err(error) => { error!("Unable to parse internal descriptor: {}", error); - panic!("Unable to parse internal descriptor: {}", error); + return Err(CargoMakeError::DescriptorParseFailed(error.to_string())); } } }; - config + Ok(config) } -pub(crate) fn load_external_config(descriptor_string: &str, file: &str) -> ExternalConfig { +pub(crate) fn load_external_config( + descriptor_string: &str, + file: &str, +) -> Result { let deserializer = toml::de::Deserializer::new(descriptor_string); - let config: ExternalConfig = match serde_ignored::deserialize(deserializer, |path| { + match serde_ignored::deserialize(deserializer, |path| { warn!("Found unknown key: {} in file: {}", path, file); }) { - Ok(value) => value, + Ok(value) => Ok(value), Err(error) => { error!("Unable to parse external file: {:#?}, {}", &file, error); - panic!("Unable to parse external file: {:#?}, {}", &file, error); + return Err(CargoMakeError::ParseFileFailed( + String::from(file), + error.to_string(), + )); } - }; - - config + } } diff --git a/src/lib/descriptor/descriptor_deserializer_test.rs b/src/lib/descriptor/descriptor_deserializer_test.rs index f61d2494..6e6a67b6 100644 --- a/src/lib/descriptor/descriptor_deserializer_test.rs +++ b/src/lib/descriptor/descriptor_deserializer_test.rs @@ -3,17 +3,17 @@ use crate::descriptor::makefiles; #[test] fn load_config_base() { - load_config(makefiles::BASE, true); + load_config(makefiles::BASE, true).unwrap(); } #[test] fn load_config_stable() { - load_config(makefiles::STABLE, true); + load_config(makefiles::STABLE, true).unwrap(); } #[test] fn load_config_beta() { - load_config(makefiles::BETA, true); + load_config(makefiles::BETA, true).unwrap(); } #[test] @@ -35,7 +35,8 @@ description = "Empty Task" category2 = "Tools" "#, true, - ); + ) + .unwrap(); } #[test] @@ -56,7 +57,8 @@ description = "Empty Task" category2 = "Tools" "#, false, - ); + ) + .unwrap(); assert!(config.tasks.contains_key("empty")); } @@ -70,7 +72,8 @@ description = "Empty Task" category2 = "Tools" "#, "somefile", - ); + ) + .unwrap(); assert!(config.tasks.unwrap().contains_key("empty")); } diff --git a/src/lib/descriptor/makefiles/mod_test.rs b/src/lib/descriptor/makefiles/mod_test.rs index a4c950a9..7edd059a 100644 --- a/src/lib/descriptor/makefiles/mod_test.rs +++ b/src/lib/descriptor/makefiles/mod_test.rs @@ -1,5 +1,6 @@ use crate::condition; use crate::descriptor; +use crate::error::CargoMakeError; use crate::runner; use crate::scriptengine; use crate::scriptengine::EngineType; @@ -10,7 +11,7 @@ use rust_info::types::RustInfo; use std::cell::RefCell; use std::rc::Rc; -fn load_descriptor() -> Config { +fn load_descriptor() -> Result { descriptor::load_internal_descriptors(true, false, None) } @@ -42,7 +43,7 @@ fn create_flow_info(config: &Config) -> FlowInfo { fn makefile_task_condition_test(name: &str, expect_enabled: bool, linux_only: bool, ci_only: bool) { if !linux_only || test::is_linux() { - let config = load_descriptor(); + let config = load_descriptor().unwrap(); let task = get_task(name, &config); let flow_info = create_flow_info(&config); let step = Step { @@ -75,14 +76,15 @@ fn makefile_task_disabled_test(name: &str, linux_only: bool) { } fn makefile_task_script_engine_test(name: &str, engine: EngineType) { - let config = load_descriptor(); + let config = load_descriptor().unwrap(); let task = get_task(name, &config); let output = scriptengine::get_engine_type( &task.script.unwrap(), &task.script_runner, &task.script_extension, - ); + ) + .unwrap(); assert_eq!(output, engine); } @@ -90,7 +92,7 @@ fn makefile_task_script_engine_test(name: &str, engine: EngineType) { #[test] fn makefile_coverage_test() { if test::is_linux() { - let config = load_descriptor(); + let config = load_descriptor().unwrap(); let task = get_task("coverage", &config); let run_task_info = task.run_task.unwrap(); @@ -167,7 +169,7 @@ fn makefile_build_file_increment_no_file_test() { let name = "build-file-increment"; - let config = load_descriptor(); + let config = load_descriptor().unwrap(); let task = get_task(name, &config); let flow_info = create_flow_info(&config); @@ -199,7 +201,7 @@ fn makefile_build_file_increment_file_exists_test() { let name = "build-file-increment"; - let config = load_descriptor(); + let config = load_descriptor().unwrap(); let task = get_task(name, &config); let flow_info = create_flow_info(&config); @@ -236,7 +238,7 @@ fn makefile_build_file_increment_panic_invalid_data_test() { let name = "build-file-increment"; - let config = load_descriptor(); + let config = load_descriptor().unwrap(); let task = get_task(name, &config); let flow_info = create_flow_info(&config); diff --git a/src/lib/descriptor/mod.rs b/src/lib/descriptor/mod.rs index d6ff1780..0a84fe4b 100755 --- a/src/lib/descriptor/mod.rs +++ b/src/lib/descriptor/mod.rs @@ -318,12 +318,12 @@ fn load_external_descriptor( envmnt::set("CARGO_MAKE_MAKEFILE_PATH", &absolute_file_path); } - let external_descriptor = io::read_text_file(&file_path); + let external_descriptor = io::read_text_file(&file_path)?; check_makefile_min_version(&external_descriptor)?; let mut file_config = - descriptor_deserializer::load_external_config(&external_descriptor, &file_path_string); + descriptor_deserializer::load_external_config(&external_descriptor, &file_path_string)?; debug!("Loaded external config: {:#?}", &file_config); file_config = add_file_location_info(file_config, &absolute_file_path); @@ -349,7 +349,10 @@ fn load_external_descriptor( } } else if force { error!("Descriptor file: {:#?} not found.", &file_path); - panic!("Descriptor file: {:#?} not found.", &file_path); + Err(CargoMakeError::NotFound(format!( + "Descriptor file: {:#?} not found.", + &file_path + ))) } else { debug!("External file not found or is not a file, skipping."); @@ -361,7 +364,7 @@ pub(crate) fn load_internal_descriptors( stable: bool, experimental: bool, modify_config: Option, -) -> Config { +) -> Result { debug!("Loading base tasks."); let base_descriptor = if stable { @@ -370,7 +373,7 @@ pub(crate) fn load_internal_descriptors( makefiles::BASE }; - let mut base_config = descriptor_deserializer::load_config(&base_descriptor, false); + let mut base_config = descriptor_deserializer::load_config(&base_descriptor, false)?; debug!("Loaded base config: {:#?}", &base_config); if experimental { @@ -378,7 +381,7 @@ pub(crate) fn load_internal_descriptors( let experimental_descriptor = makefiles::BETA; let experimental_config = - descriptor_deserializer::load_config(&experimental_descriptor, false); + descriptor_deserializer::load_config(&experimental_descriptor, false)?; debug!("Loaded experimental config: {:#?}", &experimental_config); let mut base_tasks = base_config.tasks; @@ -409,7 +412,7 @@ pub(crate) fn load_internal_descriptors( None => (), }; - base_config + Ok(base_config) } fn merge_base_config_and_external_config( @@ -510,7 +513,7 @@ fn load_descriptors( experimental: bool, modify_core_tasks: Option, ) -> Result { - let default_config = load_internal_descriptors(stable, experimental, modify_core_tasks); + let default_config = load_internal_descriptors(stable, experimental, modify_core_tasks)?; let mut external_config = load_external_descriptor(".", file_name, force, true)?; @@ -551,10 +554,10 @@ fn load_descriptors( Ok(config) } -fn load_cargo_aliases(config: &mut Config) { +fn load_cargo_aliases(config: &mut Config) -> Result<(), CargoMakeError> { if let Some(load_cargo_aliases) = config.config.load_cargo_aliases { if load_cargo_aliases { - let alias_tasks = cargo_alias::load(); + let alias_tasks = cargo_alias::load()?; for (name, task) in alias_tasks { match config.tasks.get(&name) { None => { @@ -566,6 +569,7 @@ fn load_cargo_aliases(config: &mut Config) { } } } + Ok(()) } /// Loads the tasks descriptor.
@@ -603,7 +607,7 @@ pub fn load( } } None => { - let core_config = load_internal_descriptors(true, experimental, modify_core_tasks); + let core_config = load_internal_descriptors(true, experimental, modify_core_tasks)?; let external_config = ExternalConfig { extend: None, config: Some(config.config), @@ -624,7 +628,7 @@ pub fn load( }; } - load_cargo_aliases(&mut config); + load_cargo_aliases(&mut config)?; if let Some(unstable_features) = &config.config.unstable_features { for feature in unstable_features { diff --git a/src/lib/descriptor/mod_test.rs b/src/lib/descriptor/mod_test.rs index dc556111..40bd9e0c 100755 --- a/src/lib/descriptor/mod_test.rs +++ b/src/lib/descriptor/mod_test.rs @@ -387,7 +387,7 @@ fn load_not_found() { #[test] fn load_internal_descriptors_no_stable() { - let config = load_internal_descriptors(false, false, None); + let config = load_internal_descriptors(false, false, None).unwrap(); let mut task = config.tasks.get("empty"); assert!(task.is_some()); @@ -397,7 +397,7 @@ fn load_internal_descriptors_no_stable() { #[test] fn load_internal_descriptors_with_stable() { - let config = load_internal_descriptors(true, false, None); + let config = load_internal_descriptors(true, false, None).unwrap(); let mut task = config.tasks.get("empty"); assert!(task.is_some()); @@ -407,7 +407,7 @@ fn load_internal_descriptors_with_stable() { #[test] fn load_internal_descriptors_no_experimental() { - let config = load_internal_descriptors(true, false, None); + let config = load_internal_descriptors(true, false, None).unwrap(); let mut task = config.tasks.get("ci-flow"); assert!(task.is_some()); @@ -417,7 +417,7 @@ fn load_internal_descriptors_no_experimental() { #[test] fn load_internal_descriptors_with_experimental() { - let config = load_internal_descriptors(true, true, None); + let config = load_internal_descriptors(true, true, None).unwrap(); let mut task = config.tasks.get("ci-flow"); assert!(task.is_some()); @@ -434,7 +434,8 @@ fn load_internal_descriptors_modify_empty() { private: None, namespace: None, }), - ); + ) + .unwrap(); let mut task = config.tasks.get("empty"); assert!(task.is_some()); @@ -453,7 +454,8 @@ fn load_internal_descriptors_modify_private() { private: Some(true), namespace: None, }), - ); + ) + .unwrap(); let mut task = config.tasks.get("empty"); assert!(task.is_some()); @@ -472,7 +474,8 @@ fn load_internal_descriptors_modify_namespace() { private: None, namespace: Some("default".to_string()), }), - ); + ) + .unwrap(); let mut task = config.tasks.get("empty"); assert!(task.is_none()); @@ -950,10 +953,10 @@ fn check_makefile_min_version_same_min_version() { #[test] fn load_cargo_aliases_no_file() { - let mut config = load_internal_descriptors(false, false, None); + let mut config = load_internal_descriptors(false, false, None).unwrap(); let count = config.tasks.len(); - load_cargo_aliases(&mut config); + load_cargo_aliases(&mut config).unwrap(); assert_eq!(count, config.tasks.len()); } @@ -961,11 +964,11 @@ fn load_cargo_aliases_no_file() { #[test] #[ignore] fn load_cargo_aliases_found() { - let mut config = load_internal_descriptors(false, false, None); + let mut config = load_internal_descriptors(false, false, None).unwrap(); let count = config.tasks.len(); setup_cwd(Some("src/lib/test/workspace1/member1")); - load_cargo_aliases(&mut config); + load_cargo_aliases(&mut config).unwrap(); setup_cwd(Some("../../../../..")); assert_eq!(count, config.tasks.len()); diff --git a/src/lib/environment/crateinfo.rs b/src/lib/environment/crateinfo.rs index 9dbc7b9f..533b704f 100755 --- a/src/lib/environment/crateinfo.rs +++ b/src/lib/environment/crateinfo.rs @@ -7,6 +7,7 @@ #[path = "crateinfo_test.rs"] mod crateinfo_test; +use crate::error::CargoMakeError; use crate::types::{CrateDependency, CrateInfo, PackageInfo, Workspace}; use cargo_metadata::camino::Utf8PathBuf; use cargo_metadata::{Metadata, MetadataCommand}; @@ -267,11 +268,11 @@ fn load_workspace_members(crate_info: &mut CrateInfo) { } /// Loads the crate info based on the Cargo.toml found in the current working directory. -pub(crate) fn load() -> CrateInfo { +pub(crate) fn load() -> Result { load_from(Path::new("Cargo.toml").to_path_buf()) } -pub(crate) fn load_from(file_path: PathBuf) -> CrateInfo { +pub(crate) fn load_from(file_path: PathBuf) -> Result { if file_path.exists() { info!("Calling cargo metadata to extract project info"); @@ -282,10 +283,7 @@ pub(crate) fn load_from(file_path: PathBuf) -> CrateInfo { let mut crate_info = convert_metadata_to_crate_info(&metadata); debug!("Reading file: {:#?}", &file_path); - let crate_info_string = match fsio::file::read_text_file(&file_path) { - Ok(content) => content, - Err(error) => panic!("Unable to open Cargo.toml, error: {}", error), - }; + let crate_info_string = fsio::file::read_text_file(&file_path)?; let crate_info_deserialized: CrateInfoMinimal = match toml::from_str(&crate_info_string) { @@ -302,7 +300,7 @@ pub(crate) fn load_from(file_path: PathBuf) -> CrateInfo { debug!("Loaded Cargo.toml: {:#?}", &crate_info); - crate_info + Ok(crate_info) } Err(error) => { warn!( @@ -310,19 +308,13 @@ pub(crate) fn load_from(file_path: PathBuf) -> CrateInfo { error ); - let crate_info_string = match fsio::file::read_text_file(&file_path) { - Ok(content) => content, - Err(error) => panic!("Unable to open Cargo.toml, error: {}", error), - }; + let crate_info_string = fsio::file::read_text_file(&file_path)?; - match toml::from_str(&crate_info_string) { - Ok(value) => value, - Err(error) => panic!("Unable to parse Cargo.toml, {}", error), - } + toml::from_str(&crate_info_string).map_err(From::from) } } } else { - CrateInfo::new() + Ok(CrateInfo::new()) } } diff --git a/src/lib/environment/crateinfo_test.rs b/src/lib/environment/crateinfo_test.rs index d58d4d7e..f832a684 100755 --- a/src/lib/environment/crateinfo_test.rs +++ b/src/lib/environment/crateinfo_test.rs @@ -5,7 +5,7 @@ use cargo_metadata::camino::Utf8Path; #[test] fn crate_info_load() { - let crate_info = load(); + let crate_info = load().unwrap(); assert!(crate_info.package.is_some()); assert!(crate_info.workspace.is_none()); @@ -787,7 +787,8 @@ fn get_crate_target_dir() { fn load_from_inherit_from_workspace_toml() { if is_min_rust_version("1.64.0") { let crate_info = - load_from(Path::new("src/lib/test/workspace-inherit/member1/Cargo.toml").to_path_buf()); + load_from(Path::new("src/lib/test/workspace-inherit/member1/Cargo.toml").to_path_buf()) + .unwrap(); let package_info = crate_info.package.unwrap(); assert_eq!(package_info.name.unwrap(), "member1"); diff --git a/src/lib/environment/mod.rs b/src/lib/environment/mod.rs index 60d2e95b..3deb8c62 100644 --- a/src/lib/environment/mod.rs +++ b/src/lib/environment/mod.rs @@ -352,8 +352,8 @@ fn setup_env_for_duckscript() { envmnt::set("CARGO_MAKE_DUCKSCRIPT_SDK_VERSION", version); } -fn setup_env_for_crate(home: Option) -> CrateInfo { - let crate_info = crateinfo::load(); +fn setup_env_for_crate(home: Option) -> Result { + let crate_info = crateinfo::load()?; let crate_info_clone = crate_info.clone(); let package_info = crate_info.package.unwrap_or(PackageInfo::new()); @@ -436,7 +436,7 @@ fn setup_env_for_crate(home: Option) -> CrateInfo { ), } - crate_info_clone + Ok(crate_info_clone) } fn setup_env_for_git_repo() -> GitInfo { @@ -526,7 +526,7 @@ fn get_base_directory_name() -> Option { } } -fn setup_env_for_project(config: &Config, crate_info: &CrateInfo) { +fn setup_env_for_project(config: &Config, crate_info: &CrateInfo) -> Result<(), CargoMakeError> { let project_name = match crate_info.package { Some(ref package) => match package.name { Some(ref name) => Some(name.to_string()), @@ -554,7 +554,7 @@ fn setup_env_for_project(config: &Config, crate_info: &CrateInfo) { let mut path = PathBuf::new(); path.push(member); path.push("Cargo.toml"); - let member_crate_info = crateinfo::load_from(path); + let member_crate_info = crateinfo::load_from(path)?; match member_crate_info.package { Some(package) => package.version, @@ -571,6 +571,8 @@ fn setup_env_for_project(config: &Config, crate_info: &CrateInfo) { }; envmnt::set_or_remove("CARGO_MAKE_PROJECT_VERSION", &project_version); + + Ok(()) } /// Sets up the env before the tasks execution. @@ -602,7 +604,7 @@ pub(crate) fn setup_env( let crate_info = if config.config.skip_crate_env_info.unwrap_or(false) { CrateInfo::new() } else { - setup_env_for_crate(home.clone()) + setup_env_for_crate(home.clone())? }; time_summary::add(time_summary_vec, "[Setup Env - Crate Info]", now); @@ -631,7 +633,7 @@ pub(crate) fn setup_env( // setup project info now = SystemTime::now(); - setup_env_for_project(config, &crate_info); + setup_env_for_project(config, &crate_info)?; time_summary::add(time_summary_vec, "[Setup Env - Project]", now); // load env vars diff --git a/src/lib/environment/mod_test.rs b/src/lib/environment/mod_test.rs index 89e791ad..b180f916 100755 --- a/src/lib/environment/mod_test.rs +++ b/src/lib/environment/mod_test.rs @@ -1376,7 +1376,7 @@ fn setup_env_for_crate_load_toml_found() { envmnt::set("CARGO_MAKE_CRATE_HAS_DEPENDENCIES", "EMPTY"); envmnt::set("CARGO_MAKE_CRATE_WORKSPACE_MEMBERS", "EMPTY"); - setup_env_for_crate(None); + setup_env_for_crate(None).unwrap(); assert_eq!(envmnt::get_or_panic("CARGO_MAKE_CRATE_NAME"), "cargo-make"); assert_eq!( @@ -1440,7 +1440,7 @@ fn setup_env_for_crate_load_toml_not_found_and_cwd() { assert!(envmnt::get_or_panic("CARGO_MAKE_WORKING_DIRECTORY") == "EMPTY"); setup_cwd(Some("examples")); - setup_env_for_crate(None); + setup_env_for_crate(None).unwrap(); setup_cwd(Some("..")); assert!(envmnt::get_or_panic("CARGO_MAKE_WORKING_DIRECTORY") != "EMPTY"); @@ -1472,7 +1472,7 @@ fn setup_env_for_crate_load_toml_not_found_and_cwd() { "" ); - setup_env_for_crate(None); + setup_env_for_crate(None).unwrap(); assert_eq!(envmnt::get_or_panic("CARGO_MAKE_CRATE_NAME"), "cargo-make"); assert_eq!( @@ -1533,7 +1533,7 @@ fn setup_env_for_crate_workspace() { envmnt::set("CARGO_MAKE_CRATE_WORKSPACE_MEMBERS", "EMPTY"); setup_cwd(Some("examples/workspace")); - setup_env_for_crate(None); + setup_env_for_crate(None).unwrap(); setup_cwd(Some("../..")); assert_eq!(envmnt::get_or_panic("CARGO_MAKE_CRATE_NAME"), "EMPTY"); @@ -1900,12 +1900,12 @@ fn setup_env_for_project_crate() { plugins: None, }; - let crate_info = crateinfo::load(); + let crate_info = crateinfo::load().unwrap(); envmnt::remove("CARGO_MAKE_PROJECT_NAME"); envmnt::remove("CARGO_MAKE_PROJECT_VERSION"); - setup_env_for_project(&config, &crate_info); + setup_env_for_project(&config, &crate_info).unwrap(); assert!(envmnt::is_equal("CARGO_MAKE_PROJECT_NAME", "cargo-make")); assert!(envmnt::is_equal( @@ -1933,8 +1933,8 @@ fn setup_env_for_project_workspace_with_main_crate() { envmnt::remove("CARGO_MAKE_PROJECT_VERSION"); setup_cwd(Some("src/lib/test/workspace1")); - let crate_info = crateinfo::load(); - setup_env_for_project(&config, &crate_info); + let crate_info = crateinfo::load().unwrap(); + setup_env_for_project(&config, &crate_info).unwrap(); setup_cwd(Some("../../../..")); assert!(envmnt::is_equal("CARGO_MAKE_PROJECT_NAME", "workspace1")); @@ -1957,8 +1957,8 @@ fn setup_env_for_project_workspace_no_main_crate() { envmnt::remove("CARGO_MAKE_PROJECT_VERSION"); setup_cwd(Some("src/lib/test/workspace1")); - let crate_info = crateinfo::load(); - setup_env_for_project(&config, &crate_info); + let crate_info = crateinfo::load().unwrap(); + setup_env_for_project(&config, &crate_info).unwrap(); setup_cwd(Some("../../../..")); assert!(envmnt::is_equal("CARGO_MAKE_PROJECT_NAME", "workspace1")); diff --git a/src/lib/error.rs b/src/lib/error.rs index 5d0ada29..514183ef 100644 --- a/src/lib/error.rs +++ b/src/lib/error.rs @@ -28,7 +28,22 @@ pub enum CargoMakeError { #[strum(to_string = "Error while executing command, exit code: {0}")] ExitCodeError(i32) = 104, - #[strum(to_string = "Unable to run, minimum required version is: {0}")] + #[strum(to_string = "Unable to parse internal descriptor: {0}")] + DescriptorParseFailed(String) = 105, + + #[strum(to_string = "Unable to parse external file: {0:#?}, {1}")] + ParseFileFailed(String, String) = 106, + + #[strum(to_string = "{0}")] + Arity(&'static str) = 107, + + #[strum(to_string = "{0}")] + MethodCallRestriction(&'static str) = 108, + + #[strum(to_string = "Task {0:#?} is {1}")] + TaskIs(String, &'static str), + + #[strum(to_string = "{0}")] NotFound(String) = 404, // ************************ @@ -37,6 +52,9 @@ pub enum CargoMakeError { #[strum(to_string = "`std::io::Error` error. {error:?}")] StdIoError { error: std::io::Error } = 700, + #[strum(to_string = "`std::fmt::Error` error. {error:?}")] + StdFmtError { error: std::fmt::Error } = 709, + #[strum(to_string = "{0:?}")] ExitCode(std::process::ExitCode) = 710, @@ -64,6 +82,12 @@ impl From for CargoMakeError { } } +impl From for CargoMakeError { + fn from(error: std::fmt::Error) -> Self { + Self::StdFmtError { error } + } +} + impl From for CargoMakeError { fn from(error: toml::de::Error) -> Self { Self::TomlDeError { error } diff --git a/src/lib/execution_plan.rs b/src/lib/execution_plan.rs index 72a3bd97..7241574a 100644 --- a/src/lib/execution_plan.rs +++ b/src/lib/execution_plan.rs @@ -312,12 +312,21 @@ fn is_workspace_flow( ) -> Result { // determine if workspace flow is explicitly set and enabled in the requested task let (task_set_workspace, task_enable_workspace) = - match get_optional_normalized_task(config, task, true)? { - Some(normalized_task) => match normalized_task.workspace { - Some(enable_workspace) => (true, enable_workspace), + match get_optional_normalized_task(config, task, true) { + Ok(optional_task) => match optional_task { + Some(normalized_task) => match normalized_task.workspace { + Some(enable_workspace) => (true, enable_workspace), + None => (false, false), + }, None => (false, false), }, - None => (false, false), + Err(e) => { + if let CargoMakeError::NotFound(_) = e { + (false, false) + } else { + return Err(e); + } + } }; // if project is not a workspace or if workspace is disabled via cli, return no workspace flow @@ -428,7 +437,7 @@ fn create_for_step( } } else { error!("Task {} is private", &task); - panic!("Task {} is private", &task); + return Err(CargoMakeError::TaskIs(format!("{}", &task), "private")); } Ok(()) } diff --git a/src/lib/execution_plan_test.rs b/src/lib/execution_plan_test.rs index f1a2267f..1dfb129b 100644 --- a/src/lib/execution_plan_test.rs +++ b/src/lib/execution_plan_test.rs @@ -1421,7 +1421,7 @@ fn create_workspace() { config.tasks.insert("test".to_string(), task); env::set_current_dir("./examples/workspace").unwrap(); - let crateinfo = environment::crateinfo::load(); + let crateinfo = environment::crateinfo::load().unwrap(); let execution_plan = create(&config, "test", &crateinfo, false, true, false, &None).unwrap(); env::set_current_dir("../../").unwrap(); assert_eq!(execution_plan.steps.len(), 1); @@ -1445,7 +1445,7 @@ fn create_noworkspace() { config.tasks.insert("test".to_string(), task); env::set_current_dir("./examples/workspace").unwrap(); - let crateinfo = environment::crateinfo::load(); + let crateinfo = environment::crateinfo::load().unwrap(); let execution_plan = create(&config, "test", &crateinfo, true, true, false, &None).unwrap(); env::set_current_dir("../../").unwrap(); assert_eq!(execution_plan.steps.len(), 1); diff --git a/src/lib/functions/mod.rs b/src/lib/functions/mod.rs index 8f23cadb..1e4ef212 100644 --- a/src/lib/functions/mod.rs +++ b/src/lib/functions/mod.rs @@ -13,23 +13,30 @@ mod remove_empty_func; mod split_func; mod trim_func; +use crate::error::CargoMakeError; use crate::types::{Step, Task}; -fn run_function(function_name: &str, function_args: &Vec) -> Vec { +fn run_function( + function_name: &str, + function_args: &Vec, +) -> Result, CargoMakeError> { debug!( "Running function: {} arguments: {:#?}", &function_name, &function_args ); match function_name { - "split" => split_func::invoke(function_args), - "remove-empty" => remove_empty_func::invoke(function_args), + "split" => Ok(split_func::invoke(function_args)), + "remove-empty" => Ok(remove_empty_func::invoke(function_args)), "trim" => trim_func::invoke(function_args), - "getat" => getat_func::invoke(function_args), - "decode" => decode_func::invoke(function_args), + "getat" => Ok(getat_func::invoke(function_args)), + "decode" => Ok(decode_func::invoke(function_args)), _ => { error!("Unknown function: {}", &function_name); - panic!("Unknown function: {}", &function_name); + Err(CargoMakeError::NotFound(format!( + "Unknown function: {}", + &function_name + ))) } } } @@ -70,7 +77,7 @@ fn get_function_arguments(function_string: &str) -> Option> { } } -fn evaluate_and_run(value: &str) -> Vec { +fn evaluate_and_run(value: &str) -> Result, CargoMakeError> { let value_string = value.to_string(); if value_string.starts_with("@@") { @@ -84,23 +91,23 @@ fn evaluate_and_run(value: &str) -> Vec { match func_args_option { Some(function_args) => run_function(&function_name, &function_args), - None => vec![value_string], + None => Ok(vec![value_string]), } } - None => vec![value_string], + None => Ok(vec![value_string]), } } else { - vec![value_string] + Ok(vec![value_string]) } } -fn modify_arguments(task: &mut Task) { +fn modify_arguments(task: &mut Task) -> Result<(), CargoMakeError> { task.args = match task.args { Some(ref args) => { let mut new_args = vec![]; for index in 0..args.len() { - let result_args = evaluate_and_run(&args[index]); + let result_args = evaluate_and_run(&args[index])?; for result_index in 0..result_args.len() { new_args.push(result_args[result_index].clone()); @@ -111,17 +118,18 @@ fn modify_arguments(task: &mut Task) { } None => None, }; + Ok(()) } -pub(crate) fn run(step: &Step) -> Step { +pub(crate) fn run(step: &Step) -> Result { //clone data before modify let mut config = step.config.clone(); //update args by running any needed function - modify_arguments(&mut config); + modify_arguments(&mut config)?; - Step { + Ok(Step { name: step.name.clone(), config, - } + }) } diff --git a/src/lib/functions/mod_test.rs b/src/lib/functions/mod_test.rs index bfb6e657..3c8957c0 100644 --- a/src/lib/functions/mod_test.rs +++ b/src/lib/functions/mod_test.rs @@ -3,13 +3,13 @@ use super::*; #[test] #[should_panic] fn run_function_empty() { - run_function("", &vec![]); + run_function("", &vec![]).unwrap(); } #[test] #[should_panic] fn run_function_not_exists() { - run_function("bad", &vec![]); + run_function("bad", &vec![]).unwrap(); } #[test] @@ -19,7 +19,8 @@ fn run_function_split() { let output = run_function( "split", &vec!["TEST_MOD_SPLIT_FUNC_MOD".to_string(), ",".to_string()], - ); + ) + .unwrap(); assert_eq!(output, vec!["1", "2", "3", "4"]); } @@ -35,7 +36,8 @@ fn run_function_getat() { ",".to_string(), "2".to_string(), ], - ); + ) + .unwrap(); assert_eq!(output, vec!["3"]); } @@ -47,7 +49,8 @@ fn run_function_remove_empty() { let output = run_function( "remove-empty", &vec!["TEST_MOD_REMOVE_EMPTY_FUNC_MOD".to_string()], - ); + ) + .unwrap(); assert_eq!(output.len(), 0); } @@ -56,7 +59,7 @@ fn run_function_remove_empty() { fn run_function_trim() { envmnt::set("TEST_MOD_TRIM_FUNC_MOD", " "); - let output = run_function("trim", &vec!["TEST_MOD_TRIM_FUNC_MOD".to_string()]); + let output = run_function("trim", &vec!["TEST_MOD_TRIM_FUNC_MOD".to_string()]).unwrap(); assert_eq!(output.len(), 0); } @@ -74,7 +77,8 @@ fn run_function_decode() { "ci".to_string(), "test".to_string(), ], - ); + ) + .unwrap(); assert_eq!(output, vec!["test"]); } @@ -168,7 +172,7 @@ fn get_function_arguments_multiple_with_spaces() { fn evaluate_and_run_valid() { envmnt::set("TEST_MOD_RUN_FUNC_VALUE", "1 2 3 4"); - let output = evaluate_and_run("@@split(TEST_MOD_RUN_FUNC_VALUE, )"); + let output = evaluate_and_run("@@split(TEST_MOD_RUN_FUNC_VALUE, )").unwrap(); assert_eq!(output, vec!["1", "2", "3", "4"]); } @@ -176,12 +180,12 @@ fn evaluate_and_run_valid() { #[test] #[should_panic] fn evaluate_and_run_unknown_function() { - evaluate_and_run("@@bad()"); + evaluate_and_run("@@bad()").unwrap(); } #[test] fn evaluate_and_run_no_function() { - let output = evaluate_and_run("value"); + let output = evaluate_and_run("value").unwrap(); assert_eq!(output, vec!["value"]); } @@ -197,7 +201,7 @@ fn modify_arguments_with_functions() { "end".to_string(), ]); - modify_arguments(&mut task); + modify_arguments(&mut task).unwrap(); assert_eq!(task.args.unwrap(), vec!["start", "1", "2", "3", "4", "end"]); } @@ -217,7 +221,7 @@ fn run_with_functions() { config: task, }; - step = run(&step); + step = run(&step).unwrap(); assert_eq!( step.config.args.unwrap(), diff --git a/src/lib/functions/trim_func.rs b/src/lib/functions/trim_func.rs index d5d06f8b..cb214d9d 100644 --- a/src/lib/functions/trim_func.rs +++ b/src/lib/functions/trim_func.rs @@ -4,13 +4,15 @@ //! The value will be removed if empty. //! +use crate::error::CargoMakeError; + #[cfg(test)] #[path = "trim_func_test.rs"] mod trim_func_test; -pub(crate) fn invoke(function_args: &Vec) -> Vec { +pub(crate) fn invoke(function_args: &Vec) -> Result, CargoMakeError> { if function_args.len() > 2 { - error!("trim expects up to 2 arguments (environment variable name and optionally start/end trim flag)"); + return Err(CargoMakeError::Arity("trim expects up to 2 arguments (environment variable name and optionally start/end trim flag)")); } let env_key = function_args[0].clone(); @@ -27,14 +29,16 @@ pub(crate) fn invoke(function_args: &Vec) -> Vec { "end" => value.trim_end().to_string(), _ => { error!("Invalid trim type provided, only start or end are supported."); - panic!("Invalid trim type provided, only start or end are supported."); + return Err(CargoMakeError::MethodCallRestriction( + "Invalid trim type provided, only start or end are supported.", + )); } } }; if trimmed_value.len() > 0 { - vec![trimmed_value] + Ok(vec![trimmed_value]) } else { - vec![] + Ok(vec![]) } } diff --git a/src/lib/functions/trim_func_test.rs b/src/lib/functions/trim_func_test.rs index d81f8f3a..7c8f4e13 100644 --- a/src/lib/functions/trim_func_test.rs +++ b/src/lib/functions/trim_func_test.rs @@ -3,26 +3,26 @@ use super::*; #[test] #[should_panic] fn trim_invoke_empty() { - invoke(&vec![]); + invoke(&vec![]).unwrap(); } #[test] #[should_panic] fn trim_invoke_invalid_too_many_args() { - invoke(&vec!["TEST".to_string(), "1".to_string(), "2".to_string()]); + invoke(&vec!["TEST".to_string(), "1".to_string(), "2".to_string()]).unwrap(); } #[test] #[should_panic] fn trim_invoke_invalid_trim_type() { - invoke(&vec!["TEST".to_string(), "bad".to_string()]); + invoke(&vec!["TEST".to_string(), "bad".to_string()]).unwrap(); } #[test] fn trim_invoke_exists_with_value() { envmnt::set("TEST_TRIM_VALID", "abc"); - let output = invoke(&vec!["TEST_TRIM_VALID".to_string()]); + let output = invoke(&vec!["TEST_TRIM_VALID".to_string()]).unwrap(); assert_eq!(output, vec!["abc"]); } @@ -31,14 +31,14 @@ fn trim_invoke_exists_with_value() { fn trim_invoke_exists_empty() { envmnt::set("TEST_TRIM_EMPTY", ""); - let output = invoke(&vec!["TEST_TRIM_EMPTY".to_string()]); + let output = invoke(&vec!["TEST_TRIM_EMPTY".to_string()]).unwrap(); assert_eq!(output.len(), 0); } #[test] fn trim_invoke_not_exists() { - let output = invoke(&vec!["TEST_TRIM_NOT_EXISTS".to_string()]); + let output = invoke(&vec!["TEST_TRIM_NOT_EXISTS".to_string()]).unwrap(); assert_eq!(output.len(), 0); } @@ -47,7 +47,7 @@ fn trim_invoke_not_exists() { fn trim_invoke_all_spaces() { envmnt::set("TEST_TRIM_ALL_SPACES", ""); - let output = invoke(&vec!["TEST_TRIM_ALL_SPACES".to_string()]); + let output = invoke(&vec!["TEST_TRIM_ALL_SPACES".to_string()]).unwrap(); assert_eq!(output.len(), 0); } @@ -56,7 +56,7 @@ fn trim_invoke_all_spaces() { fn trim_invoke_partial_spaces() { envmnt::set("TEST_TRIM_PARTIAL_SPACES", " 123 123 "); - let output = invoke(&vec!["TEST_TRIM_PARTIAL_SPACES".to_string()]); + let output = invoke(&vec!["TEST_TRIM_PARTIAL_SPACES".to_string()]).unwrap(); assert_eq!(output, vec!["123 123"]); } @@ -65,7 +65,7 @@ fn trim_invoke_partial_spaces() { fn trim_invoke_trim_start() { envmnt::set("TEST_TRIM_START", " 123 "); - let output = invoke(&vec!["TEST_TRIM_START".to_string(), "start".to_string()]); + let output = invoke(&vec!["TEST_TRIM_START".to_string(), "start".to_string()]).unwrap(); assert_eq!(output, vec!["123 "]); } @@ -74,7 +74,7 @@ fn trim_invoke_trim_start() { fn trim_invoke_trim_end() { envmnt::set("TEST_TRIM_END", " 123 "); - let output = invoke(&vec!["TEST_TRIM_END".to_string(), "end".to_string()]); + let output = invoke(&vec!["TEST_TRIM_END".to_string(), "end".to_string()]).unwrap(); assert_eq!(output, vec![" 123"]); } diff --git a/src/lib/installer/mod.rs b/src/lib/installer/mod.rs index 19368cec..2f5806f0 100644 --- a/src/lib/installer/mod.rs +++ b/src/lib/installer/mod.rs @@ -116,7 +116,9 @@ pub(crate) fn install( Some(ref crate_name) => (arg, crate_name.to_string()), None => { error!("Missing crate name to invoke."); - panic!("Missing crate name to invoke."); + return Err(CargoMakeError::NotFound(String::from( + "Missing crate name to invoke.", + ))); } }, None => match install_info.crate_name { @@ -125,7 +127,9 @@ pub(crate) fn install( } None => { error!("Missing cargo command to invoke."); - panic!("Missing crate command to invoke."); + return Err(CargoMakeError::NotFound(String::from( + "Missing crate command to invoke.", + ))); } }, }, diff --git a/src/lib/io.rs b/src/lib/io.rs index d36e7e13..2f6e5be2 100644 --- a/src/lib/io.rs +++ b/src/lib/io.rs @@ -7,6 +7,7 @@ #[path = "io_test.rs"] mod io_test; +use crate::error::CargoMakeError; use fsio::file::modify_file; use fsio::path as fsio_path; use fsio::path::from_path::FromPath; @@ -17,14 +18,14 @@ use std::fs::File; use std::io; use std::path::PathBuf; -pub(crate) fn create_text_file(text: &str, extension: &str) -> String { +pub(crate) fn create_text_file(text: &str, extension: &str) -> Result { let file_path = fsio_path::get_temporary_file_path(extension); match fsio::file::write_text_file(&file_path, text) { - Ok(_) => file_path, + Ok(_) => Ok(file_path), Err(error) => { error!("Unable to create file: {} {:#?}", &file_path, &error); - panic!("Unable to create file, error: {}", error); + Err(error.into()) } } } @@ -32,14 +33,14 @@ pub(crate) fn create_text_file(text: &str, extension: &str) -> String { pub(crate) fn create_file( write_content: &dyn Fn(&mut File) -> io::Result<()>, extension: &str, -) -> String { +) -> Result { let file_path = fsio_path::get_temporary_file_path(extension); match modify_file(&file_path, write_content, false) { - Ok(_) => file_path, + Ok(_) => Ok(file_path), Err(error) => { error!("Unable to write to file: {} {:#?}", &file_path, &error); - panic!("Unable to write to file, error: {}", error); + Err(error.into()) } } } @@ -58,13 +59,10 @@ pub(crate) fn write_text_file(file_path: &str, text: &str) -> bool { } } -pub(crate) fn read_text_file(file_path: &PathBuf) -> String { +pub(crate) fn read_text_file(file_path: &PathBuf) -> Result { debug!("Opening file: {:#?}", &file_path); - match fsio::file::read_text_file(file_path) { - Ok(content) => content, - Err(error) => panic!("Unable to read file: {:?} error: {:#?}", file_path, error), - } + Ok(fsio::file::read_text_file(file_path)?) } pub(crate) fn get_path_list( diff --git a/src/lib/io_test.rs b/src/lib/io_test.rs index c5b6352f..b422a36b 100644 --- a/src/lib/io_test.rs +++ b/src/lib/io_test.rs @@ -2,14 +2,14 @@ use super::*; #[test] fn create_text_file_read_and_delete() { - let file = create_text_file("test\nend", ".testfile"); + let file = create_text_file("test\nend", ".testfile").unwrap(); assert!(file.ends_with(".testfile")); let text = fsio::file::read_text_file(&file).unwrap(); let mut file_path = PathBuf::new(); file_path.push(&file); - let read_text = read_text_file(&file_path); + let read_text = read_text_file(&file_path).unwrap(); delete_file(&file); @@ -27,7 +27,7 @@ fn write_text_file_read_and_delete() { let mut file_path = PathBuf::new(); file_path.push(&file); - let read_text = read_text_file(&file_path); + let read_text = read_text_file(&file_path).unwrap(); delete_file(&file); diff --git a/src/lib/plugin/sdk/cm_plugin_force_plugin_set_test.rs b/src/lib/plugin/sdk/cm_plugin_force_plugin_set_test.rs index d75bc405..eefe775e 100644 --- a/src/lib/plugin/sdk/cm_plugin_force_plugin_set_test.rs +++ b/src/lib/plugin/sdk/cm_plugin_force_plugin_set_test.rs @@ -58,7 +58,7 @@ set_env FORCE_PLUGIN_SET_AND_CLEAR_FLOW_TEST_SET_4 1 ''' "#; - let config = descriptor_deserializer::load_config(&makefile_string, false); + let config = descriptor_deserializer::load_config(&makefile_string, false).unwrap(); let flow_info = FlowInfo { config, diff --git a/src/lib/runner.rs b/src/lib/runner.rs index 807bc429..d4c214b4 100755 --- a/src/lib/runner.rs +++ b/src/lib/runner.rs @@ -411,7 +411,7 @@ pub(crate) fn run_task_with_options( profile::set(&profile_name); // modify step using env and functions - let mut updated_step = functions::run(&step); + let mut updated_step = functions::run(&step)?; updated_step = environment::expand_env(&updated_step); let watch = should_watch(&step.config); diff --git a/src/lib/scriptengine/generic_script.rs b/src/lib/scriptengine/generic_script.rs index 588a5074..ffc9b5e4 100644 --- a/src/lib/scriptengine/generic_script.rs +++ b/src/lib/scriptengine/generic_script.rs @@ -41,7 +41,7 @@ pub(crate) fn execute( cli_arguments: &Vec, validate: bool, ) -> Result { - let file = create_script_file(script_text, &extension); + let file = create_script_file(script_text, &extension)?; let valid = run_file(&file, &runner, arguments, &mut cli_arguments.clone())?; diff --git a/src/lib/scriptengine/mod.rs b/src/lib/scriptengine/mod.rs index 78c85229..f1f9797f 100755 --- a/src/lib/scriptengine/mod.rs +++ b/src/lib/scriptengine/mod.rs @@ -43,10 +43,10 @@ pub(crate) enum EngineType { Unsupported, } -pub(crate) fn get_script_text(script: &ScriptValue) -> Vec { +pub(crate) fn get_script_text(script: &ScriptValue) -> Result, CargoMakeError> { match script { - ScriptValue::SingleLine(text) => vec![text.clone()], - ScriptValue::Text(text) => text.clone(), + ScriptValue::SingleLine(text) => Ok(vec![text.clone()]), + ScriptValue::Text(text) => Ok(text.clone()), ScriptValue::File(info) => { let mut file_path_string = String::new(); if !info.absolute_path.unwrap_or(false) { @@ -60,7 +60,7 @@ pub(crate) fn get_script_text(script: &ScriptValue) -> Vec { let mut file_path = PathBuf::new(); file_path.push(expanded_value); - let script_text = io::read_text_file(&file_path); + let script_text = io::read_text_file(&file_path)?; let lines: Vec<&str> = script_text.split('\n').collect(); let mut script_lines: Vec = vec![]; @@ -69,7 +69,7 @@ pub(crate) fn get_script_text(script: &ScriptValue) -> Vec { script_lines.push(line.to_string()); } - script_lines + Ok(script_lines) } ScriptValue::Sections(sections) => { let mut script_lines = vec![]; @@ -84,7 +84,7 @@ pub(crate) fn get_script_text(script: &ScriptValue) -> Vec { script_lines.push(text.to_string()); } - script_lines + Ok(script_lines) } } } @@ -108,7 +108,7 @@ pub(crate) fn get_engine_type( script: &ScriptValue, script_runner: &Option, script_extension: &Option, -) -> EngineType { +) -> Result { match script_runner { Some(ref runner) => { debug!("Checking script runner: {}", runner); @@ -120,19 +120,19 @@ pub(crate) fn get_engine_type( if script_extension.is_some() { // if both script runner and extension is defined, we use generic script runner debug!("Generic script detected."); - EngineType::Generic + Ok(EngineType::Generic) } else { // use default OS extension with custom runner debug!("OS script with custom runner detected."); - EngineType::OS + Ok(EngineType::OS) } } - _ => engine_type, + _ => Ok(engine_type), } } None => { // if no runner specified, try to extract it from script content - let script_text = get_script_text(&script); + let script_text = get_script_text(&script)?; let shebang = shebang_script::get_shebang(&script_text); match shebang.runner { @@ -143,15 +143,15 @@ pub(crate) fn get_engine_type( match engine_type { EngineType::Unsupported => { debug!("Shebang line does not point to an internal engine, using normal shebang script runner."); - EngineType::Shebang + Ok(EngineType::Shebang) } - _ => engine_type, + _ => Ok(engine_type), } } else { - EngineType::Shebang + Ok(EngineType::Shebang) } } - None => EngineType::OS, + None => Ok(EngineType::OS), } } } @@ -257,19 +257,19 @@ fn invoke_script( flow_state: Option>>, cli_arguments: &Vec, ) -> Result { - let engine_type = get_engine_type(script, &script_runner, &script_extension); + let engine_type = get_engine_type(script, &script_runner, &script_extension)?; match engine_type { EngineType::OS => { - let script_text = get_script_text(script); + let script_text = get_script_text(script)?; os_script::execute(&script_text, script_runner, cli_arguments, validate) } EngineType::Duckscript => { - let script_text = get_script_text(script); + let script_text = get_script_text(script)?; duck_script::execute(&script_text, cli_arguments, flow_info, flow_state, validate) } EngineType::Rust => { - let script_text = get_script_text(script); + let script_text = get_script_text(script)?; rsscript::execute( &script_text, script_runner_args.clone(), @@ -278,11 +278,11 @@ fn invoke_script( ) } EngineType::Shell2Batch => { - let script_text = get_script_text(script); + let script_text = get_script_text(script)?; shell_to_batch::execute(&script_text, cli_arguments, validate) } EngineType::Generic => { - let script_text = get_script_text(script); + let script_text = get_script_text(script)?; let extension = script_extension.clone().unwrap(); generic_script::execute( &script_text, @@ -294,7 +294,7 @@ fn invoke_script( ) } EngineType::Shebang => { - let script_text = get_script_text(script); + let script_text = get_script_text(script)?; let extension = script_extension.clone(); shebang_script::execute(&script_text, &extension, cli_arguments, validate) } diff --git a/src/lib/scriptengine/mod_test.rs b/src/lib/scriptengine/mod_test.rs index 7320243c..40d4692b 100755 --- a/src/lib/scriptengine/mod_test.rs +++ b/src/lib/scriptengine/mod_test.rs @@ -4,7 +4,9 @@ use crate::types::{FileScriptValue, ScriptSections}; #[test] fn get_script_text_single_line() { - let output = get_script_text(&ScriptValue::SingleLine("test".to_string())).join("\n"); + let output = get_script_text(&ScriptValue::SingleLine("test".to_string())) + .unwrap() + .join("\n"); assert_eq!(output, "test"); } @@ -15,6 +17,7 @@ fn get_script_text_vector() { "line 1".to_string(), "line 2".to_string(), ])) + .unwrap() .join("\n"); assert_eq!(output, "line 1\nline 2"); @@ -27,6 +30,7 @@ fn get_script_text_file() { absolute_path: None, }; let output = get_script_text(&ScriptValue::File(file_info)) + .unwrap() .join("\n") .replace("\r", ""); @@ -40,6 +44,7 @@ fn get_script_text_file_relative() { absolute_path: Some(false), }; let output = get_script_text(&ScriptValue::File(file_info)) + .unwrap() .join("\n") .replace("\r", ""); @@ -53,6 +58,7 @@ fn get_script_text_file_absolute() { absolute_path: Some(true), }; let output = get_script_text(&ScriptValue::File(file_info)) + .unwrap() .join("\n") .replace("\r", ""); @@ -66,6 +72,7 @@ fn get_script_text_script_content_sections() { main: Some("main".to_string()), post: Some("post".to_string()), })) + .unwrap() .join("\n"); assert_eq!(output, "pre\nmain\npost"); @@ -77,14 +84,16 @@ fn get_script_text_script_content_sections_empty() { pre: None, main: None, post: None, - })); + })) + .unwrap(); assert!(output.is_empty()); } #[test] fn get_engine_type_no_runner() { - let output = get_engine_type(&ScriptValue::Text(vec!["test".to_string()]), &None, &None); + let output = + get_engine_type(&ScriptValue::Text(vec!["test".to_string()]), &None, &None).unwrap(); assert_eq!(output, EngineType::OS); } @@ -95,7 +104,8 @@ fn get_engine_type_runner_no_extension() { &ScriptValue::Text(vec!["test".to_string()]), &Some("@bad".to_string()), &None, - ); + ) + .unwrap(); assert_eq!(output, EngineType::OS); } @@ -106,7 +116,8 @@ fn get_engine_type_duckscript() { &ScriptValue::Text(vec!["test".to_string()]), &Some("@duckscript".to_string()), &None, - ); + ) + .unwrap(); assert_eq!(output, EngineType::Duckscript); } @@ -117,7 +128,8 @@ fn get_engine_type_rust() { &ScriptValue::Text(vec!["test".to_string()]), &Some("@rust".to_string()), &None, - ); + ) + .unwrap(); assert_eq!(output, EngineType::Rust); } @@ -128,7 +140,8 @@ fn get_engine_type_shell_to_batch() { &ScriptValue::Text(vec!["test".to_string()]), &Some("@shell".to_string()), &None, - ); + ) + .unwrap(); assert_eq!(output, EngineType::Shell2Batch); } @@ -139,14 +152,16 @@ fn get_engine_type_generic() { &ScriptValue::Text(vec!["test".to_string()]), &Some("test1".to_string()), &Some("test2".to_string()), - ); + ) + .unwrap(); assert_eq!(output, EngineType::Generic); } #[test] fn get_engine_type_shebang() { - let output = get_engine_type(&ScriptValue::Text(vec!["#!bash".to_string()]), &None, &None); + let output = + get_engine_type(&ScriptValue::Text(vec!["#!bash".to_string()]), &None, &None).unwrap(); assert_eq!(output, EngineType::Shebang); } @@ -157,7 +172,8 @@ fn get_engine_type_duckscript_from_shebang() { &ScriptValue::Text(vec!["#!@duckscript".to_string()]), &None, &None, - ); + ) + .unwrap(); assert_eq!(output, EngineType::Duckscript); } @@ -168,7 +184,8 @@ fn get_engine_type_shell_to_batch_from_shebang() { &ScriptValue::Text(vec!["#!@shell".to_string()]), &None, &None, - ); + ) + .unwrap(); assert_eq!(output, EngineType::Shell2Batch); } @@ -179,7 +196,8 @@ fn get_engine_type_rust_from_shebang() { &ScriptValue::Text(vec!["#!@rust".to_string()]), &None, &None, - ); + ) + .unwrap(); assert_eq!(output, EngineType::Rust); } diff --git a/src/lib/scriptengine/rsscript.rs b/src/lib/scriptengine/rsscript.rs index 0ab2c4c6..25ff23eb 100755 --- a/src/lib/scriptengine/rsscript.rs +++ b/src/lib/scriptengine/rsscript.rs @@ -74,7 +74,7 @@ fn install_crate(provider: &ScriptRunner) -> Result<(), CargoMakeError> { Ok(()) } -fn create_rust_file(rust_script: &Vec) -> String { +fn create_rust_file(rust_script: &Vec) -> Result { create_persisted_script_file(rust_script, "rs") } @@ -121,7 +121,7 @@ pub(crate) fn execute( install_crate(&provider)?; - let file = create_rust_file(rust_script); + let file = create_rust_file(rust_script)?; let valid = run_file(&file, runner_arguments, &cli_arguments, &provider)?; diff --git a/src/lib/scriptengine/script_utils.rs b/src/lib/scriptengine/script_utils.rs index 66a5d8dc..2e1f3754 100644 --- a/src/lib/scriptengine/script_utils.rs +++ b/src/lib/scriptengine/script_utils.rs @@ -7,6 +7,7 @@ #[path = "script_utils_test.rs"] mod script_utils_test; +use crate::error::CargoMakeError; use crate::io::create_text_file; use fsio::file::write_text_file; use fsio::path::as_path::AsPath; @@ -14,18 +15,24 @@ use sha2::{Digest, Sha256}; use std::fmt::Write; use std::path::PathBuf; -pub(crate) fn create_script_file(script_text: &Vec, extension: &str) -> String { +pub(crate) fn create_script_file( + script_text: &Vec, + extension: &str, +) -> Result { let text = script_text.join("\n"); create_text_file(&text, &extension) } -pub(crate) fn create_persisted_script_file(script_text: &Vec, extension: &str) -> String { +pub(crate) fn create_persisted_script_file( + script_text: &Vec, + extension: &str, +) -> Result { let text = script_text.join("\n"); let string_bytes = text.as_bytes(); let bytes = Sha256::digest(string_bytes); - let file_name = bytes_to_hex(&bytes[..]); + let file_name = bytes_to_hex(&bytes[..])?; let default_target_directory = envmnt::get_or("CARGO_MAKE_CRATE_TARGET_DIRECTORY", "target"); let directory = envmnt::get_or( @@ -43,35 +50,23 @@ pub(crate) fn create_persisted_script_file(script_text: &Vec, extension: let file_path = file_path_string.as_path(); if file_path.exists() { - file_path_string + Ok(file_path_string) } else { match write_text_file(&file_path_string, &text) { - Ok(_) => file_path_string, + Ok(_) => Ok(file_path_string), Err(error) => { error!("Unable to create file: {} {:#?}", &file_path_string, &error); - panic!("Unable to create file, error: {}", error); + Err(error.into()) } } } } -fn bytes_to_hex(bytes: &[u8]) -> String { +fn bytes_to_hex(bytes: &[u8]) -> Result { let mut hex_string = String::with_capacity(2 * bytes.len()); for byte in bytes { - match write!(hex_string, "{:02X}", byte) { - Err(error) => { - error!( - "Unable to convert script hash to hex string, error: {}", - &error - ); - panic!( - "Unable to convert script hash to hex string, error: {}", - &error - ); - } - _ => (), - } + write!(hex_string, "{:02X}", byte)?; } - hex_string + Ok(hex_string) } diff --git a/src/lib/scriptengine/script_utils_test.rs b/src/lib/scriptengine/script_utils_test.rs index f7f6ef80..c6b41174 100644 --- a/src/lib/scriptengine/script_utils_test.rs +++ b/src/lib/scriptengine/script_utils_test.rs @@ -3,7 +3,8 @@ use crate::io; #[test] fn create_script_file_text() { - let file = create_script_file(&vec!["test".to_string(), "end".to_string()], ".testfile"); + let file = + create_script_file(&vec!["test".to_string(), "end".to_string()], ".testfile").unwrap(); assert!(file.ends_with(".testfile")); let text = fsio::file::read_text_file(&file).unwrap(); @@ -16,20 +17,23 @@ fn create_script_file_text() { #[test] fn create_persisted_script_file_text() { let mut file = - create_persisted_script_file(&vec!["test".to_string(), "end".to_string()], ".testfile"); + create_persisted_script_file(&vec!["test".to_string(), "end".to_string()], ".testfile") + .unwrap(); assert!(file.ends_with(".testfile")); let mut text = fsio::file::read_text_file(&file).unwrap(); io::delete_file(&file); assert_eq!("test\nend".to_string(), text); let file1 = - create_persisted_script_file(&vec!["test".to_string(), "end".to_string()], ".testfile"); + create_persisted_script_file(&vec!["test".to_string(), "end".to_string()], ".testfile") + .unwrap(); assert_eq!(file, file1); text = fsio::file::read_text_file(&file).unwrap(); assert_eq!("test\nend".to_string(), text); io::delete_file(&file); - file = create_persisted_script_file(&vec!["test2".to_string(), "end".to_string()], ".testfile"); + file = create_persisted_script_file(&vec!["test2".to_string(), "end".to_string()], ".testfile") + .unwrap(); assert_ne!(file, file1); text = fsio::file::read_text_file(&file).unwrap(); assert_eq!("test2\nend".to_string(), text);