From 9cc3ad11db58c2b4f4dded4a093a1a9b0bb78105 Mon Sep 17 00:00:00 2001 From: Freddie Ridell Date: Sat, 28 Feb 2026 18:15:11 +0000 Subject: [PATCH] Flatten config: single suite, string commands, consolidated modules --- bough.config.toml | 16 +- crates/bough-core/src/config.rs | 432 ++++++++++++++++++ .../bough-core/src/config/ideal.config.toml | 62 --- .../bough-core/src/config/minimal.config.toml | 5 - crates/bough-core/src/config/mod.rs | 391 ---------------- crates/bough-core/src/config/phase.rs | 32 -- crates/bough-core/src/config/suite.rs | 85 ---- crates/bough-core/src/io.rs | 0 crates/bough-core/src/lib.rs | 16 +- crates/bough-core/src/phase.rs | 121 ++--- crates/bough-core/src/session.rs | 20 + crates/bough-core/src/suite.rs | 16 +- crates/bough-core/src/workspace.rs | 3 + 13 files changed, 532 insertions(+), 667 deletions(-) create mode 100644 crates/bough-core/src/config.rs delete mode 100644 crates/bough-core/src/config/ideal.config.toml delete mode 100644 crates/bough-core/src/config/minimal.config.toml delete mode 100644 crates/bough-core/src/config/mod.rs delete mode 100644 crates/bough-core/src/config/phase.rs delete mode 100644 crates/bough-core/src/config/suite.rs delete mode 100644 crates/bough-core/src/io.rs create mode 100644 crates/bough-core/src/session.rs create mode 100644 crates/bough-core/src/workspace.rs diff --git a/bough.config.toml b/bough.config.toml index ac9afc45..d83c60ef 100644 --- a/bough.config.toml +++ b/bough.config.toml @@ -1,23 +1,21 @@ bough_dir = "./.bough" - -[vitest-js] pwd = "examples/vitest-js" ordering = "random" -[vitest-js.init] -commands = ["npm install"] +[init] +commands = "npm install" -[vitest-js.test] -commands = ["npm test"] +[test] +commands = "npm test" -[vitest-js.test_ids] +[test_ids] get_all = "npm run --silent get-test-ids" get_failed = "npm run --silent get-failed-test-ids" -[vitest-js.mutate.js] +[mutate.js] files.include = ["src/*.js"] files.exclude = ["**/*.test.*"] files.ignore_files = [] mutants.skip = [ - { query = "(if_statement condition: (parenthesized_expression (member_expression object: (meta_property)))) @skip" } , + { query = "(if_statement condition: (parenthesized_expression (member_expression object: (meta_property)))) @skip" }, ] diff --git a/crates/bough-core/src/config.rs b/crates/bough-core/src/config.rs new file mode 100644 index 00000000..71c8b116 --- /dev/null +++ b/crates/bough-core/src/config.rs @@ -0,0 +1,432 @@ +use crate::Outcome; +use crate::languages::LanguageId; +use crate::phase::{Phase, PhaseRunner, RunIn}; +use serde::{Deserialize, Serialize}; +use serde_value::Value; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +fn default_threads() -> u32 { + 1 +} +fn default_bough_dir() -> PathBuf { + PathBuf::from("./.bough") +} + +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct PhaseMetaConfig { + pub(crate) pwd: Option, + pub(crate) timeout: TimeoutConfig, + pub(crate) env: HashMap, +} + +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct PhaseConfig { + #[serde(flatten)] + pub(crate) meta: PhaseMetaConfig, + pub(crate) commands: String, +} + +impl PhaseConfig { + pub fn commands(&self) -> &str { + &self.commands + } +} + +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct TimeoutConfig { + pub(crate) absolute: Option, + pub(crate) relative: Option, +} + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum OrderingConfig { + #[default] + Random, + Alphabetical, + MissedFirst, + CaughtFirst, + NewestFirst, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TestIdsConfig { + pub(crate) get_all: String, + pub(crate) get_failed: String, +} + +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct MutateLanguageConfig { + pub(crate) files: FileSourceConfig, + pub(crate) mutants: MutantFilterConfig, +} + +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct FileSourceConfig { + pub(crate) include: Vec, + pub(crate) exclude: Vec, + pub(crate) ignore_files: Vec, +} + +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct MutantFilterConfig { + pub(crate) skip: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum MutantSkipConfig { + Query { query: String }, + Kind { kind: HashMap }, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Config { + pub(crate) source_dir: PathBuf, + pub(crate) ordering: OrderingConfig, + pub(crate) treat_timeouts_as: Outcome, + pub(crate) test_ids: Option, + + #[serde(default = "default_threads")] + pub(crate) threads: u32, + + #[serde(default = "default_bough_dir")] + pub(crate) bough_dir: PathBuf, + + #[serde(skip)] + #[serde(flatten)] + pub(crate) meta_defaults: PhaseMetaConfig, + + #[serde(flatten)] + pub(crate) phases: HashMap, + + #[serde(default)] + pub(crate) mutate: HashMap, +} + +impl Config { + pub fn get_phase_config(&self, phase: Phase) -> Option<&PhaseConfig> { + self.phases.get(&phase) + } + + pub fn new_phase_runner( + &self, + phase: Phase, + run_in: RunIn, + ) -> Result { + let phase_config = self + .phases + .get(&phase) + .ok_or(ConfigError::PhaseNotConfigured { phase })?; + + let base = match &run_in { + RunIn::SourceDir => self.source_dir.clone(), + RunIn::Workspace(id) => self + .resolve_path(&self.bough_dir) + .join("workspaces") + .join(id), + }; + + let pwd = phase_config + .meta + .pwd + .as_deref() + .or_else(|| self.meta_defaults.pwd.as_deref()) + .map(|p| base.join(p)) + .unwrap_or(base); + + let mut env = self.meta_defaults.env.clone(); + env.extend(phase_config.meta.env.clone()); + + let timeout = TimeoutConfig { + absolute: phase_config + .meta + .timeout + .absolute + .or(self.meta_defaults.timeout.absolute), + relative: phase_config + .meta + .timeout + .relative + .or(self.meta_defaults.timeout.relative), + }; + + Ok(PhaseRunner { + pwd, + env, + timeout, + commands: phase_config.commands.clone(), + }) + } + + fn resolve_path(&self, path: &Path) -> PathBuf { + if path.is_absolute() { + path.to_owned() + } else { + self.source_dir.join(path) + } + } +} + +impl Default for Config { + fn default() -> Self { + Self { + threads: default_threads(), + bough_dir: default_bough_dir(), + source_dir: PathBuf::default(), + ordering: OrderingConfig::default(), + treat_timeouts_as: Outcome::Caught, + test_ids: None, + meta_defaults: PhaseMetaConfig::default(), + phases: HashMap::new(), + mutate: HashMap::new(), + } + } +} + +pub struct ConfigBuilder { + value: Value, + source_dir: PathBuf, +} + +impl ConfigBuilder { + pub fn new(source_dir: PathBuf) -> Self { + Self { + value: Value::Map(Default::default()), + source_dir, + } + } + + pub fn from_value(self, value: Value) -> Self { + Self { value, ..self } + } + + pub fn override_with(mut self, patch: Value) -> Self { + self.value = Self::deep_merge(self.value, patch); + self + } + + fn deep_merge(base: Value, patch: Value) -> Value { + match (base, patch) { + (Value::Map(mut base_map), Value::Map(patch_map)) => { + for (k, v) in patch_map { + let merged = match base_map.remove(&k) { + Some(existing) => Self::deep_merge(existing, v), + None => v, + }; + base_map.insert(k, merged); + } + Value::Map(base_map) + } + (_, patch) => patch, + } + } + + pub fn build(self) -> Result { + let mut config = Config::deserialize(self.value).map_err(ConfigError::Deserialize)?; + config.source_dir = self.source_dir; + Ok(config) + } +} + +#[derive(Debug)] +pub enum ConfigError { + PhaseNotConfigured { phase: Phase }, + Deserialize(serde_value::DeserializerError), +} + +impl std::fmt::Display for ConfigError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ConfigError::PhaseNotConfigured { phase } => { + write!(f, "phase '{phase:?}' not configured") + } + ConfigError::Deserialize(e) => write!(f, "failed to deserialize config: {e}"), + } + } +} + +impl std::error::Error for ConfigError {} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Outcome; + use crate::languages::LanguageId; + use crate::phase::Phase; + + const IDEAL_CONFIG: &str = r#" +threads = 1 +bough_dir = "./.bough" +ordering = "alphabetical" +treat_timeouts_as = "Missed" + +[init] +pwd = "./examples/vitest" +commands = "npm install" + +[reset] +pwd = "./examples/vitest" +commands = "npm clean" + +[test] +pwd = "./examples/vitest" +timeout.absolute = 30 +timeout.relative = 3 +env = { NODE_ENV = "production" } +commands = "npx run test" + +[mutate.js] +files.include = ["**/*.js", "**/*.jsx"] +files.exclude = ["**/*__mocks__*"] +mutants.skip = [ + { query = "((fn 'describe') @ignore)" }, + { kind = { "BinaryOp" = "Add" } } +] + +[mutate.ts] +files.include = ["**/*.rs"] +mutants.skip = [ + { query = "((condition 'describe') @ignore)" }, + { kind = { "BinaryOp" = "Add" } } +] +"#; + + const MINIMAL_CONFIG: &str = r#" +[test] +commands = "npx vitest run" + +[mutate.ts] +files.include = ["src/**/*.ts"] +"#; + + fn toml_to_value(s: &str) -> Value { + let tv: toml::Value = toml::from_str(s).unwrap(); + serde_value::to_value(tv).unwrap() + } + + #[test] + fn deserialize_ideal_config() { + let config: Config = toml::from_str(IDEAL_CONFIG).expect("failed to parse ideal config"); + + assert_eq!(config.threads, 1); + assert_eq!(config.bough_dir, PathBuf::from("./.bough")); + assert_eq!(config.ordering, OrderingConfig::Alphabetical); + assert_eq!(config.treat_timeouts_as, Outcome::Missed); + + let init = &config.phases[&Phase::Init]; + assert_eq!(init.meta.pwd, Some(PathBuf::from("./examples/vitest"))); + assert_eq!(init.commands, "npm install"); + + let test = &config.phases[&Phase::Test]; + assert_eq!(test.meta.timeout.absolute, Some(30)); + assert_eq!(test.meta.timeout.relative, Some(3)); + assert_eq!(test.meta.env["NODE_ENV"], "production"); + assert_eq!(test.commands, "npx run test"); + + let js_mutate = &config.mutate[&LanguageId::Javascript]; + assert_eq!(js_mutate.files.include, vec!["**/*.js", "**/*.jsx"]); + assert_eq!(js_mutate.files.exclude, vec!["**/*__mocks__*"]); + assert_eq!(js_mutate.mutants.skip.len(), 2); + } + + #[test] + fn deserialize_minimal_config() { + let config: Config = + toml::from_str(MINIMAL_CONFIG).expect("failed to parse minimal config"); + + assert_eq!(config.threads, 1); + assert_eq!(config.bough_dir, PathBuf::from("./.bough")); + assert_eq!(config.ordering, OrderingConfig::Random); + assert_eq!(config.treat_timeouts_as, Outcome::Caught); + assert!(!config.phases.contains_key(&Phase::Init)); + assert!(!config.phases.contains_key(&Phase::Reset)); + + let test = &config.phases[&Phase::Test]; + assert_eq!(test.commands, "npx vitest run"); + assert_eq!(test.meta.pwd, None); + assert!(test.meta.env.is_empty()); + assert_eq!(test.meta.timeout, TimeoutConfig::default()); + + let ts_mutate = &config.mutate[&LanguageId::Typescript]; + assert_eq!(ts_mutate.files.include, vec!["src/**/*.ts"]); + assert!(ts_mutate.files.exclude.is_empty()); + assert!(ts_mutate.mutants.skip.is_empty()); + } + + fn build_with_override(base: &str, patch: &str) -> Config { + ConfigBuilder::new(PathBuf::new()) + .from_value(toml_to_value(base)) + .override_with(toml_to_value(patch)) + .build() + .unwrap() + } + + #[test] + fn override_scalar() { + let config = build_with_override("", "threads = 4"); + assert_eq!(config.threads, 4); + } + + #[test] + fn override_bough_dir() { + let config = build_with_override(IDEAL_CONFIG, r#"bough_dir = "/override""#); + assert_eq!(config.bough_dir, PathBuf::from("/override")); + } + + #[test] + fn override_vec_replaces() { + let config = build_with_override( + MINIMAL_CONFIG, + r#" + [test] + commands = "npm test" + "#, + ); + assert_eq!(config.phases[&Phase::Test].commands, "npm test"); + } + + #[test] + fn override_map_adds() { + let config = build_with_override( + MINIMAL_CONFIG, + r#" + [test.env] + FOO = "bar" + "#, + ); + assert_eq!(config.phases[&Phase::Test].meta.env["FOO"], "bar"); + } + + #[test] + fn override_deep_merge_phase() { + let config = build_with_override(IDEAL_CONFIG, r#"treat_timeouts_as = "Caught""#); + assert_eq!(config.treat_timeouts_as, Outcome::Caught); + assert!(config.phases.contains_key(&Phase::Init)); + } + + #[test] + fn defaults_are_sane() { + let config: Config = toml::from_str("").expect("empty config should parse"); + assert_eq!(config.threads, 1); + assert_eq!(config.bough_dir, PathBuf::from("./.bough")); + assert!(config.phases.is_empty()); + } + + #[test] + fn project_bough_config_parses() { + let toml_str = include_str!("../../../bough.config.toml"); + ConfigBuilder::new(PathBuf::new()) + .from_value(toml_to_value(toml_str)) + .build() + .expect("bough.config.toml should parse without errors or invariant violations"); + } +} diff --git a/crates/bough-core/src/config/ideal.config.toml b/crates/bough-core/src/config/ideal.config.toml deleted file mode 100644 index fd6bcc47..00000000 --- a/crates/bough-core/src/config/ideal.config.toml +++ /dev/null @@ -1,62 +0,0 @@ -threads = 1 -bough_dir = "./.bough" - -[vitest] -ordering = "alphabetical" -treat_timeouts_as = "Missed" - -[vitest.init] -pwd = "./examples/vitest" -commands = ["npm install"] - -[vitest.reset] -pwd = "./examples/vitest" -commands = ["npm clean"] - -[vitest.test] -pwd = "./examples/vitest" -timeout.absolute = 30 -timeout.relative = 3 -env = { NODE_ENV = "production" } -commands = [ - "npx run build", - "npx run test", -] - -[vitest.mutate.js] -files.include = ["**/*.js", "**/*.jsx"] -files.exclude = ["**/*__mocks__*"] -mutants.skip = [ - { query = "((fn 'describe') @ignore)" } , - { kind = { "BinaryOp" = "Add" } } -] - -[vitest.mutate.ts] -files.include = ["**/*.rs"] -mutants.skip = [ - { query = "((condition'describe') @ignore)" } , - { kind = { "BinaryOp" = "Add" } } -] - -[cargo] -pwd = "./examples/cargo" - -[cargo.test] -timeout.absolute = 30 -timeout.relative = 3 -commands = ["cargo test"] - -[cargo.mutate.js] -files.include = ["**/*.js", "**/*.jsx"] -files.exclude = ["**/*__mocks__*"] -mutants.skip = [ - { query = "((fn 'describe') @ignore)" } , - { kind = { "BinaryOp" = "Add" } } -] - -[cargo.mutate.ts] -files.include = ["**/*.rs"] -mutants.skip = [ - { query = "((fn 'describe') @ignore)" } , - { kind = { "BinaryOp" = "Add" } } -] diff --git a/crates/bough-core/src/config/minimal.config.toml b/crates/bough-core/src/config/minimal.config.toml deleted file mode 100644 index f2a7eb79..00000000 --- a/crates/bough-core/src/config/minimal.config.toml +++ /dev/null @@ -1,5 +0,0 @@ -[vitest.test] -commands = ["npx vitest run"] - -[vitest.mutate.ts] -files.include = ["src/**/*.ts"] diff --git a/crates/bough-core/src/config/mod.rs b/crates/bough-core/src/config/mod.rs deleted file mode 100644 index 11630509..00000000 --- a/crates/bough-core/src/config/mod.rs +++ /dev/null @@ -1,391 +0,0 @@ -pub mod phase; -pub mod suite; - -pub use phase::{PhaseConfig, PhaseMetaConfig, TimeoutConfig}; -pub use suite::{ - FileSourceConfig, MutantFilterConfig, MutantSkipConfig, MutateLanguageConfig, OrderingConfig, - SuiteConfig, TestIdsConfig, -}; - -use crate::phase::{Phase, PhaseRunner, RunIn}; -use crate::suite::Suite; -use serde::{Deserialize, Serialize}; -use serde_value::Value; -use std::collections::HashMap; -use std::path::PathBuf; - -fn default_threads() -> u32 { - 1 -} -fn default_bough_dir() -> PathBuf { - PathBuf::from("./.bough") -} - -#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(transparent)] -pub struct SuiteId(pub(crate) String); - -impl std::fmt::Display for SuiteId { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.0) - } -} - -impl SuiteId { - pub fn try_parse(config: &Config, name: &str) -> Result { - let id = Self(name.to_string()); - if config.suites.contains_key(&id) { - Ok(id) - } else { - Err(ConfigError::UnknownSuite { - name: id, - available: config.suites.keys().cloned().collect(), - }) - } - } -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct Config { - pub(crate) active_suite: SuiteId, - #[serde(default = "default_threads")] - pub(crate) threads: u32, - #[serde(default = "default_bough_dir")] - pub(crate) bough_dir: PathBuf, - #[serde(skip)] - pub(crate) source_dir: PathBuf, - #[serde(flatten)] - pub(crate) suites: HashMap, -} - -impl Config { - pub fn new_suite<'a>(&'a self, id: &SuiteId) -> Result, ConfigError> { - let suite = self.suite_or_err(id)?; - Ok(Suite::new(suite)) - } - - pub fn new_phase_runner( - &self, - suite_id: &SuiteId, - phase: Phase, - run_in: RunIn, - ) -> Result { - let suite = self.suite_or_err(suite_id)?; - let phase_config = suite.get_phase_config(phase).ok_or(ConfigError::PhaseNotConfigured { - phase, - suite: suite_id.clone(), - })?; - - let base = match &run_in { - RunIn::SourceDir => self.source_dir.clone(), - RunIn::Workspace(id) => self.resolve_path(&self.bough_dir).join("workspaces").join(id), - }; - - let pwd = phase_config.meta.pwd.as_deref() - .or_else(|| suite.meta_defaults.pwd.as_deref()) - .map(|p| base.join(p)) - .unwrap_or(base); - - let mut env = suite.meta_defaults.env.clone(); - env.extend(phase_config.meta.env.clone()); - - let timeout = TimeoutConfig { - absolute: phase_config.meta.timeout.absolute.or(suite.meta_defaults.timeout.absolute), - relative: phase_config.meta.timeout.relative.or(suite.meta_defaults.timeout.relative), - }; - - Ok(PhaseRunner { - pwd, - env, - timeout, - commands: phase_config.commands.clone(), - }) - } - - fn resolve_path(&self, path: &std::path::Path) -> PathBuf { - if path.is_absolute() { - path.to_owned() - } else { - self.source_dir.join(path) - } - } - - fn suite_or_err(&self, id: &SuiteId) -> Result<&SuiteConfig, ConfigError> { - self.suites - .get(id) - .ok_or_else(|| ConfigError::UnknownSuite { - name: id.clone(), - available: self.suites.keys().cloned().collect(), - }) - } -} - -impl Default for Config { - fn default() -> Self { - Self { - active_suite: SuiteId::default(), - threads: default_threads(), - bough_dir: default_bough_dir(), - source_dir: PathBuf::default(), - suites: HashMap::new(), - } - } -} - -pub struct ConfigBuilder { - value: Value, - source_dir: PathBuf, -} - -impl ConfigBuilder { - pub fn new(source_dir: PathBuf) -> Self { - Self { - value: Value::Map(Default::default()), - source_dir, - } - } - - pub fn from_value(self, value: Value) -> Self { - Self { value, ..self } - } - - pub fn override_with(mut self, patch: Value) -> Self { - self.value = Self::deep_merge(self.value, patch); - self - } - - fn deep_merge(base: Value, patch: Value) -> Value { - match (base, patch) { - (Value::Map(mut base_map), Value::Map(patch_map)) => { - for (k, v) in patch_map { - let merged = match base_map.remove(&k) { - Some(existing) => Self::deep_merge(existing, v), - None => v, - }; - base_map.insert(k, merged); - } - Value::Map(base_map) - } - (_, patch) => patch, - } - } - - pub fn build(self) -> Result { - let mut config = Config::deserialize(self.value).map_err(ConfigError::Deserialize)?; - config.source_dir = self.source_dir; - Self::check_invariants(&config)?; - Ok(config) - } - - fn check_invariants(config: &Config) -> Result<(), ConfigError> { - let suite = &config.active_suite; - if !suite.0.is_empty() && !config.suites.contains_key(suite) { - return Err(ConfigError::UnknownSuite { - name: suite.clone(), - available: config.suites.keys().cloned().collect(), - }); - } - Ok(()) - } -} - -#[derive(Debug)] -pub enum ConfigError { - UnknownSuite { - name: SuiteId, - available: Vec, - }, - PhaseNotConfigured { - phase: Phase, - suite: SuiteId, - }, - Deserialize(serde_value::DeserializerError), -} - -impl std::fmt::Display for ConfigError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - ConfigError::UnknownSuite { name, available } => { - write!( - f, - "suite '{}' not found in config (available: {})", - name, - if available.is_empty() { - "none".to_string() - } else { - available - .iter() - .map(|s| s.0.as_str()) - .collect::>() - .join(", ") - } - ) - } - ConfigError::PhaseNotConfigured { phase, suite } => { - write!(f, "phase '{phase:?}' not configured in suite '{suite}'") - } - ConfigError::Deserialize(e) => write!(f, "failed to deserialize config: {e}"), - } - } -} - -impl std::error::Error for ConfigError {} - -#[cfg(test)] -mod tests { - use super::*; - use crate::languages::LanguageId; - use crate::phase::Phase; - - use crate::Outcome; - - #[test] - fn deserialize_ideal_config() { - let toml_str = include_str!("ideal.config.toml"); - let config: Config = toml::from_str(toml_str).expect("failed to parse ideal config"); - - assert_eq!(config.threads, 1); - assert_eq!(config.bough_dir, PathBuf::from("./.bough")); - - let vitest = &config.suites[&SuiteId("vitest".into())]; - assert_eq!(vitest.ordering, OrderingConfig::Alphabetical); - assert_eq!(vitest.treat_timeouts_as, Outcome::Missed); - - let init = &vitest.phases[&Phase::Init]; - assert_eq!(init.meta.pwd, Some(PathBuf::from("./examples/vitest"))); - assert_eq!(init.commands, vec!["npm install"]); - - let test = &vitest.phases[&Phase::Test]; - assert_eq!(test.meta.timeout.absolute, Some(30)); - assert_eq!(test.meta.timeout.relative, Some(3)); - assert_eq!(test.meta.env["NODE_ENV"], "production"); - assert_eq!(test.commands, vec!["npx run build", "npx run test"]); - - let js_mutate = &vitest.mutate[&LanguageId::Javascript]; - assert_eq!(js_mutate.files.include, vec!["**/*.js", "**/*.jsx"]); - assert_eq!(js_mutate.files.exclude, vec!["**/*__mocks__*"]); - assert_eq!(js_mutate.mutants.skip.len(), 2); - - let cargo = &config.suites[&SuiteId("cargo".into())]; - assert_eq!( - cargo.meta_defaults.pwd, - Some(PathBuf::from("./examples/cargo")) - ); - assert_eq!(cargo.phases[&Phase::Test].commands, vec!["cargo test"]); - } - - #[test] - fn deserialize_minimal_config() { - let toml_str = include_str!("minimal.config.toml"); - let config: Config = toml::from_str(toml_str).expect("failed to parse minimal config"); - - assert_eq!(config.threads, 1); - assert_eq!(config.bough_dir, PathBuf::from("./.bough")); - - let vitest = &config.suites[&SuiteId("vitest".into())]; - assert_eq!(vitest.ordering, OrderingConfig::Random); - assert_eq!(vitest.treat_timeouts_as, Outcome::Caught); - assert!(!vitest.phases.contains_key(&Phase::Init)); - assert!(!vitest.phases.contains_key(&Phase::Reset)); - - let test = &vitest.phases[&Phase::Test]; - assert_eq!(test.commands, vec!["npx vitest run"]); - assert_eq!(test.meta.pwd, None); - assert!(test.meta.env.is_empty()); - assert_eq!(test.meta.timeout, TimeoutConfig::default()); - - let ts_mutate = &vitest.mutate[&LanguageId::Typescript]; - assert_eq!(ts_mutate.files.include, vec!["src/**/*.ts"]); - assert!(ts_mutate.files.exclude.is_empty()); - assert!(ts_mutate.mutants.skip.is_empty()); - } - - fn toml_to_value(s: &str) -> Value { - let tv: toml::Value = toml::from_str(s).unwrap(); - serde_value::to_value(tv).unwrap() - } - - fn build_with_override(base: &str, patch: &str) -> Config { - ConfigBuilder::new(PathBuf::new()) - .from_value(toml_to_value(base)) - .override_with(toml_to_value(patch)) - .build() - .unwrap() - } - - #[test] - fn override_scalar() { - let config = build_with_override("", "threads = 4"); - assert_eq!(config.threads, 4); - } - - #[test] - fn override_bough_dir() { - let config = build_with_override( - include_str!("ideal.config.toml"), - r#"bough_dir = "/override""#, - ); - assert_eq!(config.bough_dir, PathBuf::from("/override")); - } - - #[test] - fn override_vec_replaces() { - let config = build_with_override( - include_str!("minimal.config.toml"), - r#" - [vitest.test] - commands = ["npm test"] - "#, - ); - assert_eq!( - config.suites[&SuiteId("vitest".into())].phases[&Phase::Test].commands, - vec!["npm test"] - ); - } - - #[test] - fn override_map_adds() { - let config = build_with_override( - include_str!("minimal.config.toml"), - r#" - [vitest.test.env] - FOO = "bar" - "#, - ); - assert_eq!( - config.suites[&SuiteId("vitest".into())].phases[&Phase::Test] - .meta - .env["FOO"], - "bar" - ); - } - - #[test] - fn override_deep_merge_suite() { - let config = build_with_override( - include_str!("ideal.config.toml"), - r#" - [vitest] - treat_timeouts_as = "Caught" - "#, - ); - assert_eq!( - config.suites[&SuiteId("vitest".into())].treat_timeouts_as, - Outcome::Caught - ); - assert!( - config.suites[&SuiteId("vitest".into())] - .phases - .contains_key(&Phase::Init) - ); - } - - #[test] - fn defaults_are_sane() { - let config: Config = toml::from_str("").expect("empty config should parse"); - assert_eq!(config.threads, 1); - assert_eq!(config.bough_dir, PathBuf::from("./.bough")); - assert!(config.suites.is_empty()); - } -} diff --git a/crates/bough-core/src/config/phase.rs b/crates/bough-core/src/config/phase.rs deleted file mode 100644 index cb285538..00000000 --- a/crates/bough-core/src/config/phase.rs +++ /dev/null @@ -1,32 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::path::PathBuf; - -#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct PhaseMetaConfig { - pub(crate) pwd: Option, - pub(crate) timeout: TimeoutConfig, - pub(crate) env: HashMap, -} - -#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct PhaseConfig { - #[serde(flatten)] - pub(crate) meta: PhaseMetaConfig, - pub(crate) commands: Vec, -} - -impl PhaseConfig { - pub fn commands(&self) -> &[String] { - &self.commands - } -} - -#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct TimeoutConfig { - pub(crate) absolute: Option, - pub(crate) relative: Option, -} diff --git a/crates/bough-core/src/config/suite.rs b/crates/bough-core/src/config/suite.rs deleted file mode 100644 index 41dbf0eb..00000000 --- a/crates/bough-core/src/config/suite.rs +++ /dev/null @@ -1,85 +0,0 @@ -use crate::languages::LanguageId; -use crate::phase::Phase; -use crate::Outcome; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::path::PathBuf; -use super::phase::PhaseConfig; - -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)] -#[serde(rename_all = "lowercase")] -pub enum OrderingConfig { - #[default] - Random, - Alphabetical, - MissedFirst, - CaughtFirst, - NewestFirst, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct SuiteConfig { - pub(crate) ordering: OrderingConfig, - pub(crate) treat_timeouts_as: Outcome, - pub(crate) test_ids: Option, - #[serde(flatten)] - pub(crate) meta_defaults: super::phase::PhaseMetaConfig, - #[serde(flatten)] - pub(crate) phases: HashMap, - #[serde(default)] - pub(crate) mutate: HashMap, -} - -impl SuiteConfig { - pub fn get_phase_config(&self, phase: Phase) -> Option<&PhaseConfig> { - self.phases.get(&phase) - } -} - -impl Default for SuiteConfig { - fn default() -> Self { - Self { - ordering: OrderingConfig::default(), - treat_timeouts_as: Outcome::Caught, - test_ids: None, - meta_defaults: Default::default(), - phases: HashMap::new(), - mutate: HashMap::new(), - } - } -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct TestIdsConfig { - pub(crate) get_all: String, - pub(crate) get_failed: String, -} - -#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct MutateLanguageConfig { - pub(crate) files: FileSourceConfig, - pub(crate) mutants: MutantFilterConfig, -} - -#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct FileSourceConfig { - pub(crate) include: Vec, - pub(crate) exclude: Vec, - pub(crate) ignore_files: Vec, -} - -#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct MutantFilterConfig { - pub(crate) skip: Vec, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(untagged)] -pub enum MutantSkipConfig { - Query { query: String }, - Kind { kind: HashMap }, -} diff --git a/crates/bough-core/src/io.rs b/crates/bough-core/src/io.rs deleted file mode 100644 index e69de29b..00000000 diff --git a/crates/bough-core/src/lib.rs b/crates/bough-core/src/lib.rs index 406260da..e9bca757 100644 --- a/crates/bough-core/src/lib.rs +++ b/crates/bough-core/src/lib.rs @@ -1,8 +1,9 @@ pub mod config; -pub mod io; pub mod languages; pub mod phase; +mod session; pub mod suite; +pub mod workspace; use bough_typed_hash::HashInto; use chrono::{DateTime, Utc}; @@ -49,12 +50,14 @@ impl WorkspaceId { Ok(Self(name)) } - pub fn create(name: impl Into, config: &config::Config) -> Result { + pub fn create( + name: impl Into, + config: &config::Config, + ) -> Result { let name = name.into(); let path = config.bough_dir.join(&name); if !path.is_dir() { - std::fs::create_dir_all(&path) - .map_err(|e| ValidationError::CreateDir(path, e))?; + std::fs::create_dir_all(&path).map_err(|e| ValidationError::CreateDir(path, e))?; } Ok(Self(name)) } @@ -241,7 +244,10 @@ impl Mutant { driver_for(self.src.language).substitutions_for_kind(&self.kind) } - pub fn to_ts_node<'tree>(&self, tree: &'tree tree_sitter::Tree) -> Option> { + pub fn to_ts_node<'tree>( + &self, + tree: &'tree tree_sitter::Tree, + ) -> Option> { let start = tree_sitter::Point::new(self.span.start.line, self.span.start.char); let node = tree.root_node().descendant_for_point_range(start, start)?; if node.start_byte() == self.span.start.byte && node.end_byte() == self.span.end.byte { diff --git a/crates/bough-core/src/phase.rs b/crates/bough-core/src/phase.rs index 1eaaf1c8..26dc2f1f 100644 --- a/crates/bough-core/src/phase.rs +++ b/crates/bough-core/src/phase.rs @@ -62,21 +62,14 @@ pub struct PhaseRunner { pub pwd: PathBuf, pub env: HashMap, pub timeout: TimeoutConfig, - pub commands: Vec, + pub commands: String, } impl PhaseRunner { pub fn run(&self) -> Result { let timeout = self.timeout.absolute.map(Duration::from_secs); - let mut stdout = String::new(); - for (i, cmd) in self.commands.iter().enumerate() { - let (chunk, code) = self.run_one(i, cmd, &self.pwd, &timeout)?; - stdout.push_str(&chunk); - if code != 0 { - return Ok(PhaseOutput { stdout, error_code: Some(code) }); - } - } - Ok(PhaseOutput { stdout, error_code: None }) + let (stdout, code) = self.run_one(0, &self.commands, &self.pwd, &timeout)?; + Ok(PhaseOutput { stdout, error_code: if code != 0 { Some(code) } else { None } }) } fn run_one( @@ -133,7 +126,7 @@ impl PhaseRunner { #[cfg(test)] mod tests { use super::*; - use crate::config::{ConfigBuilder, ConfigError, SuiteId}; + use crate::config::{ConfigBuilder, ConfigError}; use crate::WorkspaceId; use std::path::PathBuf; @@ -145,53 +138,47 @@ mod tests { .unwrap() } - fn sid(config: &crate::config::Config, name: &str) -> SuiteId { - SuiteId::try_parse(config, name).unwrap() - } - #[test] fn source_dir_is_pwd_when_no_pwd_set() { let c = config("/src", r#" - [suite.test] - commands = ["run"] + [test] + commands = "run" "#); - let r = c.new_phase_runner(&sid(&c, "suite"), Phase::Test, RunIn::SourceDir).unwrap(); + let r = c.new_phase_runner(Phase::Test, RunIn::SourceDir).unwrap(); assert_eq!(r.pwd, PathBuf::from("/src")); } #[test] fn phase_pwd_joined_to_source_dir() { let c = config("/src", r#" - [suite.test] + [test] pwd = "subdir" - commands = ["run"] + commands = "run" "#); - let r = c.new_phase_runner(&sid(&c, "suite"), Phase::Test, RunIn::SourceDir).unwrap(); + let r = c.new_phase_runner(Phase::Test, RunIn::SourceDir).unwrap(); assert_eq!(r.pwd, PathBuf::from("/src/subdir")); } #[test] - fn suite_default_pwd_used_when_phase_has_none() { + fn meta_default_pwd_used_when_phase_has_none() { let c = config("/src", r#" - [suite] - pwd = "suite-dir" - [suite.test] - commands = ["run"] + pwd = "default-dir" + [test] + commands = "run" "#); - let r = c.new_phase_runner(&sid(&c, "suite"), Phase::Test, RunIn::SourceDir).unwrap(); - assert_eq!(r.pwd, PathBuf::from("/src/suite-dir")); + let r = c.new_phase_runner(Phase::Test, RunIn::SourceDir).unwrap(); + assert_eq!(r.pwd, PathBuf::from("/src/default-dir")); } #[test] - fn phase_pwd_takes_precedence_over_suite_default() { + fn phase_pwd_takes_precedence_over_meta_default() { let c = config("/src", r#" - [suite] - pwd = "suite-dir" - [suite.test] + pwd = "default-dir" + [test] pwd = "phase-dir" - commands = ["run"] + commands = "run" "#); - let r = c.new_phase_runner(&sid(&c, "suite"), Phase::Test, RunIn::SourceDir).unwrap(); + let r = c.new_phase_runner(Phase::Test, RunIn::SourceDir).unwrap(); assert_eq!(r.pwd, PathBuf::from("/src/phase-dir")); } @@ -199,10 +186,10 @@ mod tests { fn workspace_absolute_bough_dir() { let c = config("/src", r#" bough_dir = "/bough" - [suite.test] - commands = ["run"] + [test] + commands = "run" "#); - let r = c.new_phase_runner(&sid(&c, "suite"), Phase::Test, RunIn::Workspace(WorkspaceId::from_trusted("ws"))).unwrap(); + let r = c.new_phase_runner(Phase::Test, RunIn::Workspace(WorkspaceId::from_trusted("ws"))).unwrap(); assert_eq!(r.pwd, PathBuf::from("/bough/workspaces/ws")); } @@ -210,43 +197,42 @@ mod tests { fn workspace_relative_bough_dir_resolved_from_source_dir() { let c = config("/src", r#" bough_dir = ".bough" - [suite.test] - commands = ["run"] + [test] + commands = "run" "#); - let r = c.new_phase_runner(&sid(&c, "suite"), Phase::Test, RunIn::Workspace(WorkspaceId::from_trusted("ws"))).unwrap(); + let r = c.new_phase_runner(Phase::Test, RunIn::Workspace(WorkspaceId::from_trusted("ws"))).unwrap(); assert_eq!(r.pwd, PathBuf::from("/src/.bough/workspaces/ws")); } #[test] - fn env_merge_phase_overrides_suite() { + fn env_merge_phase_overrides_meta_default() { let c = config("/src", r#" - [suite.env] - SHARED = "suite" - SUITE_ONLY = "s" - [suite.test] - commands = ["run"] - [suite.test.env] + [env] + SHARED = "default" + DEFAULT_ONLY = "d" + [test] + commands = "run" + [test.env] SHARED = "phase" PHASE_ONLY = "p" "#); - let r = c.new_phase_runner(&sid(&c, "suite"), Phase::Test, RunIn::SourceDir).unwrap(); + let r = c.new_phase_runner(Phase::Test, RunIn::SourceDir).unwrap(); assert_eq!(r.env["SHARED"], "phase"); - assert_eq!(r.env["SUITE_ONLY"], "s"); + assert_eq!(r.env["DEFAULT_ONLY"], "d"); assert_eq!(r.env["PHASE_ONLY"], "p"); } #[test] - fn timeout_phase_overrides_suite_per_field() { + fn timeout_phase_overrides_meta_default_per_field() { let c = config("/src", r#" - [suite.timeout] - absolute = 60 - relative = 5 - [suite.test] - commands = ["run"] - [suite.test.timeout] + timeout.absolute = 60 + timeout.relative = 5 + [test] + commands = "run" + [test.timeout] absolute = 30 "#); - let r = c.new_phase_runner(&sid(&c, "suite"), Phase::Test, RunIn::SourceDir).unwrap(); + let r = c.new_phase_runner(Phase::Test, RunIn::SourceDir).unwrap(); assert_eq!(r.timeout.absolute, Some(30)); assert_eq!(r.timeout.relative, Some(5)); } @@ -254,27 +240,20 @@ mod tests { #[test] fn commands_taken_from_phase() { let c = config("/src", r#" - [suite.test] - commands = ["step1", "step2"] + [test] + commands = "step1" "#); - let r = c.new_phase_runner(&sid(&c, "suite"), Phase::Test, RunIn::SourceDir).unwrap(); - assert_eq!(r.commands, vec!["step1", "step2"]); - } - - #[test] - fn unknown_suite_returns_error() { - let c = config("/src", ""); - let err = c.new_phase_runner(&SuiteId("missing".into()), Phase::Test, RunIn::SourceDir).unwrap_err(); - assert!(matches!(err, ConfigError::UnknownSuite { .. })); + let r = c.new_phase_runner(Phase::Test, RunIn::SourceDir).unwrap(); + assert_eq!(r.commands, "step1"); } #[test] fn phase_not_configured_returns_error() { let c = config("/src", r#" - [suite.test] - commands = ["run"] + [test] + commands = "run" "#); - let err = c.new_phase_runner(&sid(&c, "suite"), Phase::Init, RunIn::SourceDir).unwrap_err(); + let err = c.new_phase_runner(Phase::Init, RunIn::SourceDir).unwrap_err(); assert!(matches!(err, ConfigError::PhaseNotConfigured { .. })); } } diff --git a/crates/bough-core/src/session.rs b/crates/bough-core/src/session.rs new file mode 100644 index 00000000..d68925a3 --- /dev/null +++ b/crates/bough-core/src/session.rs @@ -0,0 +1,20 @@ +use std::collections::HashMap; + +use crate::WorkspaceId; +use crate::config::Config; +use crate::workspace::Workspace; + +pub enum Error {} +pub struct Session { + config: Config, + workspaces: HashMap, +} + +impl Session { + pub fn new(config: Config) -> Result { + let workspaces = HashMap::new(); + let me = Self { config, workspaces }; + + Ok(me) + } +} diff --git a/crates/bough-core/src/suite.rs b/crates/bough-core/src/suite.rs index fecf479d..507f3f1e 100644 --- a/crates/bough-core/src/suite.rs +++ b/crates/bough-core/src/suite.rs @@ -1,11 +1,13 @@ -use crate::config::SuiteConfig; +use crate::WorkspaceId; -pub struct Suite<'a> { - pub config: &'a SuiteConfig, -} +pub struct Suite {} + +impl Suite { + pub fn new() -> Self { + Self {} + } -impl<'a> Suite<'a> { - pub fn new(config: &'a SuiteConfig) -> Self { - Self { config } + pub fn make_new_workspace(&self) -> WorkspaceId { + todo!() } } diff --git a/crates/bough-core/src/workspace.rs b/crates/bough-core/src/workspace.rs new file mode 100644 index 00000000..2bac12f2 --- /dev/null +++ b/crates/bough-core/src/workspace.rs @@ -0,0 +1,3 @@ +pub struct Workspace {} + +impl Workspace {} -- knotmirror 0.0.1