diff --git a/.cargo/config b/.cargo/config deleted file mode 100644 index 6731f8f..0000000 --- a/.cargo/config +++ /dev/null @@ -1,6 +0,0 @@ -[alias] -scaffold = "run --bin scaffold -- " -download = "run --bin download -- " - -solve = "run --bin" -all = "run" diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..754f083 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,11 @@ +[alias] +scaffold = "run --quiet --release -- scaffold" +download = "run --quiet --release -- download" +read = "run --quiet --release -- read" + +solve = "run --quiet --release -- solve" +all = "run --quiet --release -- all" +time = "run --quiet --release -- all --release --time" + +[env] +AOC_YEAR = "2022" diff --git a/.editorconfig b/.editorconfig index c075e7e..560e94b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -11,6 +11,7 @@ trim_trailing_whitespace = true [*.txt] insert_final_newline = false +trim_trailing_whitespace = false [*.md] trim_trailing_whitespace = false diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dadca12..9eef218 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,25 +6,28 @@ env: CARGO_TERM_COLOR: always jobs: - check: - runs-on: ubuntu-latest - name: Check - steps: - - uses: actions/checkout@v2 - - name: cargo check - run: cargo check test: runs-on: ubuntu-latest - name: Test + name: CI steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 + - name: Set up cargo cache + uses: actions/cache@v3 + continue-on-error: false + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + restore-keys: ${{ runner.os }}-cargo- - name: cargo test run: cargo test - # uncomment to enable clippy lints - # clippy: - # runs-on: ubuntu-latest - # name: Lint (clippy) - # steps: - # - uses: actions/checkout@v2 - # - name: cargo clippy - # run: cargo clippy -- -D warnings + # uncomment to enable clippy linter + # - name: cargo clippy + # run: cargo clippy -- -D warnings + # uncomment to enable format linter + # - name: cargo fmt + # run: cargo fmt --check diff --git a/.github/workflows/readme-stars.yml b/.github/workflows/readme-stars.yml index 026095e..4b943fa 100644 --- a/.github/workflows/readme-stars.yml +++ b/.github/workflows/readme-stars.yml @@ -10,7 +10,7 @@ jobs: update-readme: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 if: ${{ env.AOC_ENABLED }} env: AOC_ENABLED: ${{ secrets.AOC_ENABLED }} diff --git a/.gitignore b/.gitignore index f2fd7aa..3d20b31 100644 --- a/.gitignore +++ b/.gitignore @@ -16,5 +16,9 @@ target/ # Advent of Code # @see https://old.reddit.com/r/adventofcode/comments/k99rod/sharing_input_data_were_we_requested_not_to/gf2ukkf/?context=3 -/src/inputs -!/src/inputs/.keep + +data + +!data/inputs/.keep +!data/examples/.keep +!data/puzzles/.keep diff --git a/Cargo.lock b/Cargo.lock index a53d473..895fa26 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,7 +4,7 @@ version = 3 [[package]] name = "advent_of_code" -version = "0.8.0" +version = "0.9.0" dependencies = [ "pico-args", ] diff --git a/Cargo.toml b/Cargo.toml index 3ec21e9..fc2d1f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,11 +1,17 @@ [package] name = "advent_of_code" -version = "0.8.0" +version = "0.9.0" authors = ["Felix SpΓΆttel <1682504+fspoettel@users.noreply.github.com>"] edition = "2021" default-run = "advent_of_code" publish = false # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[lib] +doctest = false + +[features] +test_lib = [] + [dependencies] pico-args = "0.5.0" diff --git a/README.md b/README.md index f30c9e6..8f3abb1 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www. + + --- ## Template setup @@ -17,6 +19,7 @@ This template supports all major OS (macOS, Linux, Windows). 1. Open [the template repository](https://github.com/fspoettel/advent-of-code-rust) on Github. 2. Click [Use this template](https://github.com/fspoettel/advent-of-code-rust/generate) and create your repository. 3. Clone your repository to your computer. +4. If you are solving a previous year's advent of code, change the `AOC_YEAR` variable in `.cargo/config.toml` to reflect the year you are solving. ### Setup rust πŸ’» @@ -37,42 +40,37 @@ This template supports all major OS (macOS, Linux, Windows). cargo scaffold # output: -# Created module "src/bin/01.rs" -# Created empty input file "src/inputs/01.txt" -# Created empty example file "src/examples/01.txt" +# Created module file "src/bin/01.rs" +# Created empty input file "data/inputs/01.txt" +# Created empty example file "data/examples/01.txt" # --- # πŸŽ„ Type `cargo solve 01` to run your solution. ``` -Individual solutions live in the `./src/bin/` directory as separate binaries. +Individual solutions live in the `./src/bin/` directory as separate binaries. _Inputs_ and _examples_ live in the the `./data` directory. -Every [solution](https://github.com/fspoettel/advent-of-code-rust/blob/main/src/bin/scaffold.rs#L11-L41) has _unit tests_ referencing its _example_ file. Use these unit tests to develop and debug your solution against the example input. For some puzzles, it might be easier to forgo the example file and hardcode inputs into the tests. +Every [solution](https://github.com/fspoettel/advent-of-code-rust/blob/main/src/bin/scaffold.rs#L11-L41) has _unit tests_ referencing its _example_ file. Use these unit tests to develop and debug your solutions against the example input. -When editing a solution, `rust-analyzer` will display buttons for running / debugging unit tests above the unit test blocks. +Tip: when editing a solution, `rust-analyzer` will display buttons for running / debugging unit tests above the unit test blocks. -### Download input for a day +### Download input & description for a day > **Note** -> This command requires [installing the aoc-cli crate](#download-puzzle-inputs-via-aoc-cli). +> This command requires [installing the aoc-cli crate](#configure-aoc-cli-integration). ```sh # example: `cargo download 1` cargo download # output: -# Downloading input with aoc-cli... -# Loaded session cookie from "/home/felix/.adventofcode.session". -# Downloading input for day 1, 2021... -# Saving puzzle input to "/tmp/tmp.MBdcAdL9Iw/input"... -# Done! +# [INFO aoc] πŸŽ„ aoc-cli - Advent of Code command-line tool +# [INFO aoc_client] πŸŽ… Saved puzzle to 'data/puzzles/01.md' +# [INFO aoc_client] πŸŽ… Saved input to 'data/inputs/01.txt' # --- -# πŸŽ„ Successfully wrote input to "src/inputs/01.txt"! +# πŸŽ„ Successfully wrote input to "data/inputs/01.txt". +# πŸŽ„ Successfully wrote puzzle to "data/puzzles/01.md". ``` -To download inputs for previous years, append the `--year/-y` flag. _(example: `cargo download 1 --year 2020`)_ - -Puzzle inputs are not checked into git. [Reasoning](https://old.reddit.com/r/adventofcode/comments/k99rod/sharing_input_data_were_we_requested_not_to/gf2ukkf/?context=3). - ### Run solutions for a day ```sh @@ -80,19 +78,24 @@ Puzzle inputs are not checked into git. [Reasoning](https://old.reddit.com/r/adv cargo solve # output: +# Finished dev [unoptimized + debuginfo] target(s) in 0.13s # Running `target/debug/01` -# πŸŽ„ Part 1 πŸŽ„ -# -# 6 (elapsed: 37.03Β΅s) -# -# πŸŽ„ Part 2 πŸŽ„ -# -# 9 (elapsed: 33.18Β΅s) +# Part 1: 42 (166.0ns) +# Part 2: 42 (41.0ns) ``` -`solve` is an alias for `cargo run --bin`. To run an optimized version for benchmarking, append the `--release` flag. +The `solve` command runs your solution against real puzzle inputs. To run an optimized build of your code, append the `--release` flag as with any other rust program. -Displayed _timings_ show the raw execution time of your solution without overhead (e.g. file reads). +By default, `solve` executes your code once and shows the execution time. If you append the `--time` flag to the command, the runner will run your code between `10` and `10.000` times (depending on execution time of first execution) and print the average execution time. + +For example, running a benchmarked, optimized execution of day 1 would look like `cargo solve 1 --release --time`. Displayed _timings_ show the raw execution time of your solution without overhead like file reads. + +#### Submitting solutions + +> **Note** +> This command requires [installing the aoc-cli crate](#configure-aoc-cli-integration). + +In order to submit part of a solution for checking, append the `--submit ` option to the `solve` command. ### Run all solutions @@ -104,27 +107,28 @@ cargo all # ---------- # | Day 01 | # ---------- -# πŸŽ„ Part 1 πŸŽ„ -# -# 0 (elapsed: 170.00Β΅s) -# -# πŸŽ„ Part 2 πŸŽ„ -# -# 0 (elapsed: 30.00Β΅s) +# Part 1: 42 (19.0ns) +# Part 2: 42 (19.0ns) # <...other days...> # Total: 0.20ms ``` -`all` is an alias for `cargo run`. To run an optimized version for benchmarking, use the `--release` flag. +This runs all solutions sequentially and prints output to the command-line. Same as for the `solve` command, `--release` controls whether real inputs will be used. + +#### Update readme benchmarks -_Total timing_ is computed from individual solution _timings_ and excludes as much overhead as possible. +The template can output a table with solution times to your readme. Please note that these are not "scientific" benchmarks, understand them as a fun approximation. πŸ˜‰ -### Run all solutions against the example input +In order to generate a benchmarking table, run `cargo all --release --time`. If everything goes well, the command will output "_Successfully updated README with benchmarks._" after the execution finishes. + +### Run all tests ```sh cargo test ``` +To run tests for a specific day, append `--bin `, e.g. `cargo test --bin 01`. You can further scope it down to a specific part, e.g. `cargo test --bin 01 part_one`. + ### Format code ```sh @@ -137,18 +141,29 @@ cargo fmt cargo clippy ``` -## Optional template features +### Read puzzle description in terminal + +> **Note** +> This command requires [installing the aoc-cli crate](#configure-aoc-cli-integration). + +```sh +# example: `cargo read 1` +cargo read -### Download puzzle inputs via aoc-cli +# output: +# Loaded session cookie from "/Users//.adventofcode.session". +# Fetching puzzle for day 1, 2022... +# ...the input... +``` -1. Install [`aoc-cli`](https://github.com/scarvalhojr/aoc-cli/) via cargo: `cargo install aoc-cli --version 0.5.0`. -2. Create an `.adventofcode.session` file in your home directory and paste your session cookie[^1] into it. To get this, press F12 anywhere on the Advent of Code website to open your browser developer tools. Look in your Cookies under the Application or Storage tab, and copy out the `session` cookie value. +## Optional template features -Once installed, you can use the [download command](#download-input-for-a-day). +### Configure aoc-cli integration -### Enable clippy lints in CI +1. Install [`aoc-cli`](https://github.com/scarvalhojr/aoc-cli/) via cargo: `cargo install aoc-cli --version 0.12.0` +2. Create an `.adventofcode.session` file in your home directory and paste your session cookie. To retrieve the session cookie, press F12 anywhere on the Advent of Code website to open your browser developer tools. Look in _Cookies_ under the _Application_ or _Storage_ tab, and copy out the `session` cookie value. [^1] -Uncomment the `clippy` job in the `ci.yml` workflow to enable clippy checks in CI. +Once installed, you can use the [download command](#download-input--description-for-a-day) and automatically submit solutions via the [`--submit` flag](#submitting-solutions). ### Automatically track ⭐️ progress in the readme @@ -165,12 +180,16 @@ Go to the leaderboard page of the year you want to track and click _Private Lead Go to the _Secrets_ tab in your repository settings and create the following secrets: - `AOC_ENABLED`: This variable controls whether the workflow is enabled. Set it to `true` to enable the progress tracker. -- `AOC_USER_ID`: Go to [this page](https://adventofcode.com/settings) and copy your user id. It's the number behind the `#` symbol in the first name option. Example: `3031` -- `AOC_YEAR`: the year you want to track. Example: `2021` +- `AOC_USER_ID`: Go to [this page](https://adventofcode.com/settings) and copy your user id. It's the number behind the `#` symbol in the first name option. Example: `3031`. +- `AOC_YEAR`: the year you want to track. Example: `2021`. - `AOC_SESSION`: an active session[^2] for the advent of code website. To get this, press F12 anywhere on the Advent of Code website to open your browser developer tools. Look in your Cookies under the Application or Storage tab, and copy out the `session` cookie. ✨ You can now run this action manually via the _Run workflow_ button on the workflow page. If you want the workflow to run automatically, uncomment the `schedule` section in the `readme-stars.yml` workflow file or add a `push` trigger. +### Check code formatting / clippy lints in CI + +Uncomment the respective sections in the `ci.yml` workflow. + ### Use VS Code to debug your code 1. Install [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer) and [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb). diff --git a/src/examples/.keep b/data/examples/.keep similarity index 100% rename from src/examples/.keep rename to data/examples/.keep diff --git a/src/inputs/.keep b/data/inputs/.keep similarity index 100% rename from src/inputs/.keep rename to data/inputs/.keep diff --git a/data/puzzles/.keep b/data/puzzles/.keep new file mode 100644 index 0000000..e69de29 diff --git a/src/bin/.keep b/src/bin/.keep new file mode 100644 index 0000000..e69de29 diff --git a/src/bin/download.rs b/src/bin/download.rs deleted file mode 100644 index edb567d..0000000 --- a/src/bin/download.rs +++ /dev/null @@ -1,105 +0,0 @@ -/* - * This file contains template code. - * There is no need to edit this file unless you want to change template functionality. - */ -use std::io::Write; -use std::path::PathBuf; -use std::{env::temp_dir, io, process::Command}; -use std::{fs, process}; - -struct Args { - day: u8, - year: Option, -} - -fn parse_args() -> Result { - let mut args = pico_args::Arguments::from_env(); - Ok(Args { - day: args.free_from_str()?, - year: args.opt_value_from_str(["-y", "--year"])?, - }) -} - -fn remove_file(path: &PathBuf) { - #[allow(unused_must_use)] - { - fs::remove_file(path); - } -} - -fn exit_with_status(status: i32, path: &PathBuf) -> ! { - remove_file(path); - process::exit(status); -} - -fn main() { - // acquire a temp file path to write aoc-cli output to. - // aoc-cli expects this file not to be present - delete just in case. - let mut tmp_file_path = temp_dir(); - tmp_file_path.push("aoc_input_tmp"); - remove_file(&tmp_file_path); - - let args = match parse_args() { - Ok(args) => args, - Err(e) => { - eprintln!("Failed to process arguments: {}", e); - exit_with_status(1, &tmp_file_path); - } - }; - - let day_padded = format!("{:02}", args.day); - let input_path = format!("src/inputs/{}.txt", day_padded); - - // check if aoc binary exists and is callable. - if Command::new("aoc").arg("-V").output().is_err() { - eprintln!("command \"aoc\" not found or not callable. Try running \"cargo install aoc-cli\" to install it."); - exit_with_status(1, &tmp_file_path); - } - - let mut cmd_args = vec![]; - - if let Some(year) = args.year { - cmd_args.push("--year".into()); - cmd_args.push(year.to_string()); - } - - cmd_args.append(&mut vec![ - "--input-file".into(), - tmp_file_path.to_string_lossy().to_string(), - "--day".into(), - args.day.to_string(), - "download".into(), - ]); - - println!("Downloading input with >aoc {}", cmd_args.join(" ")); - - match Command::new("aoc").args(cmd_args).output() { - Ok(cmd_output) => { - io::stdout() - .write_all(&cmd_output.stdout) - .expect("could not write cmd stdout to pipe."); - io::stderr() - .write_all(&cmd_output.stderr) - .expect("could not write cmd stderr to pipe."); - if !cmd_output.status.success() { - exit_with_status(1, &tmp_file_path); - } - } - Err(e) => { - eprintln!("failed to spawn aoc-cli: {}", e); - exit_with_status(1, &tmp_file_path); - } - } - - match fs::copy(&tmp_file_path, &input_path) { - Ok(_) => { - println!("---"); - println!("πŸŽ„ Successfully wrote input to \"{}\".", &input_path); - exit_with_status(0, &tmp_file_path); - } - Err(e) => { - eprintln!("could not copy downloaded input to input file: {}", e); - exit_with_status(1, &tmp_file_path); - } - } -} diff --git a/src/bin/scaffold.rs b/src/bin/scaffold.rs deleted file mode 100644 index 0c77b4d..0000000 --- a/src/bin/scaffold.rs +++ /dev/null @@ -1,114 +0,0 @@ -/* - * This file contains template code. - * There is no need to edit this file unless you want to change template functionality. - */ -use std::{ - fs::{File, OpenOptions}, - io::Write, - process, -}; - -const MODULE_TEMPLATE: &str = r###"pub fn part_one(input: &str) -> Option { - None -} - -pub fn part_two(input: &str) -> Option { - None -} - -fn main() { - let input = &advent_of_code::read_file("inputs", DAY); - advent_of_code::solve!(1, part_one, input); - advent_of_code::solve!(2, part_two, input); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_part_one() { - let input = advent_of_code::read_file("examples", DAY); - assert_eq!(part_one(&input), None); - } - - #[test] - fn test_part_two() { - let input = advent_of_code::read_file("examples", DAY); - assert_eq!(part_two(&input), None); - } -} -"###; - -fn parse_args() -> Result { - let mut args = pico_args::Arguments::from_env(); - args.free_from_str() -} - -fn safe_create_file(path: &str) -> Result { - OpenOptions::new().write(true).create_new(true).open(path) -} - -fn create_file(path: &str) -> Result { - OpenOptions::new().write(true).create(true).open(path) -} - -fn main() { - let day = match parse_args() { - Ok(day) => day, - Err(_) => { - eprintln!("Need to specify a day (as integer). example: `cargo scaffold 7`"); - process::exit(1); - } - }; - - let day_padded = format!("{:02}", day); - - let input_path = format!("src/inputs/{}.txt", day_padded); - let example_path = format!("src/examples/{}.txt", day_padded); - let module_path = format!("src/bin/{}.rs", day_padded); - - let mut file = match safe_create_file(&module_path) { - Ok(file) => file, - Err(e) => { - eprintln!("Failed to create module file: {}", e); - process::exit(1); - } - }; - - match file.write_all(MODULE_TEMPLATE.replace("DAY", &day.to_string()).as_bytes()) { - Ok(_) => { - println!("Created module file \"{}\"", &module_path); - } - Err(e) => { - eprintln!("Failed to write module contents: {}", e); - process::exit(1); - } - } - - match create_file(&input_path) { - Ok(_) => { - println!("Created empty input file \"{}\"", &input_path); - } - Err(e) => { - eprintln!("Failed to create input file: {}", e); - process::exit(1); - } - } - - match create_file(&example_path) { - Ok(_) => { - println!("Created empty example file \"{}\"", &example_path); - } - Err(e) => { - eprintln!("Failed to create example file: {}", e); - process::exit(1); - } - } - - println!("---"); - println!( - "πŸŽ„ Type `cargo solve {}` to run your solution.", - &day_padded - ); -} diff --git a/src/helpers.rs b/src/helpers.rs deleted file mode 100644 index 079071f..0000000 --- a/src/helpers.rs +++ /dev/null @@ -1,4 +0,0 @@ -/* - * Use this file if you want to extract helpers from your solutions. - * Example import from this file: `use advent_of_code::helpers::example_fn;`. - */ diff --git a/src/lib.rs b/src/lib.rs index 23acd28..612b5b9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,125 +1 @@ -/* - * This file contains template code. - * There is no need to edit this file unless you want to change template functionality. - * Prefer `./helpers.rs` if you want to extract code from your solutions. - */ -use std::env; -use std::fs; - -pub mod helpers; - -pub const ANSI_ITALIC: &str = "\x1b[3m"; -pub const ANSI_BOLD: &str = "\x1b[1m"; -pub const ANSI_RESET: &str = "\x1b[0m"; - -#[macro_export] -macro_rules! solve { - ($part:expr, $solver:ident, $input:expr) => {{ - use advent_of_code::{ANSI_BOLD, ANSI_ITALIC, ANSI_RESET}; - use std::fmt::Display; - use std::time::Instant; - - fn print_result(func: impl FnOnce(&str) -> Option, input: &str) { - let timer = Instant::now(); - let result = func(input); - let elapsed = timer.elapsed(); - match result { - Some(result) => { - println!( - "{} {}(elapsed: {:.2?}){}", - result, ANSI_ITALIC, elapsed, ANSI_RESET - ); - } - None => { - println!("not solved.") - } - } - } - - println!("πŸŽ„ {}Part {}{} πŸŽ„", ANSI_BOLD, $part, ANSI_RESET); - print_result($solver, $input); - }}; -} - -pub fn read_file(folder: &str, day: u8) -> String { - let cwd = env::current_dir().unwrap(); - - let filepath = cwd.join("src").join(folder).join(format!("{:02}.txt", day)); - - let f = fs::read_to_string(filepath); - f.expect("could not open input file") -} - -fn parse_time(val: &str, postfix: &str) -> f64 { - val.split(postfix).next().unwrap().parse().unwrap() -} - -pub fn parse_exec_time(output: &str) -> f64 { - output.lines().fold(0_f64, |acc, l| { - if !l.contains("elapsed:") { - acc - } else { - let timing = l.split("(elapsed: ").last().unwrap(); - // use `contains` istd. of `ends_with`: string may contain ANSI escape sequences. - // for possible time formats, see: https://github.com/rust-lang/rust/blob/1.64.0/library/core/src/time.rs#L1176-L1200 - if timing.contains("ns)") { - acc // range below rounding precision. - } else if timing.contains("Β΅s)") { - acc + parse_time(timing, "Β΅s") / 1000_f64 - } else if timing.contains("ms)") { - acc + parse_time(timing, "ms") - } else if timing.contains("s)") { - acc + parse_time(timing, "s") * 1000_f64 - } else { - acc - } - } - }) -} - -/// copied from: https://github.com/rust-lang/rust/blob/1.64.0/library/std/src/macros.rs#L328-L333 -#[cfg(test)] -macro_rules! assert_approx_eq { - ($a:expr, $b:expr) => {{ - let (a, b) = (&$a, &$b); - assert!( - (*a - *b).abs() < 1.0e-6, - "{} is not approximately equal to {}", - *a, - *b - ); - }}; -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_parse_exec_time() { - assert_approx_eq!( - parse_exec_time(&format!( - "πŸŽ„ Part 1 πŸŽ„\n0 (elapsed: 74.13ns){}\nπŸŽ„ Part 2 πŸŽ„\n0 (elapsed: 50.00ns){}", - ANSI_RESET, ANSI_RESET - )), - 0_f64 - ); - - assert_approx_eq!( - parse_exec_time("πŸŽ„ Part 1 πŸŽ„\n0 (elapsed: 755Β΅s)\nπŸŽ„ Part 2 πŸŽ„\n0 (elapsed: 700Β΅s)"), - 1.455_f64 - ); - - assert_approx_eq!( - parse_exec_time("πŸŽ„ Part 1 πŸŽ„\n0 (elapsed: 70Β΅s)\nπŸŽ„ Part 2 πŸŽ„\n0 (elapsed: 1.45ms)"), - 1.52_f64 - ); - - assert_approx_eq!( - parse_exec_time( - "πŸŽ„ Part 1 πŸŽ„\n0 (elapsed: 10.3s)\nπŸŽ„ Part 2 πŸŽ„\n0 (elapsed: 100.50ms)" - ), - 10400.50_f64 - ); - } -} +pub mod template; diff --git a/src/main.rs b/src/main.rs index 45701ab..91a042c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,46 +1,90 @@ -/* - * This file contains template code. - * There is no need to edit this file unless you want to change template functionality. - */ -use advent_of_code::{ANSI_BOLD, ANSI_ITALIC, ANSI_RESET}; -use std::process::Command; +use advent_of_code::template::commands::{all, download, read, scaffold, solve}; +use args::{parse, AppArguments}; -fn main() { - let total: f64 = (1..=25) - .map(|day| { - let day = format!("{:02}", day); +mod args { + use std::process; - let cmd = Command::new("cargo") - .args(["run", "--release", "--bin", &day]) - .output() - .unwrap(); + pub enum AppArguments { + Download { + day: u8, + }, + Read { + day: u8, + }, + Scaffold { + day: u8, + }, + Solve { + day: u8, + release: bool, + time: bool, + submit: Option, + }, + All { + release: bool, + time: bool, + }, + } - println!("----------"); - println!("{}| Day {} |{}", ANSI_BOLD, day, ANSI_RESET); - println!("----------"); + pub fn parse() -> Result> { + let mut args = pico_args::Arguments::from_env(); - let output = String::from_utf8(cmd.stdout).unwrap(); - let is_empty = output.is_empty(); + let app_args = match args.subcommand()?.as_deref() { + Some("all") => AppArguments::All { + release: args.contains("--release"), + time: args.contains("--time"), + }, + Some("download") => AppArguments::Download { + day: args.free_from_str()?, + }, + Some("read") => AppArguments::Read { + day: args.free_from_str()?, + }, + Some("scaffold") => AppArguments::Scaffold { + day: args.free_from_str()?, + }, + Some("solve") => AppArguments::Solve { + day: args.free_from_str()?, + release: args.contains("--release"), + submit: args.opt_value_from_str("--submit")?, + time: args.contains("--time"), + }, + Some(x) => { + eprintln!("Unknown command: {x}"); + process::exit(1); + } + None => { + eprintln!("No command specified."); + process::exit(1); + } + }; - println!( - "{}", - if is_empty { - "Not solved." - } else { - output.trim() - } - ); + let remaining = args.finish(); + if !remaining.is_empty() { + eprintln!("Warning: unknown argument(s): {remaining:?}."); + } - if is_empty { - 0_f64 - } else { - advent_of_code::parse_exec_time(&output) - } - }) - .sum(); + Ok(app_args) + } +} - println!( - "{}Total:{} {}{:.2}ms{}", - ANSI_BOLD, ANSI_RESET, ANSI_ITALIC, total, ANSI_RESET - ); +fn main() { + match parse() { + Err(err) => { + eprintln!("Error: {err}"); + std::process::exit(1); + } + Ok(args) => match args { + AppArguments::All { release, time } => all::handle(release, time), + AppArguments::Download { day } => download::handle(day), + AppArguments::Read { day } => read::handle(day), + AppArguments::Scaffold { day } => scaffold::handle(day), + AppArguments::Solve { + day, + release, + time, + submit, + } => solve::handle(day, release, time, submit), + }, + }; } diff --git a/src/template/aoc_cli.rs b/src/template/aoc_cli.rs new file mode 100644 index 0000000..08ce9fe --- /dev/null +++ b/src/template/aoc_cli.rs @@ -0,0 +1,127 @@ +/// Wrapper module around the "aoc-cli" command-line. +use std::{ + fmt::Display, + process::{Command, Output, Stdio}, +}; + +#[derive(Debug)] +pub enum AocCommandError { + CommandNotFound, + CommandNotCallable, + BadExitStatus(Output), + IoError, +} + +impl Display for AocCommandError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + AocCommandError::CommandNotFound => write!(f, "aoc-cli is not present in environment."), + AocCommandError::CommandNotCallable => write!(f, "aoc-cli could not be called."), + AocCommandError::BadExitStatus(_) => { + write!(f, "aoc-cli exited with a non-zero status.") + } + AocCommandError::IoError => write!(f, "could not write output files to file system."), + } + } +} + +pub fn check() -> Result<(), AocCommandError> { + Command::new("aoc") + .arg("-V") + .output() + .map_err(|_| AocCommandError::CommandNotFound)?; + Ok(()) +} + +pub fn read(day: u8) -> Result { + let puzzle_path = get_puzzle_path(day); + + let args = build_args( + "read", + &[ + "--description-only".into(), + "--puzzle-file".into(), + puzzle_path, + ], + day, + ); + + call_aoc_cli(&args) +} + +pub fn download(day: u8) -> Result { + let input_path = get_input_path(day); + let puzzle_path = get_puzzle_path(day); + + let args = build_args( + "download", + &[ + "--overwrite".into(), + "--input-file".into(), + input_path.to_string(), + "--puzzle-file".into(), + puzzle_path.to_string(), + ], + day, + ); + + let output = call_aoc_cli(&args)?; + println!("---"); + println!("πŸŽ„ Successfully wrote input to \"{}\".", &input_path); + println!("πŸŽ„ Successfully wrote puzzle to \"{}\".", &puzzle_path); + Ok(output) +} + +pub fn submit(day: u8, part: u8, result: &str) -> Result { + // workaround: the argument order is inverted for submit. + let mut args = build_args("submit", &[], day); + args.push(part.to_string()); + args.push(result.to_string()); + call_aoc_cli(&args) +} + +fn get_input_path(day: u8) -> String { + let day_padded = format!("{day:02}"); + format!("data/inputs/{day_padded}.txt") +} + +fn get_puzzle_path(day: u8) -> String { + let day_padded = format!("{day:02}"); + format!("data/puzzles/{day_padded}.md") +} + +fn get_year() -> Option { + match std::env::var("AOC_YEAR") { + Ok(x) => x.parse().ok().or(None), + Err(_) => None, + } +} + +fn build_args(command: &str, args: &[String], day: u8) -> Vec { + let mut cmd_args = args.to_vec(); + + if let Some(year) = get_year() { + cmd_args.push("--year".into()); + cmd_args.push(year.to_string()); + } + + cmd_args.append(&mut vec!["--day".into(), day.to_string(), command.into()]); + + cmd_args +} + +fn call_aoc_cli(args: &[String]) -> Result { + // println!("Calling >aoc with: {}", args.join(" ")); + let output = Command::new("aoc") + .args(args) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()) + .output() + .map_err(|_| AocCommandError::CommandNotCallable)?; + + if output.status.success() { + Ok(output) + } else { + Err(AocCommandError::BadExitStatus(output)) + } +} diff --git a/src/template/commands/all.rs b/src/template/commands/all.rs new file mode 100644 index 0000000..7214b4a --- /dev/null +++ b/src/template/commands/all.rs @@ -0,0 +1,256 @@ +use std::io; + +use crate::template::{ + readme_benchmarks::{self, Timings}, + ANSI_BOLD, ANSI_ITALIC, ANSI_RESET, +}; + +pub fn handle(is_release: bool, is_timed: bool) { + let mut timings: Vec = vec![]; + + (1..=25).for_each(|day| { + if day > 1 { + println!(); + } + + println!("{ANSI_BOLD}Day {day}{ANSI_RESET}"); + println!("------"); + + let output = child_commands::run_solution(day, is_timed, is_release).unwrap(); + + if output.is_empty() { + println!("Not solved."); + } else { + let val = child_commands::parse_exec_time(&output, day); + timings.push(val); + } + }); + + if is_timed { + let total_millis = timings.iter().map(|x| x.total_nanos).sum::() / 1_000_000_f64; + + println!("\n{ANSI_BOLD}Total:{ANSI_RESET} {ANSI_ITALIC}{total_millis:.2}ms{ANSI_RESET}"); + + if is_release { + match readme_benchmarks::update(timings, total_millis) { + Ok(()) => println!("Successfully updated README with benchmarks."), + Err(_) => { + eprintln!("Failed to update readme with benchmarks."); + } + } + } + } +} + +#[derive(Debug)] +pub enum Error { + BrokenPipe, + Parser(String), + IO(io::Error), +} + +impl From for Error { + fn from(e: std::io::Error) -> Self { + Error::IO(e) + } +} + +#[must_use] +pub fn get_path_for_bin(day: usize) -> String { + let day_padded = format!("{day:02}"); + format!("./src/bin/{day_padded}.rs") +} + +/// All solutions live in isolated binaries. +/// This module encapsulates interaction with these binaries, both invoking them as well as parsing the timing output. +mod child_commands { + use super::{get_path_for_bin, Error}; + use std::{ + io::{BufRead, BufReader}, + path::Path, + process::{Command, Stdio}, + thread, + }; + + /// Run the solution bin for a given day + pub fn run_solution( + day: usize, + is_timed: bool, + is_release: bool, + ) -> Result, Error> { + let day_padded = format!("{day:02}"); + + // skip command invocation for days that have not been scaffolded yet. + if !Path::new(&get_path_for_bin(day)).exists() { + return Ok(vec![]); + } + + let mut args = vec!["run", "--quiet", "--bin", &day_padded]; + + if is_release { + args.push("--release"); + } + + if is_timed { + // mirror `--time` flag to child invocations. + args.push("--"); + args.push("--time"); + } + + // spawn child command with piped stdout/stderr. + // forward output to stdout/stderr while grabbing stdout lines. + + let mut cmd = Command::new("cargo") + .args(&args) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn()?; + + let stdout = BufReader::new(cmd.stdout.take().ok_or(super::Error::BrokenPipe)?); + let stderr = BufReader::new(cmd.stderr.take().ok_or(super::Error::BrokenPipe)?); + + let mut output = vec![]; + + let thread = thread::spawn(move || { + stderr.lines().for_each(|line| { + eprintln!("{}", line.unwrap()); + }); + }); + + for line in stdout.lines() { + let line = line.unwrap(); + println!("{line}"); + output.push(line); + } + + thread.join().unwrap(); + cmd.wait()?; + + Ok(output) + } + + pub fn parse_exec_time(output: &[String], day: usize) -> super::Timings { + let mut timings = super::Timings { + day, + part_1: None, + part_2: None, + total_nanos: 0_f64, + }; + + output + .iter() + .filter_map(|l| { + if !l.contains(" samples)") { + return None; + } + + let Some((timing_str, nanos)) = parse_time(l) else { + eprintln!("Could not parse timings from line: {l}"); + return None; + }; + + let part = l.split(':').next()?; + Some((part, timing_str, nanos)) + }) + .for_each(|(part, timing_str, nanos)| { + if part.contains("Part 1") { + timings.part_1 = Some(timing_str.into()); + } else if part.contains("Part 2") { + timings.part_2 = Some(timing_str.into()); + } + + timings.total_nanos += nanos; + }); + + timings + } + + fn parse_to_float(s: &str, postfix: &str) -> Option { + s.split(postfix).next()?.parse().ok() + } + + fn parse_time(line: &str) -> Option<(&str, f64)> { + // for possible time formats, see: https://github.com/rust-lang/rust/blob/1.64.0/library/core/src/time.rs#L1176-L1200 + let str_timing = line + .split(" samples)") + .next()? + .split('(') + .last()? + .split('@') + .next()? + .trim(); + + let parsed_timing = match str_timing { + s if s.contains("ns") => s.split("ns").next()?.parse::().ok(), + s if s.contains("Β΅s") => parse_to_float(s, "Β΅s").map(|x| x * 1000_f64), + s if s.contains("ms") => parse_to_float(s, "ms").map(|x| x * 1_000_000_f64), + s => parse_to_float(s, "s").map(|x| x * 1_000_000_000_f64), + }?; + + Some((str_timing, parsed_timing)) + } + + /// copied from: https://github.com/rust-lang/rust/blob/1.64.0/library/std/src/macros.rs#L328-L333 + #[cfg(feature = "test_lib")] + macro_rules! assert_approx_eq { + ($a:expr, $b:expr) => {{ + let (a, b) = (&$a, &$b); + assert!( + (*a - *b).abs() < 1.0e-6, + "{} is not approximately equal to {}", + *a, + *b + ); + }}; + } + + #[cfg(feature = "test_lib")] + mod tests { + use super::parse_exec_time; + + #[test] + fn test_well_formed() { + let res = parse_exec_time( + &[ + "Part 1: 0 (74.13ns @ 100000 samples)".into(), + "Part 2: 10 (74.13ms @ 99999 samples)".into(), + "".into(), + ], + 1, + ); + assert_approx_eq!(res.total_nanos, 74130074.13_f64); + assert_eq!(res.part_1.unwrap(), "74.13ns"); + assert_eq!(res.part_2.unwrap(), "74.13ms"); + } + + #[test] + fn test_patterns_in_input() { + let res = parse_exec_time( + &[ + "Part 1: @ @ @ ( ) ms (2s @ 5 samples)".into(), + "Part 2: 10s (100ms @ 1 samples)".into(), + "".into(), + ], + 1, + ); + assert_approx_eq!(res.total_nanos, 2100000000_f64); + assert_eq!(res.part_1.unwrap(), "2s"); + assert_eq!(res.part_2.unwrap(), "100ms"); + } + + #[test] + fn test_missing_parts() { + let res = parse_exec_time( + &[ + "Part 1: βœ– ".into(), + "Part 2: βœ– ".into(), + "".into(), + ], + 1, + ); + assert_approx_eq!(res.total_nanos, 0_f64); + assert_eq!(res.part_1.is_none(), true); + assert_eq!(res.part_2.is_none(), true); + } + } +} diff --git a/src/template/commands/download.rs b/src/template/commands/download.rs new file mode 100644 index 0000000..56beead --- /dev/null +++ b/src/template/commands/download.rs @@ -0,0 +1,14 @@ +use crate::template::aoc_cli; +use std::process; + +pub fn handle(day: u8) { + if aoc_cli::check().is_err() { + eprintln!("command \"aoc\" not found or not callable. Try running \"cargo install aoc-cli\" to install it."); + process::exit(1); + } + + if let Err(e) = aoc_cli::download(day) { + eprintln!("failed to call aoc-cli: {e}"); + process::exit(1); + }; +} diff --git a/src/template/commands/mod.rs b/src/template/commands/mod.rs new file mode 100644 index 0000000..88f4696 --- /dev/null +++ b/src/template/commands/mod.rs @@ -0,0 +1,5 @@ +pub mod all; +pub mod download; +pub mod read; +pub mod scaffold; +pub mod solve; diff --git a/src/template/commands/read.rs b/src/template/commands/read.rs new file mode 100644 index 0000000..65edcde --- /dev/null +++ b/src/template/commands/read.rs @@ -0,0 +1,15 @@ +use std::process; + +use crate::template::aoc_cli; + +pub fn handle(day: u8) { + if aoc_cli::check().is_err() { + eprintln!("command \"aoc\" not found or not callable. Try running \"cargo install aoc-cli\" to install it."); + process::exit(1); + } + + if let Err(e) = aoc_cli::read(day) { + eprintln!("failed to call aoc-cli: {e}"); + process::exit(1); + }; +} diff --git a/src/template/commands/scaffold.rs b/src/template/commands/scaffold.rs new file mode 100644 index 0000000..6a3d9a1 --- /dev/null +++ b/src/template/commands/scaffold.rs @@ -0,0 +1,93 @@ +use std::{ + fs::{File, OpenOptions}, + io::Write, + process, +}; + +const MODULE_TEMPLATE: &str = r#"pub fn part_one(input: &str) -> Option { + None +} + +pub fn part_two(input: &str) -> Option { + None +} + +advent_of_code::main!(DAY); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_part_one() { + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, None); + } + + #[test] + fn test_part_two() { + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, None); + } +} +"#; + +fn safe_create_file(path: &str) -> Result { + OpenOptions::new().write(true).create_new(true).open(path) +} + +fn create_file(path: &str) -> Result { + OpenOptions::new().write(true).create(true).open(path) +} + +pub fn handle(day: u8) { + let day_padded = format!("{day:02}"); + + let input_path = format!("data/inputs/{day_padded}.txt"); + let example_path = format!("data/examples/{day_padded}.txt"); + let module_path = format!("src/bin/{day_padded}.rs"); + + let mut file = match safe_create_file(&module_path) { + Ok(file) => file, + Err(e) => { + eprintln!("Failed to create module file: {e}"); + process::exit(1); + } + }; + + match file.write_all(MODULE_TEMPLATE.replace("DAY", &day.to_string()).as_bytes()) { + Ok(()) => { + println!("Created module file \"{}\"", &module_path); + } + Err(e) => { + eprintln!("Failed to write module contents: {e}"); + process::exit(1); + } + } + + match create_file(&input_path) { + Ok(_) => { + println!("Created empty input file \"{}\"", &input_path); + } + Err(e) => { + eprintln!("Failed to create input file: {e}"); + process::exit(1); + } + } + + match create_file(&example_path) { + Ok(_) => { + println!("Created empty example file \"{}\"", &example_path); + } + Err(e) => { + eprintln!("Failed to create example file: {e}"); + process::exit(1); + } + } + + println!("---"); + println!( + "πŸŽ„ Type `cargo solve {}` to run your solution.", + &day_padded + ); +} diff --git a/src/template/commands/solve.rs b/src/template/commands/solve.rs new file mode 100644 index 0000000..8c65702 --- /dev/null +++ b/src/template/commands/solve.rs @@ -0,0 +1,31 @@ +use std::process::{Command, Stdio}; + +pub fn handle(day: u8, release: bool, time: bool, submit_part: Option) { + let day_padded = format!("{day:02}"); + + let mut cmd_args = vec!["run".to_string(), "--bin".to_string(), day_padded]; + + if release { + cmd_args.push("--release".to_string()); + } + + cmd_args.push("--".to_string()); + + if let Some(submit_part) = submit_part { + cmd_args.push("--submit".to_string()); + cmd_args.push(submit_part.to_string()); + } + + if time { + cmd_args.push("--time".to_string()); + } + + let mut cmd = Command::new("cargo") + .args(&cmd_args) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()) + .spawn() + .unwrap(); + + cmd.wait().unwrap(); +} diff --git a/src/template/mod.rs b/src/template/mod.rs new file mode 100644 index 0000000..faddf0a --- /dev/null +++ b/src/template/mod.rs @@ -0,0 +1,34 @@ +use std::{env, fs}; + +pub mod aoc_cli; +pub mod commands; +pub mod readme_benchmarks; +pub mod runner; + +pub const ANSI_ITALIC: &str = "\x1b[3m"; +pub const ANSI_BOLD: &str = "\x1b[1m"; +pub const ANSI_RESET: &str = "\x1b[0m"; + +/// Helper function that reads a text file to a string. +#[must_use] pub fn read_file(folder: &str, day: u8) -> String { + let cwd = env::current_dir().unwrap(); + let filepath = cwd + .join("data") + .join(folder) + .join(format!("{day:02}.txt")); + let f = fs::read_to_string(filepath); + f.expect("could not open input file") +} + +/// main! produces a block setting up the input and runner for each part. +#[macro_export] +macro_rules! main { + ($day:expr) => { + fn main() { + use advent_of_code::template::runner::*; + let input = advent_of_code::template::read_file("inputs", $day); + run_part(part_one, &input, $day, 1); + run_part(part_two, &input, $day, 2); + } + }; +} diff --git a/src/template/readme_benchmarks.rs b/src/template/readme_benchmarks.rs new file mode 100644 index 0000000..6f11b5a --- /dev/null +++ b/src/template/readme_benchmarks.rs @@ -0,0 +1,183 @@ +/// Module that updates the readme me with timing information. +/// The approach taken is similar to how `aoc-readme-stars` handles this. +use std::{fs, io}; + +static MARKER: &str = ""; + +#[derive(Debug)] +pub enum Error { + Parser(String), + IO(io::Error), +} + +impl From for Error { + fn from(e: std::io::Error) -> Self { + Error::IO(e) + } +} + +#[derive(Clone)] +pub struct Timings { + pub day: usize, + pub part_1: Option, + pub part_2: Option, + pub total_nanos: f64, +} + +pub struct TablePosition { + pos_start: usize, + pos_end: usize, +} + +#[must_use] pub fn get_path_for_bin(day: usize) -> String { + let day_padded = format!("{day:02}"); + format!("./src/bin/{day_padded}.rs") +} + +fn locate_table(readme: &str) -> Result { + let matches: Vec<_> = readme.match_indices(MARKER).collect(); + + if matches.len() > 2 { + return Err(Error::Parser( + "{}: too many occurences of marker in README.".into(), + )); + } + + let pos_start = matches + .first() + .map(|m| m.0) + .ok_or_else(|| Error::Parser("Could not find table start position.".into()))?; + + let pos_end = matches + .last() + .map(|m| m.0 + m.1.len()) + .ok_or_else(|| Error::Parser("Could not find table end position.".into()))?; + + Ok(TablePosition { pos_start, pos_end }) +} + +fn construct_table(prefix: &str, timings: Vec, total_millis: f64) -> String { + let header = format!("{prefix} Benchmarks"); + + let mut lines: Vec = vec![ + MARKER.into(), + header, + String::new(), + "| Day | Part 1 | Part 2 |".into(), + "| :---: | :---: | :---: |".into(), + ]; + + for timing in timings { + let path = get_path_for_bin(timing.day); + lines.push(format!( + "| [Day {}]({}) | `{}` | `{}` |", + timing.day, + path, + timing.part_1.unwrap_or_else(|| "-".into()), + timing.part_2.unwrap_or_else(|| "-".into()) + )); + } + + lines.push(String::new()); + lines.push(format!("**Total: {total_millis:.2}ms**")); + lines.push(MARKER.into()); + + lines.join("\n") +} + +fn update_content(s: &mut String, timings: Vec, total_millis: f64) -> Result<(), Error> { + let positions = locate_table(s)?; + let table = construct_table("##", timings, total_millis); + s.replace_range(positions.pos_start..positions.pos_end, &table); + Ok(()) +} + +pub fn update(timings: Vec, total_millis: f64) -> Result<(), Error> { + let path = "README.md"; + let mut readme = String::from_utf8_lossy(&fs::read(path)?).to_string(); + update_content(&mut readme, timings, total_millis)?; + fs::write(path, &readme)?; + Ok(()) +} + +#[cfg(feature = "test_lib")] +mod tests { + use super::{update_content, Timings, MARKER}; + + fn get_mock_timings() -> Vec { + vec![ + Timings { + day: 1, + part_1: Some("10ms".into()), + part_2: Some("20ms".into()), + total_nanos: 3e+10, + }, + Timings { + day: 2, + part_1: Some("30ms".into()), + part_2: Some("40ms".into()), + total_nanos: 7e+10, + }, + Timings { + day: 4, + part_1: Some("40ms".into()), + part_2: Some("50ms".into()), + total_nanos: 9e+10, + }, + ] + } + + #[test] + #[should_panic] + fn errors_if_marker_not_present() { + let mut s = "# readme".to_string(); + update_content(&mut s, get_mock_timings(), 190.0).unwrap(); + } + + #[test] + #[should_panic] + fn errors_if_too_many_markers_present() { + let mut s = format!("{} {} {}", MARKER, MARKER, MARKER); + update_content(&mut s, get_mock_timings(), 190.0).unwrap(); + } + + #[test] + fn updates_empty_benchmarks() { + let mut s = format!("foo\nbar\n{}{}\nbaz", MARKER, MARKER); + update_content(&mut s, get_mock_timings(), 190.0).unwrap(); + assert_eq!(s.contains("## Benchmarks"), true); + } + + #[test] + fn updates_existing_benchmarks() { + let mut s = format!("foo\nbar\n{}{}\nbaz", MARKER, MARKER); + update_content(&mut s, get_mock_timings(), 190.0).unwrap(); + update_content(&mut s, get_mock_timings(), 190.0).unwrap(); + assert_eq!(s.matches(MARKER).collect::>().len(), 2); + assert_eq!(s.matches("## Benchmarks").collect::>().len(), 1); + } + + #[test] + fn format_benchmarks() { + let mut s = format!("foo\nbar\n{}\n{}\nbaz", MARKER, MARKER); + update_content(&mut s, get_mock_timings(), 190.0).unwrap(); + let expected = [ + "foo", + "bar", + "", + "## Benchmarks", + "", + "| Day | Part 1 | Part 2 |", + "| :---: | :---: | :---: |", + "| [Day 1](./src/bin/01.rs) | `10ms` | `20ms` |", + "| [Day 2](./src/bin/02.rs) | `30ms` | `40ms` |", + "| [Day 4](./src/bin/04.rs) | `40ms` | `50ms` |", + "", + "**Total: 190.00ms**", + "", + "baz", + ] + .join("\n"); + assert_eq!(s, expected); + } +} diff --git a/src/template/runner.rs b/src/template/runner.rs new file mode 100644 index 0000000..6557ee5 --- /dev/null +++ b/src/template/runner.rs @@ -0,0 +1,166 @@ +/// Encapsulates code that interacts with solution functions. +use crate::template::{aoc_cli, ANSI_ITALIC, ANSI_RESET}; +use std::fmt::Display; +use std::io::{stdout, Write}; +use std::process::Output; +use std::time::{Duration, Instant}; +use std::{cmp, env, process}; + +use super::ANSI_BOLD; + +pub fn run_part(func: impl Fn(I) -> Option, input: I, day: u8, part: u8) { + let part_str = format!("Part {part}"); + + let (result, duration, samples) = + run_timed(func, input, |result| print_result(result, &part_str, "")); + + print_result(&result, &part_str, &format_duration(&duration, samples)); + + if let Some(result) = result { + submit_result(result, day, part); + } +} + +/// Run a solution part. The behavior differs depending on whether we are running a release or debug build: +/// 1. in debug, the function is executed once. +/// 2. in release, the function is benched (approx. 1 second of execution time or 10 samples, whatever take longer.) +fn run_timed( + func: impl Fn(I) -> T, + input: I, + hook: impl Fn(&T), +) -> (T, Duration, u128) { + let timer = Instant::now(); + let result = func(input.clone()); + let base_time = timer.elapsed(); + + hook(&result); + + let run = if std::env::args().any(|x| x == "--time") { + bench(func, input, &base_time) + } else { + (base_time, 1) + }; + + (result, run.0, run.1) +} + +fn bench(func: impl Fn(I) -> T, input: I, base_time: &Duration) -> (Duration, u128) { + let mut stdout = stdout(); + + print!(" > {ANSI_ITALIC}benching{ANSI_RESET}"); + let _ = stdout.flush(); + + let bench_iterations = cmp::min( + 10000, + cmp::max( + Duration::from_secs(1).as_nanos() / cmp::max(base_time.as_nanos(), 10), + 10, + ), + ); + + let mut timers: Vec = vec![]; + + for _ in 0..bench_iterations { + // need a clone here to make the borrow checker happy. + let cloned = input.clone(); + let timer = Instant::now(); + func(cloned); + timers.push(timer.elapsed()); + } + + ( + #[allow(clippy::cast_possible_truncation)] + Duration::from_nanos(average_duration(&timers) as u64), + bench_iterations, + ) +} + +fn average_duration(numbers: &[Duration]) -> u128 { + numbers + .iter() + .map(std::time::Duration::as_nanos) + .sum::() + / numbers.len() as u128 +} + +fn format_duration(duration: &Duration, samples: u128) -> String { + if samples == 1 { + format!(" ({duration:.1?})") + } else { + format!(" ({duration:.1?} @ {samples} samples)") + } +} + +fn print_result(result: &Option, part: &str, duration_str: &str) { + let is_intermediate_result = duration_str.is_empty(); + + match result { + Some(result) => { + if result.to_string().contains('\n') { + let str = format!("{part}: β–Ό {duration_str}"); + if is_intermediate_result { + print!("{str}"); + } else { + print!("\r"); + println!("{str}"); + println!("{result}"); + } + } else { + let str = format!("{part}: {ANSI_BOLD}{result}{ANSI_RESET}{duration_str}"); + if is_intermediate_result { + print!("{str}"); + } else { + print!("\r"); + println!("{str}"); + } + } + } + None => { + if is_intermediate_result { + print!("{part}: βœ–"); + } else { + print!("\r"); + println!("{part}: βœ– "); + } + } + } +} + +/// Parse the arguments passed to `solve` and try to submit one part of the solution if: +/// 1. we are in `--release` mode. +/// 2. aoc-cli is installed. +fn submit_result( + result: T, + day: u8, + part: u8, +) -> Option> { + let args: Vec = env::args().collect(); + + if !args.contains(&"--submit".into()) { + return None; + } + + if args.len() < 3 { + eprintln!("Unexpected command-line input. Format: cargo solve 1 --submit 1"); + process::exit(1); + } + + let part_index = args.iter().position(|x| x == "--submit").unwrap() + 1; + + let Ok(part_submit) = args[part_index].parse::() else { + eprintln!("Unexpected command-line input. Format: cargo solve 1 --submit 1"); + process::exit(1); + }; + + if part_submit != part { + return None; + } + + if aoc_cli::check().is_err() { + eprintln!("command \"aoc\" not found or not callable. Try running \"cargo install aoc-cli\" to install it."); + process::exit(1); + } + + println!("Submitting result via aoc-cli..."); + Some(aoc_cli::submit(day, part, &result.to_string())) +}