From 73febb9177d86596522a4b7017ba6c3004826970 Mon Sep 17 00:00:00 2001 From: jacksonfu14 Date: Mon, 17 Nov 2025 17:21:40 +0100 Subject: refactor: call lilypond once per batch --- README.md | 3 + morphology-cli/src/main.rs | 7 +- morphology-img/Cargo.toml | 1 - morphology-img/src/lib.rs | 107 +-------- morphology-img/src/render.rs | 224 +++++-------------- morphology-img/tests/config.rs | 47 +--- morphology-img/tests/integration.rs | 405 +--------------------------------- morphology-img/tests/render.rs | 428 ++++++++---------------------------- 8 files changed, 161 insertions(+), 1061 deletions(-) diff --git a/README.md b/README.md index 6a20518..fbcaddf 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,9 @@ cargo run --bin generate 5 --interpolate-length # Run the release version cli ./target/release/generate --pretty 6 +# Render svgs +./target/release/generate --render 5 + # Simple benchmarking /usr/bin/time --verbose ./target/release/generate --pretty 6 > /dev/null diff --git a/morphology-cli/src/main.rs b/morphology-cli/src/main.rs index 402225b..74b7c24 100644 --- a/morphology-cli/src/main.rs +++ b/morphology-cli/src/main.rs @@ -34,7 +34,6 @@ fn main() { // Rendering flags let render = args.contains(&"--render".to_string()); let keep_temp = args.contains(&"--keep-temp".to_string()); - let parallel = args.contains(&"--parallel".to_string()); // Extract --output-dir value let output_dir = args.iter() @@ -82,7 +81,6 @@ fn main() { eprintln!(" --render Render sequences to SVG files using LilyPond"); eprintln!(" --output-dir Output directory for SVG files (default: output)"); eprintln!(" --keep-temp Keep temporary .ly files for debugging"); - eprintln!(" --parallel Enable parallel rendering for better performance"); eprintln!(" --max-batch-size Maximum sequences per batch (avoids overwhelming filesystem)"); eprintln!("\nExamples:"); eprintln!(" {} 5", args[0]); @@ -90,7 +88,7 @@ fn main() { eprintln!(" {} 5 --neg-first-outer --backward", args[0]); eprintln!(" {} 5 --breadth-first --interpolate-length", args[0]); eprintln!(" {} 5 --render --output-dir output", args[0]); - eprintln!(" {} 5 --render --parallel --max-batch-size 50", args[0]); + eprintln!(" {} 5 --render --max-batch-size 50", args[0]); process::exit(1); } @@ -143,8 +141,7 @@ fn main() { // Build rendering configuration let mut config = morphology_img::RenderConfig::new(output_dir) - .keep_temp_files(keep_temp) - .parallel(parallel); + .keep_temp_files(keep_temp); if let Some(batch_size) = max_batch_size { config = config.max_batch_size(batch_size); diff --git a/morphology-img/Cargo.toml b/morphology-img/Cargo.toml index 9454785..0c7a734 100644 --- a/morphology-img/Cargo.toml +++ b/morphology-img/Cargo.toml @@ -9,6 +9,5 @@ morphology = { path = "../morphology" } thiserror = "2.0" itertools = "0.13" tempfile = "3" -rayon = "1.8" [dev-dependencies] diff --git a/morphology-img/src/lib.rs b/morphology-img/src/lib.rs index 386d8ac..ce33c34 100644 --- a/morphology-img/src/lib.rs +++ b/morphology-img/src/lib.rs @@ -34,25 +34,6 @@ pub use error::RenderError; pub use note::sequence_to_markup; use std::path::PathBuf; -use std::sync::Arc; - -/// Type alias for progress callback function. -/// -/// The callback receives: -/// - `current`: The number of sequences processed so far (1-indexed) -/// - `total`: The total number of sequences to process -/// -/// # Examples -/// -/// ```no_run -/// use morphology_img::ProgressCallback; -/// use std::sync::Arc; -/// -/// let callback: ProgressCallback = Arc::new(|current, total| { -/// println!("Progress: {}/{}", current, total); -/// }); -/// ``` -pub type ProgressCallback = Arc; /// Configuration for rendering sequences to SVGs. /// @@ -83,21 +64,11 @@ pub struct RenderConfig { /// Path to the LilyPond binary (default: "lilypond") pub lilypond_binary: PathBuf, - /// Optional callback for progress reporting during batch rendering - pub progress_callback: Option, - /// Maximum number of sequences to process in a single batch /// /// If set, large batches will be split into smaller chunks to avoid /// filesystem issues. If None, all sequences are processed in one batch. pub max_batch_size: Option, - - /// Whether to use parallel processing for rendering SVGs - /// - /// When enabled, multiple LilyPond processes will run concurrently using rayon. - /// This can significantly improve performance for large batches on multi-core systems. - /// Default: false (conservative default to avoid overwhelming the system). - pub parallel: bool, } impl std::fmt::Debug for RenderConfig { @@ -106,9 +77,7 @@ impl std::fmt::Debug for RenderConfig { .field("output_dir", &self.output_dir) .field("keep_temp_files", &self.keep_temp_files) .field("lilypond_binary", &self.lilypond_binary) - .field("progress_callback", &self.progress_callback.as_ref().map(|_| "")) .field("max_batch_size", &self.max_batch_size) - .field("parallel", &self.parallel) .finish() } } @@ -119,9 +88,7 @@ impl Default for RenderConfig { output_dir: PathBuf::from("output"), keep_temp_files: false, lilypond_binary: PathBuf::from("lilypond"), - progress_callback: None, max_batch_size: None, - parallel: false, } } } @@ -188,27 +155,6 @@ impl RenderConfig { self } - /// Sets a progress callback for batch rendering. - /// - /// The callback will be called after each sequence is rendered, allowing - /// you to track progress for large batches. - /// - /// # Examples - /// - /// ``` - /// use morphology_img::RenderConfig; - /// use std::sync::Arc; - /// - /// let config = RenderConfig::new("output") - /// .progress_callback(Arc::new(|current, total| { - /// println!("Rendered {}/{} sequences", current, total); - /// })); - /// ``` - pub fn progress_callback(mut self, callback: ProgressCallback) -> Self { - self.progress_callback = Some(callback); - self - } - /// Sets the maximum batch size for processing sequences. /// /// When set, large batches of sequences will be split into smaller chunks @@ -229,37 +175,6 @@ impl RenderConfig { self.max_batch_size = Some(size); self } - - /// Enables or disables parallel processing for SVG rendering. - /// - /// When enabled, LilyPond will be invoked in parallel using rayon, - /// which can significantly improve performance for large batches on - /// multi-core systems. The default is false (sequential processing). - /// - /// # Performance Considerations - /// - /// Parallel processing is most beneficial when: - /// - Rendering many sequences (typically 10+) - /// - Running on a multi-core system - /// - LilyPond execution is the bottleneck (not file I/O) - /// - /// For small batches (< 10 sequences), sequential processing may be faster - /// due to the overhead of spawning parallel tasks. - /// - /// # Examples - /// - /// ``` - /// use morphology_img::RenderConfig; - /// - /// let config = RenderConfig::new("output") - /// .parallel(true); - /// - /// assert!(config.parallel); - /// ``` - pub fn parallel(mut self, parallel: bool) -> Self { - self.parallel = parallel; - self - } } /// Renders multiple sequences to SVG files. @@ -379,22 +294,12 @@ fn render_sequences_batch( total_count, )?; - // Render .ly files to SVGs (parallel or sequential based on config) - let svg_paths = if config.parallel { - render::render_ly_files_to_svg_parallel( - &ly_files, - &config.output_dir, - &config.lilypond_binary, - config.progress_callback.as_ref(), - )? - } else { - render::render_ly_files_to_svg( - &ly_files, - &config.output_dir, - &config.lilypond_binary, - config.progress_callback.as_ref(), - )? - }; + // Render .ly files to SVGs in a single batch + let svg_paths = render::render_all_ly_files_batch( + &ly_files, + &config.output_dir, + &config.lilypond_binary, + )?; // Handle temp directory cleanup if config.keep_temp_files { diff --git a/morphology-img/src/render.rs b/morphology-img/src/render.rs index a437a21..842f796 100644 --- a/morphology-img/src/render.rs +++ b/morphology-img/src/render.rs @@ -53,55 +53,69 @@ pub fn check_lilypond_available() -> Result { } } -/// Renders a single .ly file to SVG using LilyPond. +/// Renders multiple .ly files to SVGs by calling LilyPond once with all files. /// -/// This function invokes the LilyPond CLI to convert a LilyPond source file -/// into an SVG image. The SVG file will be created in the specified output directory. +/// This function invokes LilyPond with all .ly files as arguments in a single command, +/// which is significantly more efficient than calling LilyPond separately for each file. +/// It eliminates process startup overhead and allows the OS to handle scheduling optimally. /// /// # Arguments -/// - `ly_file`: Path to the .ly file to render -/// - `output_dir`: Directory where the SVG should be created +/// - `ly_files`: Paths to the .ly files to render +/// - `output_dir`: Directory where SVGs should be created /// - `lilypond_binary`: Path to the LilyPond binary (typically "lilypond") /// /// # Returns -/// Path to the generated SVG file +/// Vector of paths to generated SVG files, in the same order as input /// /// # Errors /// - `RenderError::FileIO` if the output directory cannot be created /// - `RenderError::LilyPondExecution` if LilyPond fails to execute or produce output -/// - `RenderError::Template` if the .ly filename is invalid +/// - `RenderError::Template` if any .ly filename is invalid /// /// # Examples /// ```no_run -/// use morphology_img::render::render_ly_to_svg; -/// use std::path::Path; +/// use morphology_img::render::render_all_ly_files_batch; +/// use std::path::{Path, PathBuf}; /// -/// let ly_file = Path::new("/tmp/sequence-0.ly"); +/// let ly_files = vec![ +/// PathBuf::from("/tmp/sequence-0.ly"), +/// PathBuf::from("/tmp/sequence-1.ly"), +/// ]; /// let output_dir = Path::new("output"); /// let lilypond = Path::new("lilypond"); /// -/// let svg_path = render_ly_to_svg(ly_file, output_dir, lilypond).unwrap(); -/// println!("Generated SVG: {}", svg_path.display()); +/// let svg_paths = render_all_ly_files_batch(&ly_files, output_dir, lilypond).unwrap(); +/// println!("Generated {} SVG files", svg_paths.len()); /// ``` /// -/// # Notes -/// - LilyPond creates `filename.svg` from `filename.ly` in the output directory -/// - The function verifies that the expected SVG file was actually created -/// - LilyPond must be installed and the binary must be accessible -pub fn render_ly_to_svg( - ly_file: &Path, +/// # Performance Notes +/// - All files are processed in a single LilyPond invocation +/// - Much faster than sequential individual file processing +/// - Optimal for batches of any size +pub fn render_all_ly_files_batch( + ly_files: &[PathBuf], output_dir: &Path, lilypond_binary: &Path, -) -> Result { +) -> Result, RenderError> { + // Handle empty input + if ly_files.is_empty() { + return Ok(Vec::new()); + } + // Ensure output directory exists fs::create_dir_all(output_dir)?; - // Build the command: lilypond --svg -o output_dir ly_file + // Get the directory containing the .ly files (should all be in same temp dir) + let ly_dir = ly_files[0] + .parent() + .ok_or_else(|| RenderError::Template("Invalid .ly file path".to_string()))?; + + // Build command: lilypond --svg file1.ly file2.ly file3.ly ... + // WITHOUT -o flag, so SVGs are created next to .ly files with correct names let output = Command::new(lilypond_binary) .arg("--svg") - .arg("-o") - .arg(output_dir) - .arg(ly_file) + .args(ly_files) + .current_dir(ly_dir) // Run in the temp directory .output()?; if !output.status.success() { @@ -109,156 +123,32 @@ pub fn render_ly_to_svg( return Err(RenderError::LilyPondExecution(stderr.to_string())); } - // Determine the output SVG path - // LilyPond creates filename.svg from filename.ly - let svg_filename = ly_file - .file_stem() - .ok_or_else(|| RenderError::Template("Invalid .ly filename".to_string()))? - .to_string_lossy() - .to_string() + ".svg"; + // Copy SVG files from temp directory to output directory + let mut svg_paths = Vec::with_capacity(ly_files.len()); - let svg_path = output_dir.join(svg_filename); + for ly_file in ly_files.iter() { + let svg_filename = ly_file + .file_stem() + .ok_or_else(|| RenderError::Template("Invalid .ly filename".to_string()))? + .to_string_lossy() + .to_string() + ".svg"; - // Verify the SVG was created - if !svg_path.exists() { - return Err(RenderError::LilyPondExecution( - format!("Expected SVG not created: {}", svg_path.display()) - )); - } + // SVG was created next to the .ly file in temp directory + let temp_svg_path = ly_dir.join(&svg_filename); - Ok(svg_path) -} - -/// Renders multiple .ly files to SVGs using LilyPond. -/// -/// This function processes multiple LilyPond source files sequentially, -/// converting each to an SVG image in the specified output directory. -/// -/// # Arguments -/// - `ly_files`: Paths to the .ly files to render -/// - `output_dir`: Directory where SVGs should be created -/// - `lilypond_binary`: Path to the LilyPond binary -/// - `progress_callback`: Optional callback for progress reporting -/// -/// # Returns -/// Vector of paths to generated SVG files, in the same order as input -/// -/// # Errors -/// Returns an error if any file fails to render. Processing stops at the first error. -/// -/// # Examples -/// ```no_run -/// use morphology_img::render::render_ly_files_to_svg; -/// use std::path::{Path, PathBuf}; -/// -/// let ly_files = vec![ -/// PathBuf::from("/tmp/sequence-0.ly"), -/// PathBuf::from("/tmp/sequence-1.ly"), -/// ]; -/// let output_dir = Path::new("output"); -/// let lilypond = Path::new("lilypond"); -/// -/// let svg_paths = render_ly_files_to_svg(&ly_files, output_dir, lilypond, None).unwrap(); -/// println!("Generated {} SVG files", svg_paths.len()); -/// ``` -/// -/// # Notes -/// - Files are processed sequentially (not in parallel) -/// - All SVGs are created in the same output directory -/// - If any file fails, an error is returned immediately -/// - Progress callback is called after each file is rendered (if provided) -pub fn render_ly_files_to_svg( - ly_files: &[PathBuf], - output_dir: &Path, - lilypond_binary: &Path, - progress_callback: Option<&crate::ProgressCallback>, -) -> Result, RenderError> { - let total_count = ly_files.len(); - let mut svg_paths = Vec::with_capacity(total_count); + // Verify the SVG was created + if !temp_svg_path.exists() { + return Err(RenderError::LilyPondExecution( + format!("Expected SVG not created: {}", temp_svg_path.display()) + )); + } - for (index, ly_file) in ly_files.iter().enumerate() { - let svg_path = render_ly_to_svg(ly_file, output_dir, lilypond_binary)?; - svg_paths.push(svg_path); + // Copy to output directory (can't use rename - may be different filesystem) + let final_svg_path = output_dir.join(&svg_filename); + fs::copy(&temp_svg_path, &final_svg_path)?; - // Call progress callback if provided - if let Some(callback) = progress_callback { - callback(index + 1, total_count); - } + svg_paths.push(final_svg_path); } Ok(svg_paths) } - -/// Renders multiple .ly files to SVGs using LilyPond in parallel. -/// -/// This function processes multiple LilyPond source files concurrently using rayon, -/// converting each to an SVG image in the specified output directory. This can -/// significantly improve performance for large batches on multi-core systems. -/// -/// # Arguments -/// - `ly_files`: Paths to the .ly files to render -/// - `output_dir`: Directory where SVGs should be created -/// - `lilypond_binary`: Path to the LilyPond binary -/// - `progress_callback`: Optional callback for progress reporting -/// -/// # Returns -/// Vector of paths to generated SVG files, in the same order as input -/// -/// # Errors -/// Returns an error if any file fails to render. Processing stops at the first error. -/// -/// # Performance Notes -/// - Files are processed in parallel using rayon -/// - Progress callbacks may be invoked out of order (but still track correct indices) -/// - Best for batches of 10+ files on multi-core systems -/// - May be slower than sequential for very small batches due to overhead -/// -/// # Examples -/// ```no_run -/// use morphology_img::render::render_ly_files_to_svg_parallel; -/// use std::path::{Path, PathBuf}; -/// -/// let ly_files = vec![ -/// PathBuf::from("/tmp/sequence-0.ly"), -/// PathBuf::from("/tmp/sequence-1.ly"), -/// ]; -/// let output_dir = Path::new("output"); -/// let lilypond = Path::new("lilypond"); -/// -/// let svg_paths = render_ly_files_to_svg_parallel(&ly_files, output_dir, lilypond, None).unwrap(); -/// println!("Generated {} SVG files", svg_paths.len()); -/// ``` -pub fn render_ly_files_to_svg_parallel( - ly_files: &[PathBuf], - output_dir: &Path, - lilypond_binary: &Path, - progress_callback: Option<&crate::ProgressCallback>, -) -> Result, RenderError> { - use rayon::prelude::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::Arc; - - let total_count = ly_files.len(); - - // Use atomic counter for progress tracking - let completed = Arc::new(AtomicUsize::new(0)); - - // Process files in parallel - let results: Vec> = ly_files - .par_iter() - .map(|ly_file| { - let svg_path = render_ly_to_svg(ly_file, output_dir, lilypond_binary)?; - - // Update progress if callback is provided - if let Some(callback) = progress_callback { - let current = completed.fetch_add(1, Ordering::SeqCst) + 1; - callback(current, total_count); - } - - Ok(svg_path) - }) - .collect(); - - // Collect results, returning early on first error - results.into_iter().collect() -} diff --git a/morphology-img/tests/config.rs b/morphology-img/tests/config.rs index 7cc71cb..0ea1b0c 100644 --- a/morphology-img/tests/config.rs +++ b/morphology-img/tests/config.rs @@ -242,57 +242,14 @@ fn test_max_batch_size_field_is_public() { } #[test] -fn test_default_parallel_is_false() { - let config = RenderConfig::default(); - assert!(!config.parallel); -} - -#[test] -fn test_builder_parallel_true() { - let config = RenderConfig::new("output") - .parallel(true); - - assert!(config.parallel); - assert_eq!(config.output_dir, PathBuf::from("output")); -} - -#[test] -fn test_builder_parallel_false() { - let config = RenderConfig::new("output") - .parallel(false); - - assert!(!config.parallel); -} - -#[test] -fn test_builder_parallel_overwrites() { - let config = RenderConfig::new("output") - .parallel(true) - .parallel(false); // Override previous value - - assert!(!config.parallel); -} - -#[test] -fn test_builder_with_all_options_including_parallel() { +fn test_builder_with_all_options() { let config = RenderConfig::new("my-output") .keep_temp_files(true) .lilypond_binary("/usr/bin/lilypond") - .max_batch_size(25) - .parallel(true); + .max_batch_size(25); assert_eq!(config.output_dir, PathBuf::from("my-output")); assert!(config.keep_temp_files); assert_eq!(config.lilypond_binary, PathBuf::from("/usr/bin/lilypond")); assert_eq!(config.max_batch_size, Some(25)); - assert!(config.parallel); -} - -#[test] -fn test_parallel_field_is_public() { - let config = RenderConfig::new("output").parallel(true); - - // Should be able to access field directly - let _parallel = config.parallel; - assert!(_parallel); } diff --git a/morphology-img/tests/integration.rs b/morphology-img/tests/integration.rs index 423d668..b61f097 100644 --- a/morphology-img/tests/integration.rs +++ b/morphology-img/tests/integration.rs @@ -1,8 +1,7 @@ -use morphology_img::{render_sequences, RenderConfig, ProgressCallback}; +use morphology_img::{render_sequences, RenderConfig}; use morphology::{Sequence, Value}; use tempfile::TempDir; use std::fs; -use std::sync::{Arc, Mutex}; /// Test the complete pipeline with basic configuration #[test] @@ -365,178 +364,6 @@ fn test_render_sequences_realistic_workflow() { assert_eq!(svg_paths[3].file_name().unwrap().to_str().unwrap(), "sequence-3.svg"); } -// Tests for progress callback - -/// Test that progress callback is called correctly -#[test] -#[ignore] -fn test_progress_callback_basic() { - let sequences = vec![ - Sequence::new(vec![Value::origin()]), - Sequence::new(vec![Value::new(1, 0)]), - Sequence::new(vec![Value::new(2, 0)]), - ]; - - let progress_calls = Arc::new(Mutex::new(Vec::new())); - let progress_calls_clone = progress_calls.clone(); - - let callback: ProgressCallback = Arc::new(move |current, total| { - progress_calls_clone.lock().unwrap().push((current, total)); - }); - - let output_dir = TempDir::new().unwrap(); - let config = RenderConfig::new(output_dir.path()) - .progress_callback(callback); - - let svg_paths = render_sequences(&sequences, &config).unwrap(); - - // Verify all SVGs were created - assert_eq!(svg_paths.len(), 3); - - // Verify progress callback was called correctly - let calls = progress_calls.lock().unwrap(); - assert_eq!(calls.len(), 3, "callback should be called once per sequence"); - - // Verify calls have correct values - assert_eq!(calls[0], (1, 3), "first call should be (1, 3)"); - assert_eq!(calls[1], (2, 3), "second call should be (2, 3)"); - assert_eq!(calls[2], (3, 3), "third call should be (3, 3)"); -} - -/// Test progress callback with single sequence -#[test] -#[ignore] -fn test_progress_callback_single() { - let sequences = vec![Sequence::new(vec![Value::origin()])]; - - let progress_calls = Arc::new(Mutex::new(Vec::new())); - let progress_calls_clone = progress_calls.clone(); - - let callback: ProgressCallback = Arc::new(move |current, total| { - progress_calls_clone.lock().unwrap().push((current, total)); - }); - - let output_dir = TempDir::new().unwrap(); - let config = RenderConfig::new(output_dir.path()) - .progress_callback(callback); - - let _svg_paths = render_sequences(&sequences, &config).unwrap(); - - let calls = progress_calls.lock().unwrap(); - assert_eq!(calls.len(), 1); - assert_eq!(calls[0], (1, 1)); -} - -/// Test progress callback with many sequences -#[test] -#[ignore] -fn test_progress_callback_many() { - let sequences: Vec = (0..10) - .map(|i| Sequence::new(vec![Value::new(i, 0)])) - .collect(); - - let progress_calls = Arc::new(Mutex::new(Vec::new())); - let progress_calls_clone = progress_calls.clone(); - - let callback: ProgressCallback = Arc::new(move |current, total| { - progress_calls_clone.lock().unwrap().push((current, total)); - }); - - let output_dir = TempDir::new().unwrap(); - let config = RenderConfig::new(output_dir.path()) - .progress_callback(callback); - - let svg_paths = render_sequences(&sequences, &config).unwrap(); - - assert_eq!(svg_paths.len(), 10); - - let calls = progress_calls.lock().unwrap(); - assert_eq!(calls.len(), 10); - - // Verify each call has correct values - for (i, &(current, total)) in calls.iter().enumerate() { - assert_eq!(current, i + 1); - assert_eq!(total, 10); - } -} - -/// Test that rendering works without progress callback -#[test] -#[ignore] -fn test_no_progress_callback() { - let sequences = vec![ - Sequence::new(vec![Value::origin()]), - Sequence::new(vec![Value::new(1, 0)]), - ]; - - let output_dir = TempDir::new().unwrap(); - let config = RenderConfig::new(output_dir.path()); - // No progress callback set - - let svg_paths = render_sequences(&sequences, &config).unwrap(); - - // Should work normally without callback - assert_eq!(svg_paths.len(), 2); - for svg_path in &svg_paths { - assert!(svg_path.exists()); - } -} - -/// Test progress callback with empty sequence list -#[test] -#[ignore] -fn test_progress_callback_empty() { - let sequences: Vec = vec![]; - - let progress_calls = Arc::new(Mutex::new(Vec::new())); - let progress_calls_clone = progress_calls.clone(); - - let callback: ProgressCallback = Arc::new(move |current, total| { - progress_calls_clone.lock().unwrap().push((current, total)); - }); - - let output_dir = TempDir::new().unwrap(); - let config = RenderConfig::new(output_dir.path()) - .progress_callback(callback); - - let svg_paths = render_sequences(&sequences, &config).unwrap(); - - assert_eq!(svg_paths.len(), 0); - - // Callback should not be called for empty list - let calls = progress_calls.lock().unwrap(); - assert_eq!(calls.len(), 0, "callback should not be called for empty input"); -} - -/// Test that progress callback can track actual progress -#[test] -#[ignore] -fn test_progress_callback_tracking() { - let sequences: Vec = (0..5) - .map(|i| Sequence::new(vec![Value::new(i, 0)])) - .collect(); - - let last_progress = Arc::new(Mutex::new((0, 0))); - let last_progress_clone = last_progress.clone(); - - let callback: ProgressCallback = Arc::new(move |current, total| { - let mut progress = last_progress_clone.lock().unwrap(); - *progress = (current, total); - }); - - let output_dir = TempDir::new().unwrap(); - let config = RenderConfig::new(output_dir.path()) - .progress_callback(callback); - - let svg_paths = render_sequences(&sequences, &config).unwrap(); - - assert_eq!(svg_paths.len(), 5); - - // Last progress should be 5/5 - let final_progress = last_progress.lock().unwrap(); - assert_eq!(*final_progress, (5, 5), "final progress should be 5/5"); -} - // ============================================================================ // Batch Chunking Tests // ============================================================================ @@ -662,43 +489,6 @@ fn test_batch_chunking_preserves_order() { } } -#[test] -#[ignore] -fn test_batch_chunking_with_progress() { - // Test that progress callback works correctly with batching - let sequences: Vec = (0..8) - .map(|i| { - Sequence::new(vec![Value::new(i, 0)]) - }) - .collect(); - - let progress_calls = Arc::new(Mutex::new(Vec::new())); - let progress_calls_clone = progress_calls.clone(); - - let callback: ProgressCallback = Arc::new(move |current, total| { - progress_calls_clone.lock().unwrap().push((current, total)); - }); - - let output_dir = TempDir::new().unwrap(); - let config = RenderConfig::new(output_dir.path()) - .max_batch_size(3) - .progress_callback(callback); - - let svg_paths = render_sequences(&sequences, &config).unwrap(); - - assert_eq!(svg_paths.len(), 8); - - // Progress should track within each batch - let calls = progress_calls.lock().unwrap(); - assert!(!calls.is_empty(), "Progress callback should be called"); - - // Note: Progress is per-batch, so we should see: - // Batch 1 (3 items): (1,3), (2,3), (3,3) - // Batch 2 (3 items): (1,3), (2,3), (3,3) - // Batch 3 (2 items): (1,2), (2,2) - assert_eq!(calls.len(), 8, "Should have 8 progress calls total"); -} - #[test] #[ignore] fn test_batch_size_one() { @@ -720,196 +510,3 @@ fn test_batch_size_one() { assert!(path.exists()); } } - -// ============================================================================ -// Parallel Processing Tests -// ============================================================================ - -#[test] -#[ignore] -fn test_parallel_rendering_basic() { - // Test that parallel rendering works correctly - let sequences: Vec = (0..10) - .map(|i| { - Sequence::new(vec![Value::new(i, 0)]) - }) - .collect(); - - let output_dir = TempDir::new().unwrap(); - let config = RenderConfig::new(output_dir.path()) - .parallel(true); - - let svg_paths = render_sequences(&sequences, &config).unwrap(); - - assert_eq!(svg_paths.len(), 10); - for path in &svg_paths { - assert!(path.exists(), "SVG file should exist: {}", path.display()); - } -} - -#[test] -#[ignore] -fn test_parallel_vs_sequential_same_results() { - // Verify that parallel and sequential produce the same results - let sequences: Vec = (0..5) - .map(|i| { - Sequence::new(vec![Value::new(i, 0), Value::new(i, 1)]) - }) - .collect(); - - // Sequential rendering - let output_dir_seq = TempDir::new().unwrap(); - let config_seq = RenderConfig::new(output_dir_seq.path()) - .parallel(false); - - let svg_paths_seq = render_sequences(&sequences, &config_seq).unwrap(); - - // Parallel rendering - let output_dir_par = TempDir::new().unwrap(); - let config_par = RenderConfig::new(output_dir_par.path()) - .parallel(true); - - let svg_paths_par = render_sequences(&sequences, &config_par).unwrap(); - - // Both should produce same number of files - assert_eq!(svg_paths_seq.len(), svg_paths_par.len()); - - // Both should have files with same names - for (seq_path, par_path) in svg_paths_seq.iter().zip(svg_paths_par.iter()) { - assert_eq!( - seq_path.file_name(), - par_path.file_name(), - "Sequential and parallel should produce same filenames" - ); - assert!(seq_path.exists()); - assert!(par_path.exists()); - } -} - -#[test] -#[ignore] -fn test_parallel_with_progress_callback() { - // Test that progress callbacks work with parallel rendering - let sequences: Vec = (0..8) - .map(|i| { - Sequence::new(vec![Value::new(i, 0)]) - }) - .collect(); - - let progress_calls = Arc::new(Mutex::new(Vec::new())); - let progress_calls_clone = progress_calls.clone(); - - let callback: ProgressCallback = Arc::new(move |current, total| { - progress_calls_clone.lock().unwrap().push((current, total)); - }); - - let output_dir = TempDir::new().unwrap(); - let config = RenderConfig::new(output_dir.path()) - .parallel(true) - .progress_callback(callback); - - let svg_paths = render_sequences(&sequences, &config).unwrap(); - - assert_eq!(svg_paths.len(), 8); - - // Progress callback should have been called 8 times - let calls = progress_calls.lock().unwrap(); - assert_eq!(calls.len(), 8, "Progress callback should be called for each file"); - - // All calls should have total=8 - for (_current, total) in calls.iter() { - assert_eq!(*total, 8, "Total should always be 8"); - } -} - -#[test] -#[ignore] -fn test_parallel_default_is_false() { - let config = RenderConfig::default(); - assert!(!config.parallel, "Parallel should default to false"); - - let config2 = RenderConfig::new("output"); - assert!(!config2.parallel, "Parallel should default to false"); -} - -#[test] -#[ignore] -fn test_parallel_with_batch_chunking() { - // Test parallel rendering combined with batch chunking - let sequences: Vec = (0..15) - .map(|i| { - Sequence::new(vec![Value::new(i, 0)]) - }) - .collect(); - - let output_dir = TempDir::new().unwrap(); - let config = RenderConfig::new(output_dir.path()) - .parallel(true) - .max_batch_size(5); - - let svg_paths = render_sequences(&sequences, &config).unwrap(); - - // All 15 SVGs should be created - assert_eq!(svg_paths.len(), 15); - - // Verify files are in order (sequence-00.svg through sequence-14.svg) - for (i, path) in svg_paths.iter().enumerate() { - let expected_filename = format!("sequence-{:02}.svg", i); - assert_eq!( - path.file_name().unwrap().to_str().unwrap(), - expected_filename, - "Files should be in correct order" - ); - assert!(path.exists()); - } -} - -#[test] -#[ignore] -fn test_benchmark_parallel_vs_sequential() { - use std::time::Instant; - - // Create many sequences for meaningful benchmark - let sequences: Vec = (0..20) - .map(|i| { - Sequence::new(vec![Value::new(i, 0)]) - }) - .collect(); - - // Sequential rendering - let output_dir_seq = TempDir::new().unwrap(); - let config_seq = RenderConfig::new(output_dir_seq.path()) - .parallel(false); - - let start = Instant::now(); - let svg_paths_seq = render_sequences(&sequences, &config_seq).unwrap(); - let sequential_time = start.elapsed(); - - assert_eq!(svg_paths_seq.len(), 20); - - // Parallel rendering - let output_dir_par = TempDir::new().unwrap(); - let config_par = RenderConfig::new(output_dir_par.path()) - .parallel(true); - - let start = Instant::now(); - let svg_paths_par = render_sequences(&sequences, &config_par).unwrap(); - let parallel_time = start.elapsed(); - - assert_eq!(svg_paths_par.len(), 20); - - // Print timing results - println!("\n=== Parallel vs Sequential Benchmark (20 sequences) ==="); - println!("Sequential time: {:?}", sequential_time); - println!("Parallel time: {:?}", parallel_time); - - if parallel_time < sequential_time { - let speedup = sequential_time.as_secs_f64() / parallel_time.as_secs_f64(); - println!("Speedup: {:.2}x faster", speedup); - } else { - println!("Note: Parallel was slower (overhead or system constraints)"); - } - - // No strict assertion on speed - depends on system - // Just verify both completed successfully -} diff --git a/morphology-img/tests/render.rs b/morphology-img/tests/render.rs index b6538ab..3e86f97 100644 --- a/morphology-img/tests/render.rs +++ b/morphology-img/tests/render.rs @@ -1,12 +1,11 @@ -use morphology_img::render::{check_lilypond_available, render_ly_to_svg, render_ly_files_to_svg}; +use morphology_img::render::{check_lilypond_available, render_all_ly_files_batch}; use morphology_img::error::RenderError; use morphology_img::file_gen::{create_temp_dir, generate_ly_file, write_support_files, generate_ly_files}; use morphology::{Sequence, Value}; use std::path::Path; use tempfile::TempDir; -/// This test requires LilyPond to be installed on the system. -/// Run with: cargo test -- --ignored +/// Test that LilyPond is available (requires LilyPond installation) #[test] #[ignore] fn test_lilypond_available() { @@ -17,10 +16,7 @@ fn test_lilypond_available() { let version = result.unwrap(); println!("LilyPond version: {}", version); - // Verify the version string is not empty assert!(!version.is_empty(), "version string should not be empty"); - - // Verify it contains "LilyPond" or starts with "GNU" assert!( version.contains("LilyPond") || version.starts_with("GNU"), "version string should contain 'LilyPond' or start with 'GNU', got: {}", @@ -28,18 +24,14 @@ fn test_lilypond_available() { ); } -/// Test that verifies the error type when LilyPond is not found. -/// This test will pass if LilyPond is NOT installed, or will be skipped if it is. +/// Test error type when LilyPond is not found #[test] fn test_lilypond_not_found_error_type() { - // Try to check for LilyPond let result = check_lilypond_available(); - // If it fails, verify it's the right error type if let Err(e) = result { match e { RenderError::LilyPondNotFound(msg) => { - // Verify the error message is helpful assert!(!msg.is_empty(), "error message should not be empty"); assert!( msg.contains("LilyPond") || msg.contains("PATH"), @@ -49,450 +41,221 @@ fn test_lilypond_not_found_error_type() { _ => panic!("Expected RenderError::LilyPondNotFound, got: {:?}", e), } } else { - // If LilyPond is available, we can't test the error case, so skip println!("LilyPond is installed, skipping error test"); } } -/// Test that we handle the case where the command exists but fails -#[test] -fn test_command_failure_handling() { - use std::process::Command; - - // Use a command that exists but will fail with --version - // (most systems have 'false' which always returns non-zero) - let output = Command::new("false") - .output(); - - if output.is_ok() { - let out = output.unwrap(); - // If false command exists, verify we can detect failure status - assert!(!out.status.success(), "false command should have non-success status"); - } -} - -// Tests for render_ly_to_svg (single file SVG generation) - -/// Test rendering a single .ly file to SVG +/// Test rendering multiple .ly files to SVGs in a single batch #[test] #[ignore] -fn test_render_single_svg() { - // Create a simple sequence - let seq = Sequence::new(vec![Value::origin()]); +fn test_render_batch_basic() { + let sequences = vec![ + Sequence::new(vec![Value::origin()]), + Sequence::new(vec![Value::new(1, 0)]), + Sequence::new(vec![Value::new(-1, 0)]), + ]; - // Generate .ly file let temp_dir = create_temp_dir().unwrap(); write_support_files(temp_dir.path()).unwrap(); + let ly_files = generate_ly_files(&sequences, temp_dir.path()).unwrap(); - let ly_path = temp_dir.path().join("test.ly"); - generate_ly_file(&seq, &ly_path).unwrap(); - - // Render to SVG let output_dir = TempDir::new().unwrap(); - let svg_path = render_ly_to_svg( - &ly_path, + let svg_paths = render_all_ly_files_batch( + &ly_files, output_dir.path(), Path::new("lilypond"), ).unwrap(); - // Verify SVG exists - assert!(svg_path.exists(), "SVG file should exist"); - - // Verify SVG has content - let svg_content = std::fs::read_to_string(&svg_path).unwrap(); - assert!(svg_content.contains(" 1000, "SVG should have substantial content"); -} - -/// Test that output directory is created if it doesn't exist -#[test] -#[ignore] -fn test_creates_output_directory() { - let seq = Sequence::new(vec![Value::origin()]); - - let temp_dir = create_temp_dir().unwrap(); - write_support_files(temp_dir.path()).unwrap(); - - let ly_path = temp_dir.path().join("test.ly"); - generate_ly_file(&seq, &ly_path).unwrap(); - - // Use a nested directory that doesn't exist yet - let output_base = TempDir::new().unwrap(); - let output_dir = output_base.path().join("nested").join("output"); - - assert!(!output_dir.exists(), "output directory should not exist yet"); - - let svg_path = render_ly_to_svg( - &ly_path, - &output_dir, - Path::new("lilypond"), - ).unwrap(); - - // Verify directory was created - assert!(output_dir.exists(), "output directory should be created"); - assert!(svg_path.exists(), "SVG should be in created directory"); + assert_eq!(svg_paths[0].file_name().unwrap().to_str().unwrap(), "sequence-0.svg"); + assert_eq!(svg_paths[1].file_name().unwrap().to_str().unwrap(), "sequence-1.svg"); + assert_eq!(svg_paths[2].file_name().unwrap().to_str().unwrap(), "sequence-2.svg"); } -/// Test rendering multiple different sequences +/// Test batch rendering with empty list #[test] -#[ignore] -fn test_render_multiple_different_sequences() { - let sequences = vec![ - Sequence::new(vec![Value::origin()]), - Sequence::new(vec![Value::new(1, 0)]), - Sequence::new(vec![Value::new(-1, 0)]), - ]; - - let temp_dir = create_temp_dir().unwrap(); - write_support_files(temp_dir.path()).unwrap(); - +fn test_render_batch_empty() { + let ly_files: Vec = vec![]; let output_dir = TempDir::new().unwrap(); - for (i, seq) in sequences.iter().enumerate() { - let ly_path = temp_dir.path().join(format!("seq-{}.ly", i)); - generate_ly_file(seq, &ly_path).unwrap(); - - let svg_path = render_ly_to_svg( - &ly_path, - output_dir.path(), - Path::new("lilypond"), - ).unwrap(); - - assert!(svg_path.exists()); - assert_eq!(svg_path.file_name().unwrap().to_str().unwrap(), format!("seq-{}.svg", i)); - } - - // Verify all 3 SVGs were created - let entries: Vec<_> = std::fs::read_dir(output_dir.path()) - .unwrap() - .filter_map(|e| e.ok()) - .collect(); - assert_eq!(entries.len(), 3, "should have 3 SVG files"); -} - -/// Test that SVG content is valid and contains expected elements -#[test] -#[ignore] -fn test_svg_content_validity() { - let seq = Sequence::new(vec![Value::origin()]); - - let temp_dir = create_temp_dir().unwrap(); - write_support_files(temp_dir.path()).unwrap(); - - let ly_path = temp_dir.path().join("test.ly"); - generate_ly_file(&seq, &ly_path).unwrap(); - - let output_dir = TempDir::new().unwrap(); - let svg_path = render_ly_to_svg( - &ly_path, + let svg_paths = render_all_ly_files_batch( + &ly_files, output_dir.path(), Path::new("lilypond"), ).unwrap(); - let svg_content = std::fs::read_to_string(&svg_path).unwrap(); - - // Verify SVG structure - assert!(svg_content.contains(""), "should contain closing tag"); - assert!(svg_content.contains("xmlns"), "should contain XML namespace"); - - // LilyPond SVGs typically contain these elements - assert!(svg_content.contains(" group elements"); + assert_eq!(svg_paths.len(), 0); } -/// Test rendering with relative path for lilypond binary +/// Test batch rendering creates output directory #[test] #[ignore] -fn test_render_with_relative_lilypond_path() { +fn test_render_batch_creates_output_dir() { let seq = Sequence::new(vec![Value::origin()]); - let temp_dir = create_temp_dir().unwrap(); write_support_files(temp_dir.path()).unwrap(); let ly_path = temp_dir.path().join("test.ly"); generate_ly_file(&seq, &ly_path).unwrap(); - let output_dir = TempDir::new().unwrap(); + let output_base = TempDir::new().unwrap(); + let output_dir = output_base.path().join("nested").join("output"); + assert!(!output_dir.exists()); - // Use just "lilypond" as the binary name (will be found in PATH) - let svg_path = render_ly_to_svg( - &ly_path, - output_dir.path(), + let svg_paths = render_all_ly_files_batch( + &[ly_path], + &output_dir, Path::new("lilypond"), ).unwrap(); - assert!(svg_path.exists()); + assert!(output_dir.exists()); + assert_eq!(svg_paths.len(), 1); } -/// Test that the function returns an error if LilyPond fails +/// Test with invalid .ly file #[test] #[ignore] -fn test_render_error_on_invalid_ly_file() { +fn test_render_batch_invalid_ly_file() { use std::fs; let temp_dir = create_temp_dir().unwrap(); - - // Create an invalid .ly file (missing required structure) let ly_path = temp_dir.path().join("invalid.ly"); fs::write(&ly_path, "this is not valid lilypond syntax!!!").unwrap(); let output_dir = TempDir::new().unwrap(); - - let result = render_ly_to_svg( - &ly_path, + let result = render_all_ly_files_batch( + &[ly_path], output_dir.path(), Path::new("lilypond"), ); - // Should return an error - assert!(result.is_err(), "should fail on invalid .ly file"); - + assert!(result.is_err()); match result { Err(RenderError::LilyPondExecution(msg)) => { - assert!(!msg.is_empty(), "error message should not be empty"); + assert!(!msg.is_empty()); } _ => panic!("expected LilyPondExecution error"), } } -// Tests for render_ly_files_to_svg (batch SVG generation) - -/// Test rendering multiple .ly files to SVGs in batch +/// Test batch rendering with many files #[test] #[ignore] -fn test_render_multiple_svgs_batch() { - // Create multiple sequences - let sequences = vec![ - Sequence::new(vec![Value::origin()]), - Sequence::new(vec![Value::new(1, 0)]), - Sequence::new(vec![Value::new(-1, 0)]), - ]; +fn test_render_batch_many_files() { + let sequences: Vec = (0..20) + .map(|i| Sequence::new(vec![Value::new(i, 0)])) + .collect(); let temp_dir = create_temp_dir().unwrap(); write_support_files(temp_dir.path()).unwrap(); - - // Generate .ly files let ly_files = generate_ly_files(&sequences, temp_dir.path()).unwrap(); - // Render all to SVGs let output_dir = TempDir::new().unwrap(); - let svg_paths = render_ly_files_to_svg( + let svg_paths = render_all_ly_files_batch( &ly_files, output_dir.path(), Path::new("lilypond"), - None, ).unwrap(); - // Verify all SVGs were created - assert_eq!(svg_paths.len(), 3, "should create 3 SVG files"); - + assert_eq!(svg_paths.len(), 20); for svg_path in &svg_paths { - assert!(svg_path.exists(), "each SVG should exist"); - - // Verify SVG has content + assert!(svg_path.exists()); let content = std::fs::read_to_string(svg_path).unwrap(); - assert!(content.contains(" = vec![]; - - let output_dir = TempDir::new().unwrap(); - let svg_paths = render_ly_files_to_svg( - &ly_files, - output_dir.path(), - Path::new("lilypond"), - None, - ).unwrap(); - - assert_eq!(svg_paths.len(), 0, "should return empty vector for empty input"); -} - -/// Test batch rendering with single file -#[test] -#[ignore] -fn test_batch_render_single_file() { - let seq = Sequence::new(vec![Value::origin()]); +fn test_render_example_sequence() { + let seq = Sequence::new(vec![ + Value::new(1, 0), + Value::new(-1, 1), + Value::new(-1, 0), + Value::new(0, 0), + ]); let temp_dir = create_temp_dir().unwrap(); write_support_files(temp_dir.path()).unwrap(); - let ly_path = temp_dir.path().join("single.ly"); + let ly_path = temp_dir.path().join("example.ly"); generate_ly_file(&seq, &ly_path).unwrap(); - let ly_files = vec![ly_path]; - let output_dir = TempDir::new().unwrap(); - let svg_paths = render_ly_files_to_svg( - &ly_files, + let svg_paths = render_all_ly_files_batch( + &[ly_path], output_dir.path(), Path::new("lilypond"), - None, ).unwrap(); assert_eq!(svg_paths.len(), 1); assert!(svg_paths[0].exists()); - assert_eq!(svg_paths[0].file_name().unwrap().to_str().unwrap(), "single.svg"); -} - -/// Test that batch rendering stops on first error -#[test] -#[ignore] -fn test_batch_render_stops_on_error() { - use std::fs; - - let temp_dir = create_temp_dir().unwrap(); - // Create one valid and one invalid .ly file - let seq = Sequence::new(vec![Value::origin()]); - write_support_files(temp_dir.path()).unwrap(); - - let valid_ly = temp_dir.path().join("valid.ly"); - generate_ly_file(&seq, &valid_ly).unwrap(); - - let invalid_ly = temp_dir.path().join("invalid.ly"); - fs::write(&invalid_ly, "invalid lilypond syntax!!!").unwrap(); - - let ly_files = vec![valid_ly, invalid_ly]; - - let output_dir = TempDir::new().unwrap(); - let result = render_ly_files_to_svg( - &ly_files, - output_dir.path(), - Path::new("lilypond"), - None, - ); - - // Should fail due to invalid file - assert!(result.is_err(), "should fail on invalid file"); - - match result { - Err(RenderError::LilyPondExecution(_)) => { - // Expected error type - } - _ => panic!("expected LilyPondExecution error"), - } + let svg_content = std::fs::read_to_string(&svg_paths[0]).unwrap(); + assert!(svg_content.contains(" 1000, "SVG should have substantial content"); } -/// Test batch rendering with large number of files +/// Test that SVG content is valid #[test] #[ignore] -fn test_batch_render_many_files() { - // Create 10 sequences - let sequences: Vec = (0..10) - .map(|i| Sequence::new(vec![Value::new(i, 0)])) - .collect(); +fn test_svg_content_validity() { + let seq = Sequence::new(vec![Value::origin()]); let temp_dir = create_temp_dir().unwrap(); write_support_files(temp_dir.path()).unwrap(); - let ly_files = generate_ly_files(&sequences, temp_dir.path()).unwrap(); + let ly_path = temp_dir.path().join("test.ly"); + generate_ly_file(&seq, &ly_path).unwrap(); let output_dir = TempDir::new().unwrap(); - let svg_paths = render_ly_files_to_svg( - &ly_files, + let svg_paths = render_all_ly_files_batch( + &[ly_path], output_dir.path(), Path::new("lilypond"), - None, ).unwrap(); - // Verify all 10 SVGs were created - assert_eq!(svg_paths.len(), 10, "should create 10 SVG files"); + let svg_content = std::fs::read_to_string(&svg_paths[0]).unwrap(); - for (i, svg_path) in svg_paths.iter().enumerate() { - assert!(svg_path.exists()); - // With 10 files, we need 2-digit padding: 00, 01, 02, ..., 09 - assert_eq!( - svg_path.file_name().unwrap().to_str().unwrap(), - format!("sequence-{:02}.svg", i) - ); - } - - // Verify all files have content - for svg_path in &svg_paths { - let content = std::fs::read_to_string(svg_path).unwrap(); - assert!(content.contains(" 100, "SVG should have substantial content"); - } + assert!(svg_content.contains(""), "should contain closing tag"); + assert!(svg_content.contains("xmlns"), "should contain XML namespace"); + assert!(svg_content.contains(" group elements"); } /// Integration test: Complete pipeline from sequences to SVGs #[test] #[ignore] fn test_complete_pipeline_batch_rendering() { - // Create test sequences let sequences = vec![ Sequence::new(vec![ Value::new(1, 0), @@ -509,44 +272,33 @@ fn test_complete_pipeline_batch_rendering() { ]), ]; - // Create temp directory and write support files let temp_dir = create_temp_dir().unwrap(); write_support_files(temp_dir.path()).unwrap(); - // Generate .ly files let ly_files = generate_ly_files(&sequences, temp_dir.path()).unwrap(); assert_eq!(ly_files.len(), 3); - // Render all to SVGs let output_dir = TempDir::new().unwrap(); - let svg_paths = render_ly_files_to_svg( + let svg_paths = render_all_ly_files_batch( &ly_files, output_dir.path(), Path::new("lilypond"), - None, ).unwrap(); - // Verify complete pipeline assert_eq!(svg_paths.len(), 3); - // Verify each SVG for (i, svg_path) in svg_paths.iter().enumerate() { - // File exists assert!(svg_path.exists(), "SVG {} should exist", i); - - // Correct filename assert_eq!( svg_path.file_name().unwrap().to_str().unwrap(), format!("sequence-{}.svg", i) ); - // Has valid SVG content let content = std::fs::read_to_string(svg_path).unwrap(); assert!(content.contains(""), "SVG {} should have closing tag", i); } - // Verify all files are in output directory let entries: Vec<_> = std::fs::read_dir(output_dir.path()) .unwrap() .filter_map(|e| e.ok()) -- cgit v1.2.3