Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multi-Year Suppport via Workspaces #78

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ today = "run --quiet --release --features today -- today"
scaffold = "run --quiet --release -- scaffold"
download = "run --quiet --release -- download"
read = "run --quiet --release -- read"

set-year = "run --quiet --release -- set-year"
new-year = "run --quiet --release -- new-year"
get-year = "run --quiet --release -- get-year"
try = "run --quiet --release -- try"
solve = "run --quiet --release -- solve"
all = "run --quiet --release -- all"
time = "run --quiet --release -- time"
Expand Down
26 changes: 18 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ edition = "2021"
default-run = "advent_of_code"
publish = false

[workspace]
members = ["year_template"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
doctest = false
Expand Down
63 changes: 60 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ 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

Expand All @@ -33,6 +32,22 @@ This template supports all major OS (macOS, Linux, Windows).

## Usage

### ➡️ Start a new year

```sh
# example: `cargo new-year 2024`
cargo new-year <year>

# output:
# Created 2024 workspace project.
# Set the repository's current working year to 2024.
# ---
# 🎄 Type `cargo scaffold <day>` to get started on the year.
# 🎄 Or type `cargo set-year <year>` to switch to working on a different year.
```

A year has its own directory `./<year>/` within the repository. This subdirectory behaves as its own crate with its own dependencies separate from the repository root. Its contents are copied from the directory `./year_template/` so if you add dependencies or utility files there they will be copied into any new year project you create. You can run all of the following commands from within the `./<year>/` directory. You can also run the Advent of Code custom commands from the project root directory so long as the repository year is set to `<year>` (see the `set-year` command).

### ➡️ Scaffold a day

```sh
Expand Down Expand Up @@ -74,6 +89,24 @@ cargo download <day>
# 🎄 Successfully wrote puzzle to "data/puzzles/01.md".
```

### ➡️ Run tests for a day

```sh
# example: `cargo try 1`
cargo try <day>

# Finished `test` profile [unoptimized + debuginfo] target(s) in 0.84s
# Running unittests src/bin/01.rs (target/debug/deps/01-faca1023160cfe39)

# running 2 tests
# test tests::test_part_two ... ok
# test tests::test_part_one ... ok
#
# test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
```

The `try` command runs the tests for your solution against the example puzzle inputs. You can narrow it down to a specific test or set of tests, e.g. `cargo try 1 part_one` to run just the part one test.

### ➡️ Run solutions for a day

```sh
Expand Down Expand Up @@ -112,7 +145,7 @@ cargo all
# Total: 0.20ms
```

This runs all solutions sequentially and prints output to the command-line. Same as for the `solve` command, the `--release` flag runs an optimized build.
This runs all solutions for a year sequentially and prints output to the command-line. Same as for the `solve` command, the `--release` flag runs an optimized build.

### ➡️ Benchmark your solutions

Expand Down Expand Up @@ -149,7 +182,7 @@ By default, `cargo time` does not write to the readme. In order to do so, append
cargo test
```

To run tests for a specific day, append `--bin <day>`, e.g. `cargo test --bin 01`. You can further scope it down to a specific part, e.g. `cargo test --bin 01 part_one`.
To run tests for a specific day, append `--bin <day>`, e.g. `cargo test --bin 01`. You can further scope it down to a specific part, e.g. `cargo test --bin 01 part_one`. This command only works within a given year's subdirectory (such as running all the 2024 tests by running `cargo test` in `./2024/`).

### ➡️ Read puzzle description

Expand Down Expand Up @@ -201,18 +234,42 @@ cargo today
# ...the input...
```

### ➡️ Change what year the repository is set to
```sh
# example: `cargo set-year 2024`
cargo set-year 2024

# output:
# Set repository to year 2024.
```

This sets the repository's "configured year" which is tracked in `./.cargo/config.toml`. When running Advent of Code custom commands from the project's root directory, it will execute them for this year. Creating a new year subproject automatically sets the repository's year to that year.

### ➡️ Check what year the repository is set to
```sh
# example: `cargo get-year` when you've been working on 2024
cargo get-year

# output:
# The repository is currently set to 2024.
```

### ➡️ Format code

```sh
cargo fmt
```

Run this inside the `./<year>` directory.

### ➡️ Lint code

```sh
cargo clippy
```

Run this inside the `./<year>` directory.

## Optional template features

### Configure aoc-cli integration
Expand Down
35 changes: 34 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use advent_of_code::template::commands::{all, download, read, scaffold, solve, time};
use advent_of_code::template::commands::{
all, attempt, download, new_year, read, scaffold, set_year, solve, time,
};
use args::{parse, AppArguments};

#[cfg(feature = "today")]
Expand Down Expand Up @@ -28,6 +30,11 @@ mod args {
dhat: bool,
submit: Option<u8>,
},
Try {
day: Day,
test: Option<String>,
dhat: bool,
},
All {
release: bool,
},
Expand All @@ -36,6 +43,13 @@ mod args {
day: Option<Day>,
store: bool,
},
NewYear {
year: u32,
},
SetYear {
year: u32,
},
GetYear,
#[cfg(feature = "today")]
Today,
}
Expand Down Expand Up @@ -74,6 +88,18 @@ mod args {
submit: args.opt_value_from_str("--submit")?,
dhat: args.contains("--dhat"),
},
Some("try") => AppArguments::Try {
day: args.free_from_str()?,
test: args.free_from_str().ok(),
dhat: args.contains("--dhat"),
},
Some("new-year") => AppArguments::NewYear {
year: args.free_from_str()?,
},
Some("set-year") => AppArguments::SetYear {
year: args.free_from_str()?,
},
Some("get-year") => AppArguments::GetYear,
#[cfg(feature = "today")]
Some("today") => AppArguments::Today,
Some(x) => {
Expand Down Expand Up @@ -122,6 +148,7 @@ fn main() {
dhat,
submit,
} => solve::handle(day, release, dhat, submit),
AppArguments::Try { day, test, dhat } => attempt::handle(day, test, dhat),
#[cfg(feature = "today")]
AppArguments::Today => {
match Day::today() {
Expand All @@ -139,6 +166,12 @@ fn main() {
}
};
}
AppArguments::NewYear { year } => new_year::handle(year),
AppArguments::SetYear { year } => set_year::handle(year),
AppArguments::GetYear => {
let year = advent_of_code::template::get_year_exit_on_fail();
println!("The repository is currently set to {}.", year);
}
},
};
}
15 changes: 5 additions & 10 deletions src/template/aoc_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,24 +81,19 @@ pub fn submit(day: Day, part: u8, result: &str) -> Result<Output, AocCommandErro
}

