From 345a14f054b6d35588eadc5663607fdb9e2e5697 Mon Sep 17 00:00:00 2001 From: Freddie Ridell Date: Sun, 22 Feb 2026 17:00:26 +0000 Subject: [PATCH] Extract session and config into pollard-session --- Cargo.lock | 24 +- crates/pollard-cli/Cargo.toml | 2 +- crates/pollard-cli/src/io.rs | 52 ++- crates/pollard-cli/src/main.rs | 98 ++--- crates/pollard-cli/src/mutate/apply.rs | 4 +- crates/pollard-cli/src/mutate/generate.rs | 4 +- crates/pollard-cli/src/mutate/view.rs | 4 +- crates/pollard-cli/src/session.rs | 126 ------ .../src/steps/apply_mutant_to_workspace.rs | 6 +- crates/pollard-cli/src/steps/cleanup.rs | 6 +- .../src/steps/create_workspaces.rs | 6 +- .../pollard-cli/src/steps/derive_mutants.rs | 6 +- crates/pollard-cli/src/steps/find_files.rs | 6 +- crates/pollard-cli/src/steps/mod.rs | 6 +- .../pollard-cli/src/steps/reset_workspace.rs | 6 +- .../pollard-cli/src/steps/setup_workspace.rs | 2 +- .../pollard-cli/src/steps/test_workspace.rs | 2 +- crates/pollard-core/Cargo.toml | 1 - crates/pollard-core/src/config.rs | 95 ----- crates/pollard-session-derive/Cargo.toml | 13 + crates/pollard-session-derive/src/lib.rs | 10 + crates/pollard-session-derive/src/settings.rs | 359 ++++++++++++++++++ crates/pollard-session/Cargo.toml | 13 + crates/pollard-session/src/config.rs | 62 +++ crates/pollard-session/src/lib.rs | 72 ++++ crates/pollard-session/tests/smoke.rs | 112 ++++++ 26 files changed, 759 insertions(+), 338 deletions(-) delete mode 100644 crates/pollard-cli/src/session.rs create mode 100644 crates/pollard-session-derive/Cargo.toml create mode 100644 crates/pollard-session-derive/src/lib.rs create mode 100644 crates/pollard-session-derive/src/settings.rs create mode 100644 crates/pollard-session/Cargo.toml create mode 100644 crates/pollard-session/src/config.rs create mode 100644 crates/pollard-session/src/lib.rs create mode 100644 crates/pollard-session/tests/smoke.rs diff --git a/Cargo.lock b/Cargo.lock index 86d2c204..b1cc509d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -270,11 +270,11 @@ dependencies = [ "clap", "glob", "pollard-core", + "pollard-session", "serde", "serde_json", "similar", "terminal_size", - "toml", ] [[package]] @@ -285,7 +285,6 @@ dependencies = [ "serde", "serde_json", "sha2", - "toml", "tree-sitter", "tree-sitter-javascript", "tree-sitter-typescript", @@ -295,6 +294,27 @@ dependencies = [ name = "pollard-lib" version = "0.0.0" +[[package]] +name = "pollard-session" +version = "0.0.0" +dependencies = [ + "clap", + "pollard-core", + "pollard-session-derive", + "serde", + "serde_json", + "toml", +] + +[[package]] +name = "pollard-session-derive" +version = "0.0.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "proc-macro2" version = "1.0.106" diff --git a/crates/pollard-cli/Cargo.toml b/crates/pollard-cli/Cargo.toml index 2d6a55a7..e06adf68 100644 --- a/crates/pollard-cli/Cargo.toml +++ b/crates/pollard-cli/Cargo.toml @@ -8,8 +8,8 @@ license.workspace = true clap = { version = "4", features = ["derive", "env"] } glob = "0.3.3" pollard-core = { path = "../pollard-core" } +pollard-session = { path = "../pollard-session" } serde = { version = "1", features = ["derive"] } serde_json = "1" similar = "2" terminal_size = "0.4" -toml = "1.0.3" diff --git a/crates/pollard-cli/src/io.rs b/crates/pollard-cli/src/io.rs index 98c9d0f5..0c2f2d7c 100644 --- a/crates/pollard-cli/src/io.rs +++ b/crates/pollard-cli/src/io.rs @@ -1,24 +1,12 @@ use serde::Serialize; use std::path::PathBuf; -#[derive(Debug, Clone, Serialize, clap::ValueEnum)] -pub enum DiffStyle { - Unified, - SideBySide, -} - -#[derive(Debug, Clone, Serialize, clap::ValueEnum)] -pub enum Style { - Plain, - Pretty, - Json, - Markdown, -} +pub use pollard_session::{DiffStyle, Session, Style}; pub trait Report { fn render(&self, style: &Style, no_color: bool, depth: u8); - fn get_dir(&self, session: &crate::session::Session) -> PathBuf; - fn make_path(&self, session: &crate::session::Session) -> PathBuf; + fn get_dir(&self, session: &Session) -> PathBuf; + fn make_path(&self, session: &Session) -> PathBuf; } pub fn hashed_path(dir: &PathBuf, content: &str, label: &str) -> PathBuf { @@ -92,11 +80,11 @@ fn color(code: &str, text: &str, no_color: bool) -> String { } impl Report for Action { - fn get_dir(&self, session: &crate::session::Session) -> PathBuf { + fn get_dir(&self, session: &Session) -> PathBuf { session.report_dir.join("action") } - fn make_path(&self, session: &crate::session::Session) -> PathBuf { + fn make_path(&self, session: &Session) -> PathBuf { let content = serde_json::to_string(self).expect("failed to serialize"); hashed_path(&self.get_dir(session), &content, "action") } @@ -152,3 +140,33 @@ impl Report for Action { } } +pub struct SessionReport { + json: String, + debug: String, +} + +impl SessionReport { + pub fn new(session: &Session) -> Self { + Self { + json: serde_json::to_string_pretty(session).expect("failed to serialize"), + debug: format!("{session:#?}"), + } + } +} + +impl Report for SessionReport { + fn get_dir(&self, session: &Session) -> PathBuf { + session.report_dir.join("session") + } + + fn make_path(&self, session: &Session) -> PathBuf { + hashed_path(&self.get_dir(session), &self.json, "session") + } + + fn render(&self, style: &Style, _no_color: bool, _depth: u8) { + match style { + Style::Json => println!("{}", self.json), + _ => println!("{}", self.debug), + } + } +} diff --git a/crates/pollard-cli/src/main.rs b/crates/pollard-cli/src/main.rs index 4ea143a8..4019b52f 100644 --- a/crates/pollard-cli/src/main.rs +++ b/crates/pollard-cli/src/main.rs @@ -1,71 +1,23 @@ mod io; mod mutate; -mod session; mod steps; use clap::{Parser, Subcommand}; -use io::{Action, Report, Style}; +use io::{Action, Report}; use pollard_core::Hash; -use pollard_core::config::{Config, LanguageId, Ordering, Vcs}; -use session::Session; +use pollard_session::{ + PartialSession, Session, SessionSkipped, discover_config, read_config, +}; use std::path::PathBuf; #[derive(Debug, Parser)] #[command(name = "pollard", about = "Cross-language mutation testing")] struct Cli { - #[arg(short, long, global = true)] - language: Option, - - #[arg(short, long, default_value = "plain", global = true)] - style: Style, - - #[arg(long, default_value = "unified", global = true)] - diff: io::DiffStyle, - - #[arg( - long, - env = "NO_COLOR", - hide = true, - default_value_t = false, - global = true - )] - no_color: bool, - #[arg(long, global = true)] config: Option, - #[arg(long, global = true)] - vcs: Option, - - #[arg(long, global = true)] - working_dir: Option, - - #[arg(long, global = true)] - parallelism: Option, - - #[arg(long, global = true)] - report_dir: Option, - - #[arg(long, global = true)] - ordering: Option, - - #[arg(long, global = true)] - sub_dir: Option, - - #[arg(long, global = true)] - files: Option, - - #[arg(long, global = true)] - ignore_mutants: Vec, - - #[arg(long, global = true)] - timeout_absolute: Option, - - #[arg(long, global = true)] - timeout_relative: Option, - - #[arg(long, global = true, default_value_t = false)] - exec: bool, + #[command(flatten)] + settings: PartialSession, #[command(subcommand)] command: Command, @@ -152,16 +104,14 @@ fn render_and_apply(actions: Vec, reports: Vec>, session } } -fn main() { - let cli = Cli::parse(); - +fn build_session(cli: Cli) -> (Session, Command) { let cwd = std::env::current_dir().expect("failed to get current directory"); let discovered = match &cli.config { - Some(path) => Some((path.clone(), Config::read(path))), - None => Config::discover(&cwd), + Some(path) => Some((path.clone(), read_config(path))), + None => discover_config(&cwd), }; - let (config_path, config) = match discovered { - Some((path, Ok(config))) => (path, config), + let (config_path, config_partial) = match discovered { + Some((path, Ok(partial))) => (path, partial), Some((path, Err(e))) => { eprintln!("error in {}: {e}", path.display()); std::process::exit(1); @@ -171,12 +121,26 @@ fn main() { std::process::exit(1); } }; - let session = Session::from_cli_and_config(&cli, config, config_path).unwrap_or_else(|e| { - eprintln!("{e}"); - std::process::exit(1); - }); - let (actions, reports): (Vec, Vec>) = match &cli.command { + let merged = cli.settings.merge(config_partial); + + let session = merged + .resolve(SessionSkipped { + config_path, + }) + .unwrap_or_else(|e| { + eprintln!("{e}"); + std::process::exit(1); + }); + + (session, cli.command) +} + +fn main() { + let cli = Cli::parse(); + let (session, command) = build_session(cli); + + let (actions, reports): (Vec, Vec>) = match &command { Command::Mutate { action: MutateAction::Generate { file: pattern }, } => { @@ -277,7 +241,7 @@ fn main() { (actions, vec![Box::new(report)]) } Command::DumpSession => { - let report = session::SessionReport::new(&session); + let report = io::SessionReport::new(&session); (vec![], vec![Box::new(report)]) } }; diff --git a/crates/pollard-cli/src/mutate/apply.rs b/crates/pollard-cli/src/mutate/apply.rs index 26e6a3fe..85b86460 100644 --- a/crates/pollard-cli/src/mutate/apply.rs +++ b/crates/pollard-cli/src/mutate/apply.rs @@ -43,11 +43,11 @@ pub struct ApplyReport { } impl Report for ApplyReport { - fn get_dir(&self, session: &crate::session::Session) -> PathBuf { + fn get_dir(&self, session: &pollard_session::Session) -> PathBuf { session.report_dir.join("mutate").join("apply") } - fn make_path(&self, session: &crate::session::Session) -> PathBuf { + fn make_path(&self, session: &pollard_session::Session) -> PathBuf { let content = serde_json::to_string(self).expect("failed to serialize"); hashed_path(&self.get_dir(session), &content, "applied") } diff --git a/crates/pollard-cli/src/mutate/generate.rs b/crates/pollard-cli/src/mutate/generate.rs index c271ce5e..00d4d77f 100644 --- a/crates/pollard-cli/src/mutate/generate.rs +++ b/crates/pollard-cli/src/mutate/generate.rs @@ -64,11 +64,11 @@ pub struct GenerateReport { } impl Report for GenerateReport { - fn get_dir(&self, session: &crate::session::Session) -> PathBuf { + fn get_dir(&self, session: &pollard_session::Session) -> PathBuf { session.report_dir.join("mutate").join("generate") } - fn make_path(&self, session: &crate::session::Session) -> PathBuf { + fn make_path(&self, session: &pollard_session::Session) -> PathBuf { let content = serde_json::to_string(self).expect("failed to serialize"); hashed_path(&self.get_dir(session), &content, "mutations") } diff --git a/crates/pollard-cli/src/mutate/view.rs b/crates/pollard-cli/src/mutate/view.rs index 484bf8b8..ed5901bc 100644 --- a/crates/pollard-cli/src/mutate/view.rs +++ b/crates/pollard-cli/src/mutate/view.rs @@ -34,11 +34,11 @@ pub struct ViewReport { } impl Report for ViewReport { - fn get_dir(&self, session: &crate::session::Session) -> PathBuf { + fn get_dir(&self, session: &pollard_session::Session) -> PathBuf { session.report_dir.join("mutate").join("view") } - fn make_path(&self, session: &crate::session::Session) -> PathBuf { + fn make_path(&self, session: &pollard_session::Session) -> PathBuf { let content = format!("{}:{}:{}", self.path, self.old, self.new); hashed_path(&self.get_dir(session), &content, "diff") } diff --git a/crates/pollard-cli/src/session.rs b/crates/pollard-cli/src/session.rs deleted file mode 100644 index 8a0c2b5a..00000000 --- a/crates/pollard-cli/src/session.rs +++ /dev/null @@ -1,126 +0,0 @@ -use std::path::PathBuf; - -use pollard_core::config::{Commands, Config, LanguageId, Ordering, Vcs}; -use serde::Serialize; - -use crate::io::{DiffStyle, Report, Style, hashed_path}; -use crate::Cli; - -pub struct SessionReport { - json: String, - debug: String, -} - -impl SessionReport { - pub fn new(session: &Session) -> Self { - Self { - json: serde_json::to_string_pretty(session).expect("failed to serialize"), - debug: format!("{session:#?}"), - } - } -} - -impl Report for SessionReport { - fn get_dir(&self, session: &Session) -> PathBuf { - session.report_dir.join("session") - } - - fn make_path(&self, session: &Session) -> PathBuf { - hashed_path(&self.get_dir(session), &self.json, "session") - } - - fn render(&self, style: &Style, _no_color: bool, _depth: u8) { - match style { - Style::Json => println!("{}", self.json), - _ => println!("{}", self.debug), - } - } -} - -// All fields are resolved and non-optional. No defaults are applied here; -// every value must be provided by CLI args or config. No Option types allowed. -#[derive(Debug, Serialize)] -pub struct Session { - pub language: LanguageId, - pub vcs: Vcs, - pub working_dir: PathBuf, - pub parallelism: usize, - pub report_dir: PathBuf, - pub ordering: Ordering, - pub sub_dir: PathBuf, - pub files: String, - pub ignore_mutants: Vec, - pub timeout_absolute: u64, - pub timeout_relative: f64, - pub style: Style, - pub diff: DiffStyle, - pub no_color: bool, - pub exec: bool, - pub config_path: PathBuf, - pub commands: Commands, -} - -macro_rules! require { - ($missing:ident, $expr:expr, $name:literal, $hint:literal) => { - { - let val = $expr; - if val.is_none() { - $missing.push(concat!($name, " (", $hint, ")")); - } - val - } - }; -} - -impl Session { - pub fn from_cli_and_config( - cli: &Cli, - config: Config, - config_path: PathBuf, - ) -> Result { - let mut missing: Vec<&str> = Vec::new(); - - let language = require!(missing, cli.language.or(config.language), "language", "use -l/--language or set in config"); - let vcs = require!(missing, cli.vcs.or(config.vcs), "vcs", "use --vcs or set in config"); - let working_dir = require!(missing, cli.working_dir.clone().or(config.working_dir.clone()), "working_dir", "use --working-dir or set in config"); - let parallelism = require!(missing, cli.parallelism.or(config.parallelism), "parallelism", "use --parallelism or set in config"); - let report_dir = require!(missing, cli.report_dir.clone().or(config.report_dir.clone()), "report_dir", "use --report-dir or set in config"); - let ordering = require!(missing, cli.ordering.or(config.ordering), "ordering", "use --ordering or set in config"); - let files = require!(missing, cli.files.clone().or(config.files.clone()), "files", "use --files or set in config"); - let timeout_absolute = require!(missing, cli.timeout_absolute.or(config.timeout.absolute), "timeout.absolute", "use --timeout-absolute or set in config"); - let timeout_relative = require!(missing, cli.timeout_relative.or(config.timeout.relative), "timeout.relative", "use --timeout-relative or set in config"); - - if !missing.is_empty() { - return Err(format!( - "missing required settings:\n - {}", - missing.join("\n - ") - )); - } - - Ok(Self { - language: language.unwrap(), - vcs: vcs.unwrap(), - working_dir: working_dir.unwrap(), - parallelism: parallelism.unwrap(), - report_dir: report_dir.unwrap(), - ordering: ordering.unwrap(), - sub_dir: cli.sub_dir.clone() - .or(config.sub_dir.clone()) - .unwrap_or_else(|| PathBuf::from(".")), - files: files.unwrap(), - timeout_absolute: timeout_absolute.unwrap(), - timeout_relative: timeout_relative.unwrap(), - ignore_mutants: if cli.ignore_mutants.is_empty() { - config.ignore_mutants - } else { - cli.ignore_mutants.clone() - }, - style: cli.style.clone(), - diff: cli.diff.clone(), - no_color: cli.no_color, - exec: cli.exec, - config_path, - commands: config.commands, - }) - } -} diff --git a/crates/pollard-cli/src/steps/apply_mutant_to_workspace.rs b/crates/pollard-cli/src/steps/apply_mutant_to_workspace.rs index a4120960..8b6f517c 100644 --- a/crates/pollard-cli/src/steps/apply_mutant_to_workspace.rs +++ b/crates/pollard-cli/src/steps/apply_mutant_to_workspace.rs @@ -1,5 +1,5 @@ use crate::io::{Action, Report, Style, hashed_path}; -use crate::session::Session; +use pollard_session::Session; use crate::steps::{color, find_workspace, read_plan, read_workspace_manifest}; use pollard_core::Hash; use serde::Serialize; @@ -67,14 +67,14 @@ pub struct ApplyMutantToWorkspaceReport { } impl Report for ApplyMutantToWorkspaceReport { - fn get_dir(&self, session: &crate::session::Session) -> PathBuf { + fn get_dir(&self, session: &pollard_session::Session) -> PathBuf { session .report_dir .join("step") .join("apply-mutant-to-workspace") } - fn make_path(&self, session: &crate::session::Session) -> PathBuf { + fn make_path(&self, session: &pollard_session::Session) -> PathBuf { let content = serde_json::to_string(self).expect("failed to serialize"); hashed_path(&self.get_dir(session), &content, "applied") } diff --git a/crates/pollard-cli/src/steps/cleanup.rs b/crates/pollard-cli/src/steps/cleanup.rs index 60930914..00778850 100644 --- a/crates/pollard-cli/src/steps/cleanup.rs +++ b/crates/pollard-cli/src/steps/cleanup.rs @@ -1,5 +1,5 @@ use crate::io::{Action, Report, Style, hashed_path}; -use crate::session::Session; +use pollard_session::Session; use crate::steps::{color, expand_glob}; use serde::Serialize; use std::path::PathBuf; @@ -52,11 +52,11 @@ pub struct CleanupReport { } impl Report for CleanupReport { - fn get_dir(&self, session: &crate::session::Session) -> PathBuf { + fn get_dir(&self, session: &pollard_session::Session) -> PathBuf { session.report_dir.join("step").join("cleanup") } - fn make_path(&self, session: &crate::session::Session) -> PathBuf { + fn make_path(&self, session: &pollard_session::Session) -> PathBuf { let content = serde_json::to_string(self).expect("failed to serialize"); hashed_path(&self.get_dir(session), &content, "cleanup") } diff --git a/crates/pollard-cli/src/steps/create_workspaces.rs b/crates/pollard-cli/src/steps/create_workspaces.rs index 1dd0a48e..ea5e5cc7 100644 --- a/crates/pollard-cli/src/steps/create_workspaces.rs +++ b/crates/pollard-cli/src/steps/create_workspaces.rs @@ -1,5 +1,5 @@ use crate::io::{Action, Report, Style, hashed_path}; -use crate::session::Session; +use pollard_session::Session; use crate::steps::{color, content_id}; use pollard_core::config::Vcs; use serde::Serialize; @@ -64,11 +64,11 @@ pub struct CreateWorkspacesReport { } impl Report for CreateWorkspacesReport { - fn get_dir(&self, session: &crate::session::Session) -> PathBuf { + fn get_dir(&self, session: &pollard_session::Session) -> PathBuf { session.report_dir.join("step").join("create-workspaces") } - fn make_path(&self, session: &crate::session::Session) -> PathBuf { + fn make_path(&self, session: &pollard_session::Session) -> PathBuf { let content = serde_json::to_string(self).expect("failed to serialize"); hashed_path(&self.get_dir(session), &content, "workspaces") } diff --git a/crates/pollard-cli/src/steps/derive_mutants.rs b/crates/pollard-cli/src/steps/derive_mutants.rs index 7ad275ff..14b9ccb9 100644 --- a/crates/pollard-cli/src/steps/derive_mutants.rs +++ b/crates/pollard-cli/src/steps/derive_mutants.rs @@ -1,5 +1,5 @@ use crate::io::{Action, Report, Style, hashed_path}; -use crate::session::Session; +use pollard_session::Session; use crate::steps::{color, content_id}; use pollard_core::config::LanguageId; use pollard_core::languages::javascript::JavaScript; @@ -78,11 +78,11 @@ pub struct DeriveMutantsReport { } impl Report for DeriveMutantsReport { - fn get_dir(&self, session: &crate::session::Session) -> PathBuf { + fn get_dir(&self, session: &pollard_session::Session) -> PathBuf { session.report_dir.join("step").join("derive-mutants") } - fn make_path(&self, session: &crate::session::Session) -> PathBuf { + fn make_path(&self, session: &pollard_session::Session) -> PathBuf { let content = serde_json::to_string(self).expect("failed to serialize"); hashed_path(&self.get_dir(session), &content, "plan") } diff --git a/crates/pollard-cli/src/steps/find_files.rs b/crates/pollard-cli/src/steps/find_files.rs index f35895ba..3bc0594c 100644 --- a/crates/pollard-cli/src/steps/find_files.rs +++ b/crates/pollard-cli/src/steps/find_files.rs @@ -1,5 +1,5 @@ use crate::io::{Action, Report, Style, hashed_path}; -use crate::session::Session; +use pollard_session::Session; use crate::steps::expand_glob; use serde::Serialize; use std::path::PathBuf; @@ -22,11 +22,11 @@ pub struct FindFilesReport { } impl Report for FindFilesReport { - fn get_dir(&self, session: &crate::session::Session) -> PathBuf { + fn get_dir(&self, session: &pollard_session::Session) -> PathBuf { session.report_dir.join("step").join("find-files") } - fn make_path(&self, session: &crate::session::Session) -> PathBuf { + fn make_path(&self, session: &pollard_session::Session) -> PathBuf { let content = serde_json::to_string(self).expect("failed to serialize"); hashed_path(&self.get_dir(session), &content, "files") } diff --git a/crates/pollard-cli/src/steps/mod.rs b/crates/pollard-cli/src/steps/mod.rs index f6944e6b..2e773084 100644 --- a/crates/pollard-cli/src/steps/mod.rs +++ b/crates/pollard-cli/src/steps/mod.rs @@ -8,7 +8,7 @@ pub mod setup_workspace; pub mod test_workspace; use crate::io::{Report, Style, hashed_path}; -use crate::session::Session; +use pollard_session::Session; use pollard_core::plan::{Plan, WorkspaceManifest}; use serde::Serialize; use std::path::PathBuf; @@ -141,11 +141,11 @@ pub struct CommandReport { } impl Report for CommandReport { - fn get_dir(&self, session: &crate::session::Session) -> PathBuf { + fn get_dir(&self, session: &pollard_session::Session) -> PathBuf { session.report_dir.join("step").join(&self.step) } - fn make_path(&self, session: &crate::session::Session) -> PathBuf { + fn make_path(&self, session: &pollard_session::Session) -> PathBuf { let content = serde_json::to_string(self).expect("failed to serialize"); hashed_path(&self.get_dir(session), &content, "command") } diff --git a/crates/pollard-cli/src/steps/reset_workspace.rs b/crates/pollard-cli/src/steps/reset_workspace.rs index c9937d0f..fdc05186 100644 --- a/crates/pollard-cli/src/steps/reset_workspace.rs +++ b/crates/pollard-cli/src/steps/reset_workspace.rs @@ -1,5 +1,5 @@ use crate::io::{Action, Report, Style, hashed_path}; -use crate::session::Session; +use pollard_session::Session; use crate::steps::{color, find_workspace, read_workspace_manifest}; use pollard_core::config::Vcs; use serde::Serialize; @@ -51,11 +51,11 @@ pub struct ResetWorkspaceReport { } impl Report for ResetWorkspaceReport { - fn get_dir(&self, session: &crate::session::Session) -> PathBuf { + fn get_dir(&self, session: &pollard_session::Session) -> PathBuf { session.report_dir.join("step").join("reset-workspace") } - fn make_path(&self, session: &crate::session::Session) -> PathBuf { + fn make_path(&self, session: &pollard_session::Session) -> PathBuf { let content = serde_json::to_string(self).expect("failed to serialize"); hashed_path(&self.get_dir(session), &content, "reset") } diff --git a/crates/pollard-cli/src/steps/setup_workspace.rs b/crates/pollard-cli/src/steps/setup_workspace.rs index 467dc8cf..7d599eca 100644 --- a/crates/pollard-cli/src/steps/setup_workspace.rs +++ b/crates/pollard-cli/src/steps/setup_workspace.rs @@ -1,5 +1,5 @@ use crate::io::Action; -use crate::session::Session; +use pollard_session::Session; use crate::steps::{run_in_workspace, CommandReport}; pub fn run(session: &Session, workspace: &str) -> (Vec, Option) { diff --git a/crates/pollard-cli/src/steps/test_workspace.rs b/crates/pollard-cli/src/steps/test_workspace.rs index 940260d9..bdcdc8e9 100644 --- a/crates/pollard-cli/src/steps/test_workspace.rs +++ b/crates/pollard-cli/src/steps/test_workspace.rs @@ -1,5 +1,5 @@ use crate::io::Action; -use crate::session::Session; +use pollard_session::Session; use crate::steps::{run_in_workspace, CommandReport}; pub fn run(session: &Session, workspace: &str) -> (Vec, Option) { diff --git a/crates/pollard-core/Cargo.toml b/crates/pollard-core/Cargo.toml index 492f322e..de72fb55 100644 --- a/crates/pollard-core/Cargo.toml +++ b/crates/pollard-core/Cargo.toml @@ -9,7 +9,6 @@ clap = { version = "4.5.60", features = ["derive"] } serde = { version = "1", features = ["derive"] } serde_json = "1.0.149" sha2 = "0.10" -toml = "1.0.3" tree-sitter = "0.26" tree-sitter-javascript = "0.25" tree-sitter-typescript = "0.23" diff --git a/crates/pollard-core/src/config.rs b/crates/pollard-core/src/config.rs index 0913116e..8aa73d55 100644 --- a/crates/pollard-core/src/config.rs +++ b/crates/pollard-core/src/config.rs @@ -1,5 +1,4 @@ use serde::{Deserialize, Serialize}; -use std::path::{Path, PathBuf}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)] #[serde(rename_all = "lowercase")] @@ -26,97 +25,3 @@ pub enum Ordering { Random, Alphabetical, } - -#[derive(Debug, Default, Clone, Serialize, Deserialize)] -pub struct Commands { - pub install: Option, - pub build: Option, - pub test: String, - pub cleanup: Option, -} - -#[derive(Debug, Default, Clone, Serialize, Deserialize)] -pub struct Config { - pub language: Option, - pub vcs: Option, - pub working_dir: Option, - pub parallelism: Option, - pub report_dir: Option, - pub ordering: Option, - pub sub_dir: Option, - pub files: Option, - #[serde(default)] - pub ignore_mutants: Vec, - #[serde(default)] - pub timeout: Timeout, - #[serde(default)] - pub commands: Commands, -} - -#[derive(Debug, Default, Clone, Serialize, Deserialize)] -pub struct Timeout { - pub absolute: Option, - pub relative: Option, -} - -#[derive(Debug)] -pub enum ConfigError { - Io(std::io::Error), - Toml(toml::de::Error), - Json(serde_json::Error), - UnknownExtension(PathBuf), -} - -impl std::fmt::Display for ConfigError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Io(e) => write!(f, "failed to read config: {e}"), - Self::Toml(e) => write!(f, "invalid toml: {e}"), - Self::Json(e) => write!(f, "invalid json: {e}"), - Self::UnknownExtension(p) => write!(f, "unknown config extension: {}", p.display()), - } - } -} - -impl std::error::Error for ConfigError {} - -const SEARCH_PATHS: &[&str] = &[ - ".config/pollard.config.json", - ".config/pollard.config.toml", - ".config/pollard.json", - ".config/pollard.toml", - ".pollard.config.json", - ".pollard.config.toml", - ".pollard.json", - ".pollard.toml", - "pollard.config.json", - "pollard.config.toml", - "pollard.json", - "pollard.toml", -]; - -impl Config { - pub fn read(path: &Path) -> Result { - let content = std::fs::read_to_string(path).map_err(ConfigError::Io)?; - match path.extension().and_then(|e| e.to_str()) { - Some("toml") => toml::from_str(&content).map_err(ConfigError::Toml), - Some("json") => serde_json::from_str(&content).map_err(ConfigError::Json), - _ => Err(ConfigError::UnknownExtension(path.to_owned())), - } - } - - pub fn discover(from: &Path) -> Option<(PathBuf, Result)> { - let mut dir = from.to_path_buf(); - loop { - for name in SEARCH_PATHS { - let candidate = dir.join(name); - if candidate.is_file() { - return Some((candidate.clone(), Self::read(&candidate))); - } - } - if !dir.pop() { - return None; - } - } - } -} diff --git a/crates/pollard-session-derive/Cargo.toml b/crates/pollard-session-derive/Cargo.toml new file mode 100644 index 00000000..d1747136 --- /dev/null +++ b/crates/pollard-session-derive/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "pollard-session-derive" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1" +quote = "1" +syn = { version = "2", features = ["full", "extra-traits"] } diff --git a/crates/pollard-session-derive/src/lib.rs b/crates/pollard-session-derive/src/lib.rs new file mode 100644 index 00000000..a536089c --- /dev/null +++ b/crates/pollard-session-derive/src/lib.rs @@ -0,0 +1,10 @@ +use proc_macro::TokenStream; + +mod settings; + +#[proc_macro_derive(Settings, attributes(setting))] +pub fn derive_settings(input: TokenStream) -> TokenStream { + settings::derive(input.into()) + .unwrap_or_else(|e| e.to_compile_error()) + .into() +} diff --git a/crates/pollard-session-derive/src/settings.rs b/crates/pollard-session-derive/src/settings.rs new file mode 100644 index 00000000..d832fb6b --- /dev/null +++ b/crates/pollard-session-derive/src/settings.rs @@ -0,0 +1,359 @@ +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; +use syn::{ + Data, DeriveInput, Field, Fields, GenericArgument, Lit, PathArguments, Type, + parse2, +}; + +struct FieldInfo { + ident: syn::Ident, + ty: Type, + is_option: bool, + is_vec: bool, + skip: bool, + cli_only: bool, + flatten: bool, + default_expr: Option, + env: Option, + long: Option, +} + +fn extract_inner_type(ty: &Type) -> Option<&Type> { + if let Type::Path(type_path) = ty { + let seg = type_path.path.segments.last()?; + if seg.ident == "Option" || seg.ident == "Vec" { + if let PathArguments::AngleBracketed(args) = &seg.arguments { + if let Some(GenericArgument::Type(inner)) = args.args.first() { + return Some(inner); + } + } + } + } + None +} + +fn is_type_wrapper(ty: &Type, name: &str) -> bool { + if let Type::Path(type_path) = ty { + if let Some(seg) = type_path.path.segments.last() { + return seg.ident == name; + } + } + false +} + +fn parse_field(field: &Field) -> syn::Result { + let ident = field.ident.clone().expect("named fields only"); + let ty = field.ty.clone(); + let is_option = is_type_wrapper(&ty, "Option"); + let is_vec = is_type_wrapper(&ty, "Vec"); + + let mut skip = false; + let mut cli_only = false; + let mut flatten = false; + let mut default_expr = None; + let mut env = None; + let mut long = None; + + for attr in &field.attrs { + if !attr.path().is_ident("setting") { + continue; + } + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("skip") { + skip = true; + } else if meta.path.is_ident("cli_only") { + cli_only = true; + } else if meta.path.is_ident("flatten") { + flatten = true; + } else if meta.path.is_ident("default") { + let value = meta.value()?; + let lit: Lit = value.parse()?; + if let Lit::Str(s) = lit { + let expr: TokenStream = s.parse()?; + default_expr = Some(expr); + } + } else if meta.path.is_ident("env") { + let value = meta.value()?; + let lit: Lit = value.parse()?; + if let Lit::Str(s) = lit { + env = Some(s.value()); + } + } else if meta.path.is_ident("long") { + let value = meta.value()?; + let lit: Lit = value.parse()?; + if let Lit::Str(s) = lit { + long = Some(s.value()); + } + } + Ok(()) + })?; + } + + Ok(FieldInfo { + ident, + ty, + is_option, + is_vec, + skip, + cli_only, + flatten, + default_expr, + env, + long, + }) +} + +fn partial_ident(original: &syn::Ident) -> syn::Ident { + format_ident!("Partial{}", original) +} + +pub fn derive(input: TokenStream) -> syn::Result { + let input: DeriveInput = parse2(input)?; + let vis = &input.vis; + let name = &input.ident; + let partial_name = partial_ident(name); + + let fields = match &input.data { + Data::Struct(data) => match &data.fields { + Fields::Named(named) => &named.named, + _ => return Err(syn::Error::new_spanned(&input, "expected named fields")), + }, + _ => return Err(syn::Error::new_spanned(&input, "expected struct")), + }; + + let parsed: Vec = fields.iter().map(parse_field).collect::>()?; + + let partial_fields = gen_partial_fields(&parsed); + let merge_fields = gen_merge_fields(&parsed); + let resolve_fields = gen_resolve_fields(&parsed, name); + let skipped_fields = gen_skipped_struct(&parsed, name, vis); + + Ok(quote! { + #[derive(Default, Clone, Debug, clap::Args, serde::Deserialize)] + #[serde(default)] + #vis struct #partial_name { + #(#partial_fields)* + } + + #skipped_fields + + impl #partial_name { + #vis fn merge(self, fallback: Self) -> Self { + Self { + #(#merge_fields)* + } + } + + #resolve_fields + } + }) +} + +fn gen_partial_fields(fields: &[FieldInfo]) -> Vec { + fields + .iter() + .filter(|f| !f.skip) + .map(|f| { + let ident = &f.ident; + let long_name = f.long.clone().unwrap_or_else(|| { + ident.to_string().replace('_', "-") + }); + + if f.flatten { + let inner = extract_inner_type(&f.ty).unwrap_or(&f.ty); + let partial_ty = if let Type::Path(tp) = inner { + let seg = tp.path.segments.last().unwrap(); + let partial = format_ident!("Partial{}", seg.ident); + quote! { #partial } + } else { + quote! { #inner } + }; + + quote! { + #[command(flatten)] + #[serde(default)] + pub #ident: #partial_ty, + } + } else if f.is_vec { + let inner = extract_inner_type(&f.ty).unwrap_or(&f.ty); + let serde_skip = if f.cli_only { + quote! { #[serde(skip)] } + } else { + quote! { #[serde(default)] } + }; + let env_attr = f.env.as_ref().map(|e| quote! { env = #e, }); + quote! { + #[arg(long = #long_name, global = true, #env_attr)] + #serde_skip + pub #ident: Vec<#inner>, + } + } else { + let ty = if f.is_option { + let inner = extract_inner_type(&f.ty).unwrap(); + quote! { Option<#inner> } + } else { + let ty = &f.ty; + quote! { Option<#ty> } + }; + + let serde_skip = if f.cli_only { + quote! { #[serde(skip)] } + } else { + quote! { #[serde(default)] } + }; + + let env_attr = f.env.as_ref().map(|e| quote! { env = #e, }); + let hide_env = f.env.as_ref().map(|_| quote! { hide_env = true, }); + + quote! { + #[arg(long = #long_name, global = true, #env_attr #hide_env)] + #serde_skip + pub #ident: #ty, + } + } + }) + .collect() +} + +fn gen_merge_fields(fields: &[FieldInfo]) -> Vec { + fields + .iter() + .filter(|f| !f.skip) + .map(|f| { + let ident = &f.ident; + if f.flatten { + quote! { #ident: self.#ident.merge(fallback.#ident), } + } else if f.is_vec { + quote! { + #ident: if self.#ident.is_empty() { + fallback.#ident + } else { + self.#ident + }, + } + } else { + quote! { #ident: self.#ident.or(fallback.#ident), } + } + }) + .collect() +} + +fn gen_resolve_fields(fields: &[FieldInfo], struct_name: &syn::Ident) -> TokenStream { + let skipped_name = format_ident!("{}Skipped", struct_name); + let has_skip_fields = fields.iter().any(|f| f.skip); + + // Phase 1: check required fields, collect missing + let check_stmts: Vec = fields + .iter() + .filter(|f| !f.skip && !f.flatten && !f.is_vec && !f.is_option && f.default_expr.is_none()) + .map(|f| { + let field_name = f.ident.to_string(); + let ident = &f.ident; + quote! { + if self.#ident.is_none() { + missing.push(#field_name); + } + } + }) + .collect(); + + // Phase 2: build the struct (only reached if no missing fields) + let resolve_assignments: Vec = fields + .iter() + .map(|f| { + let ident = &f.ident; + + if f.skip { + return quote! { #ident: skipped.#ident, }; + } + + if f.flatten { + let inner_has_skip = false; // sub-structs don't have skip fields in our usage + if inner_has_skip { + return quote! { #ident: self.#ident.resolve(/* skipped */)?, }; + } + return quote! { #ident: self.#ident.resolve_no_skip()?, }; + } + + if f.is_vec { + return quote! { #ident: self.#ident, }; + } + + if f.is_option { + return quote! { #ident: self.#ident, }; + } + + match &f.default_expr { + Some(default) => quote! { + #ident: self.#ident.unwrap_or_else(|| #default), + }, + None => quote! { + #ident: self.#ident.unwrap(), + }, + } + }) + .collect(); + + let resolve_with_skip = if has_skip_fields { + quote! { + pub fn resolve(self, skipped: #skipped_name) -> Result<#struct_name, String> { + let mut missing: Vec<&str> = Vec::new(); + #(#check_stmts)* + if !missing.is_empty() { + return Err(format!( + "missing required settings:\n - {}", + missing.join("\n - ") + )); + } + Ok(#struct_name { + #(#resolve_assignments)* + }) + } + } + } else { + // No skip fields — generate resolve_no_skip that takes no args + quote! { + pub fn resolve_no_skip(self) -> Result<#struct_name, String> { + let mut missing: Vec<&str> = Vec::new(); + #(#check_stmts)* + if !missing.is_empty() { + return Err(format!( + "missing required settings:\n - {}", + missing.join("\n - ") + )); + } + // skipped is unused but needed for struct construction + let skipped = #skipped_name {}; + Ok(#struct_name { + #(#resolve_assignments)* + }) + } + } + }; + + resolve_with_skip +} + +fn gen_skipped_struct( + fields: &[FieldInfo], + struct_name: &syn::Ident, + vis: &syn::Visibility, +) -> TokenStream { + let skipped_name = format_ident!("{}Skipped", struct_name); + + let skipped_fields: Vec = fields + .iter() + .filter(|f| f.skip) + .map(|f| { + let ident = &f.ident; + let ty = &f.ty; + quote! { pub #ident: #ty, } + }) + .collect(); + + quote! { + #vis struct #skipped_name { + #(#skipped_fields)* + } + } +} diff --git a/crates/pollard-session/Cargo.toml b/crates/pollard-session/Cargo.toml new file mode 100644 index 00000000..8d279796 --- /dev/null +++ b/crates/pollard-session/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "pollard-session" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +clap = { version = "4", features = ["derive", "env"] } +pollard-core = { path = "../pollard-core" } +pollard-session-derive = { path = "../pollard-session-derive" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "1.0.3" diff --git a/crates/pollard-session/src/config.rs b/crates/pollard-session/src/config.rs new file mode 100644 index 00000000..00535482 --- /dev/null +++ b/crates/pollard-session/src/config.rs @@ -0,0 +1,62 @@ +use crate::PartialSession; +use std::path::{Path, PathBuf}; + +#[derive(Debug)] +pub enum ConfigError { + Io(std::io::Error), + Toml(toml::de::Error), + Json(serde_json::Error), + UnknownExtension(PathBuf), +} + +impl std::fmt::Display for ConfigError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Io(e) => write!(f, "failed to read config: {e}"), + Self::Toml(e) => write!(f, "invalid toml: {e}"), + Self::Json(e) => write!(f, "invalid json: {e}"), + Self::UnknownExtension(p) => write!(f, "unknown config extension: {}", p.display()), + } + } +} + +impl std::error::Error for ConfigError {} + +pub const SEARCH_PATHS: &[&str] = &[ + ".config/pollard.config.json", + ".config/pollard.config.toml", + ".config/pollard.json", + ".config/pollard.toml", + ".pollard.config.json", + ".pollard.config.toml", + ".pollard.json", + ".pollard.toml", + "pollard.config.json", + "pollard.config.toml", + "pollard.json", + "pollard.toml", +]; + +pub fn read_config(path: &Path) -> Result { + let content = std::fs::read_to_string(path).map_err(ConfigError::Io)?; + match path.extension().and_then(|e| e.to_str()) { + Some("toml") => toml::from_str(&content).map_err(ConfigError::Toml), + Some("json") => serde_json::from_str(&content).map_err(ConfigError::Json), + _ => Err(ConfigError::UnknownExtension(path.to_owned())), + } +} + +pub fn discover_config(from: &Path) -> Option<(PathBuf, Result)> { + let mut dir = from.to_path_buf(); + loop { + for name in SEARCH_PATHS { + let candidate = dir.join(name); + if candidate.is_file() { + return Some((candidate.clone(), read_config(&candidate))); + } + } + if !dir.pop() { + return None; + } + } +} diff --git a/crates/pollard-session/src/lib.rs b/crates/pollard-session/src/lib.rs new file mode 100644 index 00000000..e1a48f59 --- /dev/null +++ b/crates/pollard-session/src/lib.rs @@ -0,0 +1,72 @@ +mod config; + +pub use config::{discover_config, read_config, ConfigError, SEARCH_PATHS}; + +use pollard_core::config::{LanguageId, Ordering, Vcs}; +use pollard_session_derive::Settings; +use serde::Serialize; +use std::path::PathBuf; + +#[derive(Debug, Clone, Serialize, serde::Deserialize, clap::ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum Style { + Plain, + Pretty, + Json, + Markdown, +} + +#[derive(Debug, Clone, Serialize, serde::Deserialize, clap::ValueEnum)] +#[serde(rename_all = "kebab-case")] +pub enum DiffStyle { + Unified, + SideBySide, +} + +#[derive(Debug, Clone, Serialize, Settings)] +pub struct Commands { + #[setting(long = "command-install")] + pub install: Option, + #[setting(long = "command-build")] + pub build: Option, + #[setting(long = "command-test")] + pub test: String, + #[setting(long = "command-cleanup")] + pub cleanup: Option, +} + +#[derive(Debug, Clone, Serialize, Settings)] +pub struct Timeout { + #[setting(long = "timeout-absolute")] + pub absolute: u64, + #[setting(long = "timeout-relative")] + pub relative: f64, +} + +#[derive(Debug, Serialize, Settings)] +pub struct Session { + pub language: LanguageId, + pub vcs: Vcs, + pub working_dir: PathBuf, + pub parallelism: usize, + pub report_dir: PathBuf, + pub ordering: Ordering, + #[setting(default = "PathBuf::from(\".\")")] + pub sub_dir: PathBuf, + pub files: String, + pub ignore_mutants: Vec, + #[setting(flatten)] + pub timeout: Timeout, + #[setting(default = "Style::Plain")] + pub style: Style, + #[setting(default = "DiffStyle::Unified")] + pub diff: DiffStyle, + #[setting(env = "NO_COLOR", default = "false")] + pub no_color: bool, + #[setting(cli_only, default = "false")] + pub exec: bool, + #[setting(skip)] + pub config_path: PathBuf, + #[setting(flatten)] + pub commands: Commands, +} diff --git a/crates/pollard-session/tests/smoke.rs b/crates/pollard-session/tests/smoke.rs new file mode 100644 index 00000000..fa1ee2cd --- /dev/null +++ b/crates/pollard-session/tests/smoke.rs @@ -0,0 +1,112 @@ +use pollard_session::*; +use std::path::PathBuf; + +#[test] +fn merge_cli_overrides_config() { + let config = PartialSession { + language: Some(pollard_core::config::LanguageId::Javascript), + parallelism: Some(4), + ..Default::default() + }; + let cli = PartialSession { + parallelism: Some(8), + ..Default::default() + }; + let merged = cli.merge(config); + assert_eq!(merged.parallelism, Some(8)); + assert_eq!(merged.language, Some(pollard_core::config::LanguageId::Javascript)); +} + +#[test] +fn resolve_collects_missing() { + let partial = PartialSession::default(); + let result = partial.resolve(SessionSkipped { + config_path: PathBuf::from("test"), + }); + assert!(result.is_err()); + let err = result.unwrap_err(); + assert!(err.contains("language")); + assert!(err.contains("vcs")); +} + +#[test] +fn resolve_succeeds_with_all_fields() { + let partial = PartialSession { + language: Some(pollard_core::config::LanguageId::Javascript), + vcs: Some(pollard_core::config::Vcs::Jj), + working_dir: Some(PathBuf::from("/tmp")), + parallelism: Some(1), + report_dir: Some(PathBuf::from("/tmp/reports")), + ordering: Some(pollard_core::config::Ordering::Random), + files: Some("src/**/*.js".to_string()), + timeout: PartialTimeout { + absolute: Some(30), + relative: Some(1.5), + }, + commands: PartialCommands { + test: Some("npm test".to_string()), + ..Default::default() + }, + ..Default::default() + }; + let session = partial.resolve(SessionSkipped { + config_path: PathBuf::from("test.toml"), + }).unwrap(); + + assert_eq!(session.parallelism, 1); + assert_eq!(session.sub_dir, PathBuf::from(".")); + assert!(session.commands.install.is_none()); + assert_eq!(session.commands.test, "npm test"); + assert!(!session.exec); + assert!(!session.no_color); +} + +#[test] +fn deserialize_from_toml() { + let toml_str = r#" +language = "js" +vcs = "jj" +working_dir = "/tmp" +parallelism = 2 +report_dir = "/tmp/reports" +ordering = "random" +files = "src/**/*.js" + +[timeout] +absolute = 30 +relative = 1.5 + +[commands] +test = "npm test" +"#; + let partial: PartialSession = toml::from_str(toml_str).unwrap(); + assert_eq!(partial.language, Some(pollard_core::config::LanguageId::Javascript)); + assert_eq!(partial.parallelism, Some(2)); + assert_eq!(partial.timeout.absolute, Some(30)); + assert_eq!(partial.commands.test, Some("npm test".to_string())); +} + +#[test] +fn vec_merge_override() { + let config = PartialSession { + ignore_mutants: vec!["a".to_string()], + ..Default::default() + }; + let cli = PartialSession { + ignore_mutants: vec!["b".to_string()], + ..Default::default() + }; + let merged = cli.merge(config); + assert_eq!(merged.ignore_mutants, vec!["b".to_string()]); +} + +#[test] +fn vec_merge_fallback() { + let config = PartialSession { + ignore_mutants: vec!["a".to_string()], + ..Default::default() + }; + let cli = PartialSession::default(); + let merged = cli.merge(config); + assert_eq!(merged.ignore_mutants, vec!["a".to_string()]); +} -- knotmirror 0.0.1