Skip to content

Commit dcf8329

Browse files
committed
Add command to extract examples
Fixes fspoettel#81
1 parent 012c8e1 commit dcf8329

File tree

3 files changed

+64
-1
lines changed

3 files changed

+64
-1
lines changed

src/template/aoc_cli.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ fn get_input_path(day: Day) -> String {
8484
format!("data/inputs/{day}.txt")
8585
}
8686

87-
fn get_puzzle_path(day: Day) -> String {
87+
pub fn get_puzzle_path(day: Day) -> String {
8888
format!("data/puzzles/{day}.md")
8989
}
9090

src/template/commands/extract.rs

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
}

src/template/commands/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
pub mod all;
22
pub mod download;
3+
pub mod extract;
34
pub mod read;
45
pub mod scaffold;
56
pub mod solve;

0 commit comments

Comments
 (0)