fn get_input_path(day: Day) -> String {
format!("data/inputs/{day}.txt")
let year = crate::template::get_year_exit_on_fail();
format!("{year}/data/inputs/{day}.txt")
}

fn get_puzzle_path(day: Day) -> String {
format!("data/puzzles/{day}.md")
}

fn get_year() -> Option<u16> {
match std::env::var("AOC_YEAR") {
Ok(x) => x.parse().ok().or(None),
Err(_) => None,
}
let year = crate::template::get_year_exit_on_fail();
format!("{year}/data/puzzles/{day}.md")
}

fn build_args(command: &str, args: &[String], day: Day) -> Vec<String> {
let mut cmd_args = args.to_vec();

if let Some(year) = get_year() {
if let Some(year) = super::get_year() {
cmd_args.push("--year".into());
cmd_args.push(year.to_string());
}
Expand Down
37 changes: 37 additions & 0 deletions src/template/commands/attempt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use std::process::{Command, Stdio};

use crate::template::Day;

pub fn handle(day: Day, test: Option<String>, dhat: bool) {
let year = crate::template::get_year_exit_on_fail();
let year = format!("advent_of_code_{}", year);
let mut cmd_args = vec![
"test".to_string(),
"-p".to_string(),
year,
"--bin".to_string(),
day.to_string(),
];

if dhat {
cmd_args.extend([
"--profile".to_string(),
"dhat".to_string(),
"--features".to_string(),
"dhat-heap".to_string(),
]);
} else if let Some(test_id) = test {
cmd_args.push(test_id);
}

cmd_args.push("--".to_string());

let mut cmd = Command::new("cargo")
.args(&cmd_args)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.spawn()
.unwrap();

cmd.wait().unwrap();
}
37 changes: 37 additions & 0 deletions src/template/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,43 @@
use std::{
fs::{File, OpenOptions},
io::Write,
path::PathBuf,
};

pub mod all;
pub mod attempt;
pub mod download;
pub mod new_year;
pub mod read;
pub mod scaffold;
pub mod set_year;
pub mod solve;
pub mod time;

#[derive(Debug)]
enum WriteError {
Open,
Write,
}

fn open_file(filepath: &PathBuf) -> Result<File, std::io::Error> {
OpenOptions::new().write(true).truncate(true).open(filepath)
}

fn write_file(filepath: &PathBuf, to_write: &[u8]) -> Result<(), WriteError> {
let file = open_file(filepath);
if file.is_err() {
eprintln!("Failed to open file {}", filepath.to_str().unwrap());
return Err(WriteError::Open);
}
let mut file = file.unwrap();

match file.write_all(to_write) {
Ok(()) => Ok(()),
Err(e) => {
let filepath = filepath.to_str().unwrap();
eprintln!("Failed to write to {filepath}: {e}");
Err(WriteError::Write)
}
}
}
Loading