|
| 1 | +use itertools::Itertools; |
| 2 | + |
| 3 | +use crate::template::{aoc_cli, Day, ANSI_BOLD, ANSI_RESET}; |
| 4 | +use std::process; |
| 5 | + |
| 6 | +fn example_file_path(day: Day) -> String { |
| 7 | + format!("data/examples/{day}.txt") |
| 8 | +} |
| 9 | + |
| 10 | +fn example_file_path_part(day: Day, part: u8) -> String { |
| 11 | + format!("data/examples/{day}-{part}.txt") |
| 12 | +} |
| 13 | + |
| 14 | +fn extract_examples(text: &str) -> Vec<&str> { |
| 15 | + text.split("```\n").skip(1).step_by(2).collect_vec() |
| 16 | +} |
| 17 | + |
| 18 | +pub fn handle(day: Day) { |
| 19 | + println!("Extracting day {}...", day); |
| 20 | + let text = std::fs::read_to_string(aoc_cli::get_puzzle_path(day)).unwrap_or_else(|err| { |
| 21 | + eprintln!("Error reading file: {}", err); |
| 22 | + process::exit(1); |
| 23 | + }); |
| 24 | + let examples = extract_examples(&text); |
| 25 | + let mut selected = Vec::new(); |
| 26 | + if examples.len() == 1 { |
| 27 | + selected = examples.clone(); |
| 28 | + } else { |
| 29 | + for (i, block) in examples.iter().enumerate() { |
| 30 | + println!("Extracted block {}", i + 1); |
| 31 | + println!("--------------------"); |
| 32 | + println!("{ANSI_BOLD}{}{ANSI_RESET}", block.trim()); |
| 33 | + println!("--------------------"); |
| 34 | + println!("Write this block to a file? [y/N/q]"); |
| 35 | + let mut input = String::new(); |
| 36 | + std::io::stdin().read_line(&mut input).unwrap(); |
| 37 | + if input.trim().to_lowercase() == "y" { |
| 38 | + selected.push(block); |
| 39 | + } else if input.trim().to_lowercase() == "q" { |
| 40 | + println!("Aborted."); |
| 41 | + process::exit(0); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + if selected.len() == 1 { |
| 46 | + let path = example_file_path(day); |
| 47 | + std::fs::write(&path, selected[0]).unwrap_or_else(|err| { |
| 48 | + eprintln!("Error writing file: {}", err); |
| 49 | + process::exit(1); |
| 50 | + }); |
| 51 | + println!("🎄 Successfully wrote example to \"{}\".", &path); |
| 52 | + } else { |
| 53 | + for (i, out) in selected.iter().enumerate() { |
| 54 | + let path = example_file_path_part(day, (i + 1) as u8); |
| 55 | + std::fs::write(&path, out).unwrap_or_else(|err| { |
| 56 | + eprintln!("Error writing file: {}", err); |
| 57 | + process::exit(1); |
| 58 | + }); |
| 59 | + println!("🎄 Successfully wrote example to \"{}\".", &path); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments