Compare commits

..

No commits in common. "7526c6b1f92626df6ab8b4853535b73711bfada4" and "24539666afb0e8c80fbccbca7ad212ba8fbd1189" have entirely different histories.

23 changed files with 476 additions and 653 deletions

2
.gitignore vendored
View file

@ -4,7 +4,7 @@ target/
/dev/Cargo.lock
# State file
.rustlings-state.txt
.rustlings-state.json
# oranda
public/

72
Cargo.lock generated
View file

@ -261,9 +261,9 @@ checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10"
[[package]]
name = "either"
version = "1.11.0"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a47c1c47d2f5964e29c61246e81db715514cd532db6b5116a25ea3c03d6780a2"
checksum = "11157ac094ffbdde99aa67b23417ebdd801842852b500e395a45a9c0aac03e4a"
[[package]]
name = "equivalent"
@ -684,12 +684,12 @@ dependencies = [
"assert_cmd",
"clap",
"crossterm",
"hashbrown",
"notify-debouncer-mini",
"predicates",
"ratatui",
"rustlings-macros",
"serde",
"serde_json",
"toml_edit",
"which",
]
@ -748,6 +748,17 @@ dependencies = [
"syn 2.0.58",
]
[[package]]
name = "serde_json"
version = "1.0.115"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd"
dependencies = [
"itoa",
"ryu",
"serde",
]
[[package]]
name = "serde_spanned"
version = "0.6.5"
@ -1000,7 +1011,7 @@ version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.5",
"windows-targets 0.52.4",
]
[[package]]
@ -1020,18 +1031,17 @@ dependencies = [
[[package]]
name = "windows-targets"
version = "0.52.5"
version = "0.52.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb"
checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b"
dependencies = [
"windows_aarch64_gnullvm 0.52.5",
"windows_aarch64_msvc 0.52.5",
"windows_i686_gnu 0.52.5",
"windows_i686_gnullvm",
"windows_i686_msvc 0.52.5",
"windows_x86_64_gnu 0.52.5",
"windows_x86_64_gnullvm 0.52.5",
"windows_x86_64_msvc 0.52.5",
"windows_aarch64_gnullvm 0.52.4",
"windows_aarch64_msvc 0.52.4",
"windows_i686_gnu 0.52.4",
"windows_i686_msvc 0.52.4",
"windows_x86_64_gnu 0.52.4",
"windows_x86_64_gnullvm 0.52.4",
"windows_x86_64_msvc 0.52.4",
]
[[package]]
@ -1042,9 +1052,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.5"
version = "0.52.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263"
checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9"
[[package]]
name = "windows_aarch64_msvc"
@ -1054,9 +1064,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.5"
version = "0.52.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6"
checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675"
[[package]]
name = "windows_i686_gnu"
@ -1066,15 +1076,9 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
version = "0.52.5"
version = "0.52.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9"
checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3"
[[package]]
name = "windows_i686_msvc"
@ -1084,9 +1088,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_i686_msvc"
version = "0.52.5"
version = "0.52.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf"
checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02"
[[package]]
name = "windows_x86_64_gnu"
@ -1096,9 +1100,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.5"
version = "0.52.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9"
checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03"
[[package]]
name = "windows_x86_64_gnullvm"
@ -1108,9 +1112,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.5"
version = "0.52.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596"
checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177"
[[package]]
name = "windows_x86_64_msvc"
@ -1120,9 +1124,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.5"
version = "0.52.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"
checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8"
[[package]]
name = "winnow"

View file

@ -37,10 +37,10 @@ edition.workspace = true
anyhow.workspace = true
clap = { version = "4.5.4", features = ["derive"] }
crossterm = "0.27.0"
hashbrown = "0.14.3"
notify-debouncer-mini = "0.4.1"
ratatui = "0.26.1"
rustlings-macros = { path = "rustlings-macros" }
serde_json = "1.0.115"
serde.workspace = true
toml_edit.workspace = true
which = "6.0.1"

View file

@ -1,5 +1,6 @@
// intro1.rs
//
// TODO: Update comment
// We sometimes encourage you to keep trying things on a given exercise, even
// after you already figured it out. If you got everything working and feel
// ready for the next exercise, remove the `I AM NOT DONE` comment below.

View file

@ -10,18 +10,18 @@ use std::{
};
#[derive(Deserialize)]
struct ExerciseInfo {
struct Exercise {
name: String,
dir: Option<String>,
path: String,
}
#[derive(Deserialize)]
struct InfoFile {
exercises: Vec<ExerciseInfo>,
struct InfoToml {
exercises: Vec<Exercise>,
}
fn main() -> Result<()> {
let exercise_infos = toml_edit::de::from_str::<InfoFile>(
let exercises = toml_edit::de::from_str::<InfoToml>(
&fs::read_to_string("info.toml").context("Failed to read `info.toml`")?,
)
.context("Failed to deserialize `info.toml`")?
@ -36,16 +36,12 @@ fn main() -> Result<()> {
bin = [\n",
);
for exercise_info in exercise_infos {
for exercise in exercises {
buf.extend_from_slice(b" { name = \"");
buf.extend_from_slice(exercise_info.name.as_bytes());
buf.extend_from_slice(b"\", path = \"../exercises/");
if let Some(dir) = &exercise_info.dir {
buf.extend_from_slice(dir.as_bytes());
buf.push(b'/');
}
buf.extend_from_slice(exercise_info.name.as_bytes());
buf.extend_from_slice(b".rs\" },\n");
buf.extend_from_slice(exercise.name.as_bytes());
buf.extend_from_slice(b"\", path = \"../");
buf.extend_from_slice(exercise.path.as_bytes());
buf.extend_from_slice(b"\" },\n");
}
buf.extend_from_slice(

272
info.toml
View file

@ -33,11 +33,10 @@ https://github.com/rust-lang/rustlings/blob/main/CONTRIBUTING.md
# INTRO
# TODO: Update exercise
[[exercises]]
name = "intro1"
dir = "00_intro"
mode = "run"
path = "exercises/00_intro/intro1.rs"
mode = "compile"
# TODO: Fix hint
hint = """
Remove the `I AM NOT DONE` comment in the `exercises/intro00/intro1.rs` file
@ -45,8 +44,8 @@ to move on to the next exercise."""
[[exercises]]
name = "intro2"
dir = "00_intro"
mode = "run"
path = "exercises/00_intro/intro2.rs"
mode = "compile"
hint = """
The compiler is informing us that we've got the name of the print macro wrong, and has suggested an alternative."""
@ -54,16 +53,16 @@ The compiler is informing us that we've got the name of the print macro wrong, a
[[exercises]]
name = "variables1"
dir = "01_variables"
mode = "run"
path = "exercises/01_variables/variables1.rs"
mode = "compile"
hint = """
The declaration in the first line in the main function is missing a keyword
that is needed in Rust to create a new variable binding."""
[[exercises]]
name = "variables2"
dir = "01_variables"
mode = "run"
path = "exercises/01_variables/variables2.rs"
mode = "compile"
hint = """
The compiler message is saying that Rust cannot infer the type that the
variable binding `x` has with what is given here.
@ -81,8 +80,8 @@ What if `x` is the same type as `10`? What if it's a different type?"""
[[exercises]]
name = "variables3"
dir = "01_variables"
mode = "run"
path = "exercises/01_variables/variables3.rs"
mode = "compile"
hint = """
Oops! In this exercise, we have a variable binding that we've created on in the
first line in the `main` function, and we're trying to use it in the next line,
@ -95,8 +94,8 @@ programming language -- thankfully the Rust compiler has caught this for us!"""
[[exercises]]
name = "variables4"
dir = "01_variables"
mode = "run"
path = "exercises/01_variables/variables4.rs"
mode = "compile"
hint = """
In Rust, variable bindings are immutable by default. But here we're trying
to reassign a different value to `x`! There's a keyword we can use to make
@ -104,8 +103,8 @@ a variable binding mutable instead."""
[[exercises]]
name = "variables5"
dir = "01_variables"
mode = "run"
path = "exercises/01_variables/variables5.rs"
mode = "compile"
hint = """
In `variables4` we already learned how to make an immutable variable mutable
using a special keyword. Unfortunately this doesn't help us much in this
@ -122,8 +121,8 @@ Try to solve this exercise afterwards using this technique."""
[[exercises]]
name = "variables6"
dir = "01_variables"
mode = "run"
path = "exercises/01_variables/variables6.rs"
mode = "compile"
hint = """
We know about variables and mutability, but there is another important type of
variable available: constants.
@ -142,8 +141,8 @@ https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#constants
[[exercises]]
name = "functions1"
dir = "02_functions"
mode = "run"
path = "exercises/02_functions/functions1.rs"
mode = "compile"
hint = """
This main function is calling a function that it expects to exist, but the
function doesn't exist. It expects this function to have the name `call_me`.
@ -152,24 +151,24 @@ Sounds a lot like `main`, doesn't it?"""
[[exercises]]
name = "functions2"
dir = "02_functions"
mode = "run"
path = "exercises/02_functions/functions2.rs"
mode = "compile"
hint = """
Rust requires that all parts of a function's signature have type annotations,
but `call_me` is missing the type annotation of `num`."""
[[exercises]]
name = "functions3"
dir = "02_functions"
mode = "run"
path = "exercises/02_functions/functions3.rs"
mode = "compile"
hint = """
This time, the function *declaration* is okay, but there's something wrong
with the place where we're calling the function."""
[[exercises]]
name = "functions4"
dir = "02_functions"
mode = "run"
path = "exercises/02_functions/functions4.rs"
mode = "compile"
hint = """
The error message points to the function `sale_price` and says it expects a type
after the `->`. This is where the function's return type should be -- take a
@ -180,8 +179,8 @@ for the inputs of the functions here, since the original prices shouldn't be neg
[[exercises]]
name = "functions5"
dir = "02_functions"
mode = "run"
path = "exercises/02_functions/functions5.rs"
mode = "compile"
hint = """
This is a really common error that can be fixed by removing one character.
It happens because Rust distinguishes between expressions and statements:
@ -199,7 +198,7 @@ They are not the same. There are two solutions:
[[exercises]]
name = "if1"
dir = "03_if"
path = "exercises/03_if/if1.rs"
mode = "test"
hint = """
It's possible to do this in one line if you would like!
@ -215,7 +214,7 @@ Remember in Rust that:
[[exercises]]
name = "if2"
dir = "03_if"
path = "exercises/03_if/if2.rs"
mode = "test"
hint = """
For that first compiler error, it's important in Rust that each conditional
@ -224,7 +223,7 @@ conditions checking different input values."""
[[exercises]]
name = "if3"
dir = "03_if"
path = "exercises/03_if/if3.rs"
mode = "test"
hint = """
In Rust, every arm of an `if` expression has to return the same type of value.
@ -234,6 +233,7 @@ Make sure the type is consistent across all arms."""
[[exercises]]
name = "quiz1"
path = "exercises/quiz1.rs"
mode = "test"
hint = "No hints this time ;)"
@ -241,20 +241,20 @@ hint = "No hints this time ;)"
[[exercises]]
name = "primitive_types1"
dir = "04_primitive_types"
mode = "run"
path = "exercises/04_primitive_types/primitive_types1.rs"
mode = "compile"
hint = "No hints this time ;)"
[[exercises]]
name = "primitive_types2"
dir = "04_primitive_types"
mode = "run"
path = "exercises/04_primitive_types/primitive_types2.rs"
mode = "compile"
hint = "No hints this time ;)"
[[exercises]]
name = "primitive_types3"
dir = "04_primitive_types"
mode = "run"
path = "exercises/04_primitive_types/primitive_types3.rs"
mode = "compile"
hint = """
There's a shorthand to initialize Arrays with a certain size that does not
require you to type in 100 items (but you certainly can if you want!).
@ -269,7 +269,7 @@ for `a.len() >= 100`?"""
[[exercises]]
name = "primitive_types4"
dir = "04_primitive_types"
path = "exercises/04_primitive_types/primitive_types4.rs"
mode = "test"
hint = """
Take a look at the 'Understanding Ownership -> Slices -> Other Slices' section
@ -284,8 +284,8 @@ https://doc.rust-lang.org/nomicon/coercions.html"""
[[exercises]]
name = "primitive_types5"
dir = "04_primitive_types"
mode = "run"
path = "exercises/04_primitive_types/primitive_types5.rs"
mode = "compile"
hint = """
Take a look at the 'Data Types -> The Tuple Type' section of the book:
https://doc.rust-lang.org/book/ch03-02-data-types.html#the-tuple-type
@ -297,7 +297,7 @@ of the tuple. You can do it!!"""
[[exercises]]
name = "primitive_types6"
dir = "04_primitive_types"
path = "exercises/04_primitive_types/primitive_types6.rs"
mode = "test"
hint = """
While you could use a destructuring `let` for the tuple here, try
@ -310,7 +310,7 @@ Now you have another tool in your toolbox!"""
[[exercises]]
name = "vecs1"
dir = "05_vecs"
path = "exercises/05_vecs/vecs1.rs"
mode = "test"
hint = """
In Rust, there are two ways to define a Vector.
@ -325,7 +325,7 @@ of the Rust book to learn more.
[[exercises]]
name = "vecs2"
dir = "05_vecs"
path = "exercises/05_vecs/vecs2.rs"
mode = "test"
hint = """
In the first function we are looping over the Vector and getting a reference to
@ -348,7 +348,7 @@ What do you think is the more commonly used pattern under Rust developers?
[[exercises]]
name = "move_semantics1"
dir = "06_move_semantics"
path = "exercises/06_move_semantics/move_semantics1.rs"
mode = "test"
hint = """
So you've got the "cannot borrow immutable local variable `vec` as mutable"
@ -362,7 +362,7 @@ happens!"""
[[exercises]]
name = "move_semantics2"
dir = "06_move_semantics"
path = "exercises/06_move_semantics/move_semantics2.rs"
mode = "test"
hint = """
When running this exercise for the first time, you'll notice an error about
@ -383,7 +383,7 @@ try them all:
[[exercises]]
name = "move_semantics3"
dir = "06_move_semantics"
path = "exercises/06_move_semantics/move_semantics3.rs"
mode = "test"
hint = """
The difference between this one and the previous ones is that the first line
@ -393,7 +393,7 @@ an existing binding to be a mutable binding instead of an immutable one :)"""
[[exercises]]
name = "move_semantics4"
dir = "06_move_semantics"
path = "exercises/06_move_semantics/move_semantics4.rs"
mode = "test"
hint = """
Stop reading whenever you feel like you have enough direction :) Or try
@ -407,7 +407,7 @@ So the end goal is to:
[[exercises]]
name = "move_semantics5"
dir = "06_move_semantics"
path = "exercises/06_move_semantics/move_semantics5.rs"
mode = "test"
hint = """
Carefully reason about the range in which each mutable reference is in
@ -419,8 +419,8 @@ https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-ref
[[exercises]]
name = "move_semantics6"
dir = "06_move_semantics"
mode = "run"
path = "exercises/06_move_semantics/move_semantics6.rs"
mode = "compile"
hint = """
To find the answer, you can consult the book section "References and Borrowing":
https://doc.rust-lang.org/stable/book/ch04-02-references-and-borrowing.html
@ -440,7 +440,7 @@ Another hint: it has to do with the `&` character."""
[[exercises]]
name = "structs1"
dir = "07_structs"
path = "exercises/07_structs/structs1.rs"
mode = "test"
hint = """
Rust has more than one type of struct. Three actually, all variants are used to
@ -460,7 +460,7 @@ https://doc.rust-lang.org/book/ch05-01-defining-structs.html"""
[[exercises]]
name = "structs2"
dir = "07_structs"
path = "exercises/07_structs/structs2.rs"
mode = "test"
hint = """
Creating instances of structs is easy, all you need to do is assign some values
@ -472,7 +472,7 @@ https://doc.rust-lang.org/stable/book/ch05-01-defining-structs.html#creating-ins
[[exercises]]
name = "structs3"
dir = "07_structs"
path = "exercises/07_structs/structs3.rs"
mode = "test"
hint = """
For `is_international`: What makes a package international? Seems related to
@ -488,21 +488,21 @@ https://doc.rust-lang.org/book/ch05-03-method-syntax.html"""
[[exercises]]
name = "enums1"
dir = "08_enums"
mode = "run"
path = "exercises/08_enums/enums1.rs"
mode = "compile"
hint = "No hints this time ;)"
[[exercises]]
name = "enums2"
dir = "08_enums"
mode = "run"
path = "exercises/08_enums/enums2.rs"
mode = "compile"
hint = """
You can create enumerations that have different variants with different types
such as no data, anonymous structs, a single string, tuples, ...etc"""
[[exercises]]
name = "enums3"
dir = "08_enums"
path = "exercises/08_enums/enums3.rs"
mode = "test"
hint = """
As a first step, you can define enums to compile this code without errors.
@ -516,8 +516,8 @@ to get value in the variant."""
[[exercises]]
name = "strings1"
dir = "09_strings"
mode = "run"
path = "exercises/09_strings/strings1.rs"
mode = "compile"
hint = """
The `current_favorite_color` function is currently returning a string slice
with the `'static` lifetime. We know this because the data of the string lives
@ -530,8 +530,8 @@ another way that uses the `From` trait."""
[[exercises]]
name = "strings2"
dir = "09_strings"
mode = "run"
path = "exercises/09_strings/strings2.rs"
mode = "compile"
hint = """
Yes, it would be really easy to fix this by just changing the value bound to
`word` to be a string slice instead of a `String`, wouldn't it?? There is a way
@ -545,7 +545,7 @@ https://doc.rust-lang.org/stable/book/ch15-02-deref.html#implicit-deref-coercion
[[exercises]]
name = "strings3"
dir = "09_strings"
path = "exercises/09_strings/strings3.rs"
mode = "test"
hint = """
There's tons of useful standard library functions for strings. Let's try and use some of them:
@ -556,16 +556,16 @@ the string slice into an owned string, which you can then freely extend."""
[[exercises]]
name = "strings4"
dir = "09_strings"
mode = "run"
path = "exercises/09_strings/strings4.rs"
mode = "compile"
hint = "No hints this time ;)"
# MODULES
[[exercises]]
name = "modules1"
dir = "10_modules"
mode = "run"
path = "exercises/10_modules/modules1.rs"
mode = "compile"
hint = """
Everything is private in Rust by default-- but there's a keyword we can use
to make something public! The compiler error should point to the thing that
@ -573,8 +573,8 @@ needs to be public."""
[[exercises]]
name = "modules2"
dir = "10_modules"
mode = "run"
path = "exercises/10_modules/modules2.rs"
mode = "compile"
hint = """
The delicious_snacks module is trying to present an external interface that is
different than its internal structure (the `fruits` and `veggies` modules and
@ -585,8 +585,8 @@ Learn more at https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-w
[[exercises]]
name = "modules3"
dir = "10_modules"
mode = "run"
path = "exercises/10_modules/modules3.rs"
mode = "compile"
hint = """
`UNIX_EPOCH` and `SystemTime` are declared in the `std::time` module. Add a
`use` statement for these two to bring them into scope. You can use nested
@ -596,7 +596,7 @@ paths or the glob operator to bring these two in using only one line."""
[[exercises]]
name = "hashmaps1"
dir = "11_hashmaps"
path = "exercises/11_hashmaps/hashmaps1.rs"
mode = "test"
hint = """
Hint 1: Take a look at the return type of the function to figure out
@ -608,7 +608,7 @@ Hint 2: Number of fruits should be at least 5. And you have to put
[[exercises]]
name = "hashmaps2"
dir = "11_hashmaps"
path = "exercises/11_hashmaps/hashmaps2.rs"
mode = "test"
hint = """
Use the `entry()` and `or_insert()` methods of `HashMap` to achieve this.
@ -617,7 +617,7 @@ Learn more at https://doc.rust-lang.org/stable/book/ch08-03-hash-maps.html#only-
[[exercises]]
name = "hashmaps3"
dir = "11_hashmaps"
path = "exercises/11_hashmaps/hashmaps3.rs"
mode = "test"
hint = """
Hint 1: Use the `entry()` and `or_insert()` methods of `HashMap` to insert
@ -635,6 +635,7 @@ Learn more at https://doc.rust-lang.org/book/ch08-03-hash-maps.html#updating-a-v
[[exercises]]
name = "quiz2"
path = "exercises/quiz2.rs"
mode = "test"
hint = "No hints this time ;)"
@ -642,7 +643,7 @@ hint = "No hints this time ;)"
[[exercises]]
name = "options1"
dir = "12_options"
path = "exercises/12_options/options1.rs"
mode = "test"
hint = """
Options can have a `Some` value, with an inner value, or a `None` value,
@ -654,7 +655,7 @@ it doesn't panic in your face later?"""
[[exercises]]
name = "options2"
dir = "12_options"
path = "exercises/12_options/options2.rs"
mode = "test"
hint = """
Check out:
@ -671,8 +672,8 @@ Also see `Option::flatten`
[[exercises]]
name = "options3"
dir = "12_options"
mode = "run"
path = "exercises/12_options/options3.rs"
mode = "compile"
hint = """
The compiler says a partial move happened in the `match` statement. How can
this be avoided? The compiler shows the correction needed.
@ -684,7 +685,7 @@ https://doc.rust-lang.org/std/keyword.ref.html"""
[[exercises]]
name = "errors1"
dir = "13_error_handling"
path = "exercises/13_error_handling/errors1.rs"
mode = "test"
hint = """
`Ok` and `Err` are the two variants of `Result`, so what the tests are saying
@ -700,7 +701,7 @@ To make this change, you'll need to:
[[exercises]]
name = "errors2"
dir = "13_error_handling"
path = "exercises/13_error_handling/errors2.rs"
mode = "test"
hint = """
One way to handle this is using a `match` statement on
@ -716,8 +717,8 @@ and give it a try!"""
[[exercises]]
name = "errors3"
dir = "13_error_handling"
mode = "run"
path = "exercises/13_error_handling/errors3.rs"
mode = "compile"
hint = """
If other functions can return a `Result`, why shouldn't `main`? It's a fairly
common convention to return something like `Result<(), ErrorType>` from your
@ -728,7 +729,7 @@ positive results."""
[[exercises]]
name = "errors4"
dir = "13_error_handling"
path = "exercises/13_error_handling/errors4.rs"
mode = "test"
hint = """
`PositiveNonzeroInteger::new` is always creating a new instance and returning
@ -740,8 +741,8 @@ everything is... okay :)"""
[[exercises]]
name = "errors5"
dir = "13_error_handling"
mode = "run"
path = "exercises/13_error_handling/errors5.rs"
mode = "compile"
hint = """
There are two different possible `Result` types produced within `main()`, which
are propagated using `?` operators. How do we declare a return type from
@ -764,7 +765,7 @@ https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/reen
[[exercises]]
name = "errors6"
dir = "13_error_handling"
path = "exercises/13_error_handling/errors6.rs"
mode = "test"
hint = """
This exercise uses a completed version of `PositiveNonzeroInteger` from
@ -786,8 +787,8 @@ https://doc.rust-lang.org/std/result/enum.Result.html#method.map_err"""
[[exercises]]
name = "generics1"
dir = "14_generics"
mode = "run"
path = "exercises/14_generics/generics1.rs"
mode = "compile"
hint = """
Vectors in Rust make use of generics to create dynamically sized arrays of any
type.
@ -796,7 +797,7 @@ You need to tell the compiler what type we are pushing onto this vector."""
[[exercises]]
name = "generics2"
dir = "14_generics"
path = "exercises/14_generics/generics2.rs"
mode = "test"
hint = """
Currently we are wrapping only values of type `u32`.
@ -810,7 +811,7 @@ If you are still stuck https://doc.rust-lang.org/stable/book/ch10-01-syntax.html
[[exercises]]
name = "traits1"
dir = "15_traits"
path = "exercises/15_traits/traits1.rs"
mode = "test"
hint = """
A discussion about Traits in Rust can be found at:
@ -819,7 +820,7 @@ https://doc.rust-lang.org/book/ch10-02-traits.html
[[exercises]]
name = "traits2"
dir = "15_traits"
path = "exercises/15_traits/traits2.rs"
mode = "test"
hint = """
Notice how the trait takes ownership of `self`, and returns `Self`.
@ -832,7 +833,7 @@ the documentation at: https://doc.rust-lang.org/std/vec/struct.Vec.html"""
[[exercises]]
name = "traits3"
dir = "15_traits"
path = "exercises/15_traits/traits3.rs"
mode = "test"
hint = """
Traits can have a default implementation for functions. Structs that implement
@ -844,7 +845,7 @@ See the documentation at: https://doc.rust-lang.org/book/ch10-02-traits.html#def
[[exercises]]
name = "traits4"
dir = "15_traits"
path = "exercises/15_traits/traits4.rs"
mode = "test"
hint = """
Instead of using concrete types as parameters you can use traits. Try replacing
@ -855,8 +856,8 @@ See the documentation at: https://doc.rust-lang.org/book/ch10-02-traits.html#tra
[[exercises]]
name = "traits5"
dir = "15_traits"
mode = "run"
path = "exercises/15_traits/traits5.rs"
mode = "compile"
hint = """
To ensure a parameter implements multiple traits use the '+ syntax'. Try
replacing the '??' with 'impl <> + <>'.
@ -868,6 +869,7 @@ See the documentation at: https://doc.rust-lang.org/book/ch10-02-traits.html#spe
[[exercises]]
name = "quiz3"
path = "exercises/quiz3.rs"
mode = "test"
hint = """
To find the best solution to this challenge you're going to need to think back
@ -879,16 +881,16 @@ You may also need this: `use std::fmt::Display;`."""
[[exercises]]
name = "lifetimes1"
dir = "16_lifetimes"
mode = "run"
path = "exercises/16_lifetimes/lifetimes1.rs"
mode = "compile"
hint = """
Let the compiler guide you. Also take a look at the book if you need help:
https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html"""
[[exercises]]
name = "lifetimes2"
dir = "16_lifetimes"
mode = "run"
path = "exercises/16_lifetimes/lifetimes2.rs"
mode = "compile"
hint = """
Remember that the generic lifetime `'a` will get the concrete lifetime that is
equal to the smaller of the lifetimes of `x` and `y`.
@ -901,8 +903,8 @@ inner block:
[[exercises]]
name = "lifetimes3"
dir = "16_lifetimes"
mode = "run"
path = "exercises/16_lifetimes/lifetimes3.rs"
mode = "compile"
hint = """
If you use a lifetime annotation in a struct's fields, where else does it need
to be added?"""
@ -911,7 +913,7 @@ to be added?"""
[[exercises]]
name = "tests1"
dir = "17_tests"
path = "exercises/17_tests/tests1.rs"
mode = "test"
hint = """
You don't even need to write any code to test -- you can just test values and
@ -926,7 +928,7 @@ ones pass, and which ones fail :)"""
[[exercises]]
name = "tests2"
dir = "17_tests"
path = "exercises/17_tests/tests2.rs"
mode = "test"
hint = """
Like the previous exercise, you don't need to write any code to get this test
@ -939,7 +941,7 @@ argument comes first and which comes second!"""
[[exercises]]
name = "tests3"
dir = "17_tests"
path = "exercises/17_tests/tests3.rs"
mode = "test"
hint = """
You can call a function right where you're passing arguments to `assert!`. So
@ -950,7 +952,7 @@ what you're doing using `!`, like `assert!(!having_fun())`."""
[[exercises]]
name = "tests4"
dir = "17_tests"
path = "exercises/17_tests/tests4.rs"
mode = "test"
hint = """
We expect method `Rectangle::new()` to panic for negative values.
@ -964,7 +966,7 @@ https://doc.rust-lang.org/stable/book/ch11-01-writing-tests.html#checking-for-pa
[[exercises]]
name = "iterators1"
dir = "18_iterators"
path = "exercises/18_iterators/iterators1.rs"
mode = "test"
hint = """
Step 1:
@ -987,7 +989,7 @@ https://doc.rust-lang.org/std/iter/trait.Iterator.html for some ideas.
[[exercises]]
name = "iterators2"
dir = "18_iterators"
path = "exercises/18_iterators/iterators2.rs"
mode = "test"
hint = """
Step 1:
@ -1013,7 +1015,7 @@ powerful and very general. Rust just needs to know the desired type."""
[[exercises]]
name = "iterators3"
dir = "18_iterators"
path = "exercises/18_iterators/iterators3.rs"
mode = "test"
hint = """
The `divide` function needs to return the correct error when even division is
@ -1032,7 +1034,7 @@ powerful! It can make the solution to this exercise infinitely easier."""
[[exercises]]
name = "iterators4"
dir = "18_iterators"
path = "exercises/18_iterators/iterators4.rs"
mode = "test"
hint = """
In an imperative language, you might write a `for` loop that updates a mutable
@ -1044,7 +1046,7 @@ Hint 2: Check out the `fold` and `rfold` methods!"""
[[exercises]]
name = "iterators5"
dir = "18_iterators"
path = "exercises/18_iterators/iterators5.rs"
mode = "test"
hint = """
The documentation for the `std::iter::Iterator` trait contains numerous methods
@ -1063,7 +1065,7 @@ a different method that could make your code more compact than using `fold`."""
[[exercises]]
name = "box1"
dir = "19_smart_pointers"
path = "exercises/19_smart_pointers/box1.rs"
mode = "test"
hint = """
Step 1:
@ -1087,7 +1089,7 @@ definition and try other types!
[[exercises]]
name = "rc1"
dir = "19_smart_pointers"
path = "exercises/19_smart_pointers/rc1.rs"
mode = "test"
hint = """
This is a straightforward exercise to use the `Rc<T>` type. Each `Planet` has
@ -1106,8 +1108,8 @@ See more at: https://doc.rust-lang.org/book/ch15-04-rc.html
[[exercises]]
name = "arc1"
dir = "19_smart_pointers"
mode = "run"
path = "exercises/19_smart_pointers/arc1.rs"
mode = "compile"
hint = """
Make `shared_numbers` be an `Arc` from the numbers vector. Then, in order
to avoid creating a copy of `numbers`, you'll need to create `child_numbers`
@ -1124,7 +1126,7 @@ https://doc.rust-lang.org/stable/book/ch16-00-concurrency.html
[[exercises]]
name = "cow1"
dir = "19_smart_pointers"
path = "exercises/19_smart_pointers/cow1.rs"
mode = "test"
hint = """
If `Cow` already owns the data it doesn't need to clone it when `to_mut()` is
@ -1138,8 +1140,8 @@ on the `Cow` type.
[[exercises]]
name = "threads1"
dir = "20_threads"
mode = "run"
path = "exercises/20_threads/threads1.rs"
mode = "compile"
hint = """
`JoinHandle` is a struct that is returned from a spawned thread:
https://doc.rust-lang.org/std/thread/fn.spawn.html
@ -1156,8 +1158,8 @@ https://doc.rust-lang.org/std/thread/struct.JoinHandle.html
[[exercises]]
name = "threads2"
dir = "20_threads"
mode = "run"
path = "exercises/20_threads/threads2.rs"
mode = "compile"
hint = """
`Arc` is an Atomic Reference Counted pointer that allows safe, shared access
to **immutable** data. But we want to *change* the number of `jobs_completed`
@ -1178,7 +1180,7 @@ https://doc.rust-lang.org/book/ch16-03-shared-state.html#sharing-a-mutext-betwee
[[exercises]]
name = "threads3"
dir = "20_threads"
path = "exercises/20_threads/threads3.rs"
mode = "test"
hint = """
An alternate way to handle concurrency between threads is to use an `mpsc`
@ -1197,8 +1199,8 @@ See https://doc.rust-lang.org/book/ch16-02-message-passing.html for more info.
[[exercises]]
name = "macros1"
dir = "21_macros"
mode = "run"
path = "exercises/21_macros/macros1.rs"
mode = "compile"
hint = """
When you call a macro, you need to add something special compared to a
regular function call. If you're stuck, take a look at what's inside
@ -1206,8 +1208,8 @@ regular function call. If you're stuck, take a look at what's inside
[[exercises]]
name = "macros2"
dir = "21_macros"
mode = "run"
path = "exercises/21_macros/macros2.rs"
mode = "compile"
hint = """
Macros don't quite play by the same rules as the rest of Rust, in terms of
what's available where.
@ -1217,8 +1219,8 @@ Unlike other things in Rust, the order of "where you define a macro" versus
[[exercises]]
name = "macros3"
dir = "21_macros"
mode = "run"
path = "exercises/21_macros/macros3.rs"
mode = "compile"
hint = """
In order to use a macro outside of its module, you need to do something
special to the module to lift the macro out into its parent.
@ -1228,8 +1230,8 @@ exported macros, if you've seen any of those around."""
[[exercises]]
name = "macros4"
dir = "21_macros"
mode = "run"
path = "exercises/21_macros/macros4.rs"
mode = "compile"
hint = """
You only need to add a single character to make this compile.
@ -1245,7 +1247,7 @@ https://veykril.github.io/tlborm/"""
[[exercises]]
name = "clippy1"
dir = "22_clippy"
path = "exercises/22_clippy/clippy1.rs"
mode = "clippy"
hint = """
Rust stores the highest precision version of any long or infinite precision
@ -1261,14 +1263,14 @@ appropriate replacement constant from `std::f32::consts`..."""
[[exercises]]
name = "clippy2"
dir = "22_clippy"
path = "exercises/22_clippy/clippy2.rs"
mode = "clippy"
hint = """
`for` loops over `Option` values are more clearly expressed as an `if let`"""
[[exercises]]
name = "clippy3"
dir = "22_clippy"
path = "exercises/22_clippy/clippy3.rs"
mode = "clippy"
hint = "No hints this time!"
@ -1276,7 +1278,7 @@ hint = "No hints this time!"
[[exercises]]
name = "using_as"
dir = "23_conversions"
path = "exercises/23_conversions/using_as.rs"
mode = "test"
hint = """
Use the `as` operator to cast one of the operands in the last line of the
@ -1284,14 +1286,14 @@ Use the `as` operator to cast one of the operands in the last line of the
[[exercises]]
name = "from_into"
dir = "23_conversions"
path = "exercises/23_conversions/from_into.rs"
mode = "test"
hint = """
Follow the steps provided right before the `From` implementation"""
[[exercises]]
name = "from_str"
dir = "23_conversions"
path = "exercises/23_conversions/from_str.rs"
mode = "test"
hint = """
The implementation of `FromStr` should return an `Ok` with a `Person` object,
@ -1312,7 +1314,7 @@ https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/reen
[[exercises]]
name = "try_from_into"
dir = "23_conversions"
path = "exercises/23_conversions/try_from_into.rs"
mode = "test"
hint = """
Follow the steps provided right before the `TryFrom` implementation.
@ -1335,7 +1337,7 @@ Challenge: Can you make the `TryFrom` implementations generic over many integer
[[exercises]]
name = "as_ref_mut"
dir = "23_conversions"
path = "exercises/23_conversions/as_ref_mut.rs"
mode = "test"
hint = """
Add `AsRef<str>` or `AsMut<u32>` as a trait bound to the functions."""

View file

@ -4,128 +4,106 @@ use crossterm::{
terminal::{Clear, ClearType},
ExecutableCommand,
};
use serde::{Deserialize, Serialize};
use std::{
fs::{self, File},
io::{Read, StdoutLock, Write},
fs,
io::{StdoutLock, Write},
};
use crate::{exercise::Exercise, info_file::ExerciseInfo, FENISH_LINE};
use crate::{exercise::Exercise, FENISH_LINE};
const STATE_FILE_NAME: &str = ".rustlings-state.txt";
const BAD_INDEX_ERR: &str = "The current exercise index is higher than the number of exercises";
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StateFile {
current_exercise_ind: usize,
progress: Vec<bool>,
}
impl StateFile {
fn read(exercises: &[Exercise]) -> Option<Self> {
let file_content = fs::read(".rustlings-state.json").ok()?;
let slf: Self = serde_json::de::from_slice(&file_content).ok()?;
if slf.progress.len() != exercises.len() || slf.current_exercise_ind >= exercises.len() {
return None;
}
Some(slf)
}
fn read_or_default(exercises: &[Exercise]) -> Self {
Self::read(exercises).unwrap_or_else(|| Self {
current_exercise_ind: 0,
progress: vec![false; exercises.len()],
})
}
fn write(&self) -> Result<()> {
let mut buf = Vec::with_capacity(1024);
serde_json::ser::to_writer(&mut buf, self).context("Failed to serialize the state")?;
fs::write(".rustlings-state.json", buf)
.context("Failed to write the state file `.rustlings-state.json`")?;
Ok(())
}
}
#[must_use]
pub enum ExercisesProgress {
AllDone,
Pending,
}
pub enum StateFileStatus {
Read,
NotRead,
}
pub struct AppState {
current_exercise_ind: usize,
exercises: Vec<Exercise>,
state_file: StateFile,
exercises: &'static [Exercise],
n_done: u16,
final_message: String,
file_buf: Vec<u8>,
current_exercise: &'static Exercise,
final_message: &'static str,
}
impl AppState {
fn update_from_file(&mut self) -> StateFileStatus {
self.file_buf.clear();
self.n_done = 0;
pub fn new(mut exercises: Vec<Exercise>, mut final_message: String) -> Self {
// Leaking especially for sending the exercises to the debounce event handler.
// Leaking is not a problem because the `AppState` instance lives until
// the end of the program.
exercises.shrink_to_fit();
let exercises = exercises.leak();
final_message.shrink_to_fit();
let final_message = final_message.leak();
if File::open(STATE_FILE_NAME)
.and_then(|mut file| file.read_to_end(&mut self.file_buf))
.is_err()
{
return StateFileStatus::NotRead;
}
let state_file = StateFile::read_or_default(exercises);
let n_done = state_file
.progress
.iter()
.fold(0, |acc, done| acc + u16::from(*done));
let current_exercise = &exercises[state_file.current_exercise_ind];
// See `Self::write` for more information about the file format.
let mut lines = self.file_buf.split(|c| *c == b'\n');
let Some(current_exercise_name) = lines.next() else {
return StateFileStatus::NotRead;
};
if current_exercise_name.is_empty() || lines.next().is_none() {
return StateFileStatus::NotRead;
}
let mut done_exercises = hashbrown::HashSet::with_capacity(self.exercises.len());
for done_exerise_name in lines {
if done_exerise_name.is_empty() {
break;
}
done_exercises.insert(done_exerise_name);
}
for (ind, exercise) in self.exercises.iter_mut().enumerate() {
if done_exercises.contains(exercise.name.as_bytes()) {
exercise.done = true;
self.n_done += 1;
}
if exercise.name.as_bytes() == current_exercise_name {
self.current_exercise_ind = ind;
}
}
StateFileStatus::Read
}
pub fn new(
exercise_infos: Vec<ExerciseInfo>,
final_message: String,
) -> (Self, StateFileStatus) {
let exercises = exercise_infos
.into_iter()
.map(|mut exercise_info| {
// Leaking to be able to borrow in the watch mode `Table`.
// Leaking is not a problem because the `AppState` instance lives until
// the end of the program.
let path = exercise_info.path().leak();
exercise_info.name.shrink_to_fit();
let name = exercise_info.name.leak();
let hint = exercise_info.hint.trim().to_owned();
Exercise {
name,
path,
mode: exercise_info.mode,
hint,
done: false,
}
})
.collect::<Vec<_>>();
let mut slf = Self {
current_exercise_ind: 0,
Self {
state_file,
exercises,
n_done: 0,
n_done,
current_exercise,
final_message,
file_buf: Vec::with_capacity(2048),
};
let state_file_status = slf.update_from_file();
(slf, state_file_status)
}
}
#[inline]
pub fn current_exercise_ind(&self) -> usize {
self.current_exercise_ind
self.state_file.current_exercise_ind
}
#[inline]
pub fn exercises(&self) -> &[Exercise] {
&self.exercises
pub fn progress(&self) -> &[bool] {
&self.state_file.progress
}
#[inline]
pub fn exercises(&self) -> &'static [Exercise] {
self.exercises
}
#[inline]
@ -134,8 +112,8 @@ impl AppState {
}
#[inline]
pub fn current_exercise(&self) -> &Exercise {
&self.exercises[self.current_exercise_ind]
pub fn current_exercise(&self) -> &'static Exercise {
self.current_exercise
}
pub fn set_current_exercise_ind(&mut self, ind: usize) -> Result<()> {
@ -143,61 +121,70 @@ impl AppState {
bail!(BAD_INDEX_ERR);
}
self.current_exercise_ind = ind;
self.state_file.current_exercise_ind = ind;
self.current_exercise = &self.exercises[ind];
self.write()
self.state_file.write()
}
pub fn set_current_exercise_by_name(&mut self, name: &str) -> Result<()> {
// O(N) is fine since this method is used only once until the program exits.
// Building a hashmap would have more overhead.
self.current_exercise_ind = self
let (ind, exercise) = self
.exercises
.iter()
.position(|exercise| exercise.name == name)
.enumerate()
.find(|(_, exercise)| exercise.name == name)
.with_context(|| format!("No exercise found for '{name}'!"))?;
self.write()
self.state_file.current_exercise_ind = ind;
self.current_exercise = exercise;
self.state_file.write()
}
pub fn set_pending(&mut self, ind: usize) -> Result<()> {
let exercise = self.exercises.get_mut(ind).context(BAD_INDEX_ERR)?;
let done = self
.state_file
.progress
.get_mut(ind)
.context(BAD_INDEX_ERR)?;
if exercise.done {
exercise.done = false;
if *done {
*done = false;
self.n_done -= 1;
self.write()?;
self.state_file.write()?;
}
Ok(())
}
fn next_pending_exercise_ind(&self) -> Option<usize> {
if self.current_exercise_ind == self.exercises.len() - 1 {
let current_ind = self.state_file.current_exercise_ind;
if current_ind == self.state_file.progress.len() - 1 {
// The last exercise is done.
// Search for exercises not done from the start.
return self.exercises[..self.current_exercise_ind]
return self.state_file.progress[..current_ind]
.iter()
.position(|exercise| !exercise.done);
.position(|done| !done);
}
// The done exercise isn't the last one.
// Search for a pending exercise after the current one and then from the start.
match self.exercises[self.current_exercise_ind + 1..]
match self.state_file.progress[current_ind + 1..]
.iter()
.position(|exercise| !exercise.done)
.position(|done| !done)
{
Some(ind) => Some(self.current_exercise_ind + 1 + ind),
None => self.exercises[..self.current_exercise_ind]
Some(ind) => Some(current_ind + 1 + ind),
None => self.state_file.progress[..current_ind]
.iter()
.position(|exercise| !exercise.done),
.position(|done| !done),
}
}
pub fn done_current_exercise(&mut self, writer: &mut StdoutLock) -> Result<ExercisesProgress> {
let exercise = &mut self.exercises[self.current_exercise_ind];
if !exercise.done {
exercise.done = true;
let done = &mut self.state_file.progress[self.state_file.current_exercise_ind];
if !*done {
*done = true;
self.n_done += 1;
}
@ -211,14 +198,15 @@ impl AppState {
if !exercise.run()?.status.success() {
writer.write_fmt(format_args!("{}\n\n", "FAILED".red()))?;
self.current_exercise_ind = exercise_ind;
self.state_file.current_exercise_ind = exercise_ind;
self.current_exercise = exercise;
// No check if the exercise is done before setting it to pending
// because no pending exercise was found.
self.exercises[exercise_ind].done = false;
self.state_file.progress[exercise_ind] = false;
self.n_done -= 1;
self.write()?;
self.state_file.write()?;
return Ok(ExercisesProgress::Pending);
}
@ -228,12 +216,8 @@ impl AppState {
writer.execute(Clear(ClearType::All))?;
writer.write_all(FENISH_LINE.as_bytes())?;
let final_message = self.final_message.trim();
if !final_message.is_empty() {
writer.write_all(self.final_message.as_bytes())?;
writer.write_all(b"\n")?;
}
writer.write_all(self.final_message.as_bytes())?;
writer.write_all(b"\n")?;
return Ok(ExercisesProgress::AllDone);
};
@ -242,32 +226,6 @@ impl AppState {
Ok(ExercisesProgress::Pending)
}
// Write the state file.
// The file's format is very simple:
// - The first line is the name of the current exercise. It must end with `\n` even if there
// are no done exercises.
// - The second line is an empty line.
// - All remaining lines are the names of done exercises.
fn write(&mut self) -> Result<()> {
self.file_buf.clear();
self.file_buf
.extend_from_slice(self.current_exercise().name.as_bytes());
self.file_buf.push(b'\n');
for exercise in &self.exercises {
if exercise.done {
self.file_buf.push(b'\n');
self.file_buf.extend_from_slice(exercise.name.as_bytes());
}
}
fs::write(STATE_FILE_NAME, &self.file_buf)
.with_context(|| format!("Failed to write the state file {STATE_FILE_NAME}"))?;
Ok(())
}
}
const RERUNNING_ALL_EXERCISES_MSG: &[u8] = b"

View file

@ -91,12 +91,7 @@ impl EmbeddedFiles {
Ok(())
}
pub fn write_exercise_to_disk<P>(&self, path: P, strategy: WriteStrategy) -> io::Result<()>
where
P: AsRef<Path>,
{
let path = path.as_ref();
pub fn write_exercise_to_disk(&self, path: &Path, strategy: WriteStrategy) -> io::Result<()> {
if let Some(file) = self
.exercises_dir
.files

View file

@ -1,47 +1,77 @@
use anyhow::{Context, Result};
use crossterm::style::{style, StyledContent, Stylize};
use serde::Deserialize;
use std::{
fmt::{self, Display, Formatter},
fs,
fmt::{self, Debug, Display, Formatter},
fs::{self},
path::PathBuf,
process::{Command, Output},
};
use crate::{
embedded::{WriteStrategy, EMBEDDED_FILES},
info_file::Mode,
};
use crate::embedded::{WriteStrategy, EMBEDDED_FILES};
pub struct TerminalFileLink<'a> {
path: &'a str,
// The mode of the exercise.
#[derive(Deserialize, Copy, Clone)]
#[serde(rename_all = "lowercase")]
pub enum Mode {
// The exercise should be compiled as a binary
Compile,
// The exercise should be compiled as a test harness
Test,
// The exercise should be linted with clippy
Clippy,
}
impl<'a> Display for TerminalFileLink<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
if let Ok(Some(canonical_path)) = fs::canonicalize(self.path)
.as_deref()
.map(|path| path.to_str())
{
write!(
f,
"\x1b]8;;file://{}\x1b\\{}\x1b]8;;\x1b\\",
canonical_path, self.path,
)
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InfoFile {
// TODO
pub welcome_message: Option<String>,
pub final_message: Option<String>,
pub exercises: Vec<Exercise>,
}
impl InfoFile {
pub fn parse() -> Result<Self> {
// Read a local `info.toml` if it exists.
// Mainly to let the tests work for now.
let slf: Self = if let Ok(file_content) = fs::read_to_string("info.toml") {
toml_edit::de::from_str(&file_content)
} else {
write!(f, "{}", self.path,)
toml_edit::de::from_str(include_str!("../info.toml"))
}
.context("Failed to parse `info.toml`")?;
if slf.exercises.is_empty() {
panic!("{NO_EXERCISES_ERR}");
}
Ok(slf)
}
}
// Deserialized from the `info.toml` file.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Exercise {
// Exercise's unique name
pub name: &'static str,
// Exercise's path
pub path: &'static str,
// Name of the exercise
pub name: String,
// The path to the file containing the exercise's source code
pub path: PathBuf,
// The mode of the exercise
pub mode: Mode,
// The hint text associated with the exercise
pub hint: String,
pub done: bool,
}
// The context information of a pending exercise.
#[derive(PartialEq, Eq, Debug)]
pub struct ContextLine {
// The source code line
pub line: String,
// The line number
pub number: usize,
// Whether this is important and should be highlighted
pub important: bool,
}
impl Exercise {
@ -60,7 +90,7 @@ impl Exercise {
.arg("always")
.arg("-q")
.arg("--bin")
.arg(self.name)
.arg(&self.name)
.args(args)
.output()
.context("Failed to run Cargo")
@ -68,7 +98,7 @@ impl Exercise {
pub fn run(&self) -> Result<Output> {
match self.mode {
Mode::Run => self.cargo_cmd("run", &[]),
Mode::Compile => self.cargo_cmd("run", &[]),
Mode::Test => self.cargo_cmd("test", &["--", "--nocapture", "--format", "pretty"]),
Mode::Clippy => self.cargo_cmd(
"clippy",
@ -79,19 +109,16 @@ impl Exercise {
pub fn reset(&self) -> Result<()> {
EMBEDDED_FILES
.write_exercise_to_disk(self.path, WriteStrategy::Overwrite)
.write_exercise_to_disk(&self.path, WriteStrategy::Overwrite)
.with_context(|| format!("Failed to reset the exercise {self}"))
}
pub fn terminal_link(&self) -> StyledContent<TerminalFileLink<'_>> {
style(TerminalFileLink { path: self.path })
.underlined()
.blue()
}
}
impl Display for Exercise {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.path.fmt(f)
Display::fmt(&self.path.display(), f)
}
}
const NO_EXERCISES_ERR: &str = "There are no exercises yet!
If you are developing third-party exercises, add at least one exercise before testing.";

View file

@ -1,79 +0,0 @@
use anyhow::{bail, Context, Error, Result};
use serde::Deserialize;
use std::fs;
// The mode of the exercise.
#[derive(Deserialize, Copy, Clone)]
#[serde(rename_all = "lowercase")]
pub enum Mode {
// The exercise should be compiled as a binary
Run,
// The exercise should be compiled as a test harness
Test,
// The exercise should be linted with clippy
Clippy,
}
// Deserialized from the `info.toml` file.
#[derive(Deserialize)]
pub struct ExerciseInfo {
// Name of the exercise
pub name: String,
// The exercise's directory inside the `exercises` directory
pub dir: Option<String>,
// The mode of the exercise
pub mode: Mode,
// The hint text associated with the exercise
pub hint: String,
}
impl ExerciseInfo {
pub fn path(&self) -> String {
if let Some(dir) = &self.dir {
format!("exercises/{dir}/{}.rs", self.name)
} else {
format!("exercises/{}.rs", self.name)
}
}
}
#[derive(Deserialize)]
pub struct InfoFile {
pub welcome_message: Option<String>,
pub final_message: Option<String>,
pub exercises: Vec<ExerciseInfo>,
}
impl InfoFile {
pub fn parse() -> Result<Self> {
// Read a local `info.toml` if it exists.
let slf: Self = match fs::read_to_string("info.toml") {
Ok(file_content) => toml_edit::de::from_str(&file_content)
.context("Failed to parse the `info.toml` file")?,
Err(e) => match e.kind() {
std::io::ErrorKind::NotFound => {
toml_edit::de::from_str(include_str!("../info.toml"))
.context("Failed to parse the embedded `info.toml` file")?
}
_ => return Err(Error::from(e).context("Failed to read the `info.toml` file")),
},
};
if slf.exercises.is_empty() {
bail!("{NO_EXERCISES_ERR}");
}
let mut names_set = hashbrown::HashSet::with_capacity(slf.exercises.len());
for exercise in &slf.exercises {
if !names_set.insert(exercise.name.as_str()) {
bail!("Exercise names must all be unique!")
}
}
drop(names_set);
Ok(slf)
}
}
const NO_EXERCISES_ERR: &str = "There are no exercises yet!
If you are developing third-party exercises, add at least one exercise before testing.";

View file

@ -6,21 +6,17 @@ use std::{
path::Path,
};
use crate::{embedded::EMBEDDED_FILES, info_file::ExerciseInfo};
use crate::{embedded::EMBEDDED_FILES, exercise::Exercise};
fn create_cargo_toml(exercise_infos: &[ExerciseInfo]) -> io::Result<()> {
fn create_cargo_toml(exercises: &[Exercise]) -> io::Result<()> {
let mut cargo_toml = Vec::with_capacity(1 << 13);
cargo_toml.extend_from_slice(b"bin = [\n");
for exercise_info in exercise_infos {
for exercise in exercises {
cargo_toml.extend_from_slice(b" { name = \"");
cargo_toml.extend_from_slice(exercise_info.name.as_bytes());
cargo_toml.extend_from_slice(b"\", path = \"exercises/");
if let Some(dir) = &exercise_info.dir {
cargo_toml.extend_from_slice(dir.as_bytes());
cargo_toml.push(b'/');
}
cargo_toml.extend_from_slice(exercise_info.name.as_bytes());
cargo_toml.extend_from_slice(b".rs\" },\n");
cargo_toml.extend_from_slice(exercise.name.as_bytes());
cargo_toml.extend_from_slice(b"\", path = \"");
cargo_toml.extend_from_slice(exercise.path.to_str().unwrap().as_bytes());
cargo_toml.extend_from_slice(b"\" },\n");
}
cargo_toml.extend_from_slice(
@ -58,7 +54,7 @@ fn create_vscode_dir() -> Result<()> {
Ok(())
}
pub fn init(exercise_infos: &[ExerciseInfo]) -> Result<()> {
pub fn init(exercises: &[Exercise]) -> Result<()> {
if Path::new("exercises").is_dir() && Path::new("Cargo.toml").is_file() {
bail!(PROBABLY_IN_RUSTLINGS_DIR_ERR);
}
@ -78,8 +74,7 @@ pub fn init(exercise_infos: &[ExerciseInfo]) -> Result<()> {
.init_exercises_dir()
.context("Failed to initialize the `rustlings/exercises` directory")?;
create_cargo_toml(exercise_infos)
.context("Failed to create the file `rustlings/Cargo.toml`")?;
create_cargo_toml(exercises).context("Failed to create the file `rustlings/Cargo.toml`")?;
create_gitignore().context("Failed to create the file `rustlings/.gitignore`")?;
@ -89,7 +84,7 @@ pub fn init(exercise_infos: &[ExerciseInfo]) -> Result<()> {
}
const GITIGNORE: &[u8] = b"/target
/.rustlings-state.txt
/.rustlings-state.json
";
const VS_CODE_EXTENSIONS_JSON: &[u8] = br#"{"recommendations":["rust-lang.rust-analyzer"]}"#;

View file

@ -5,7 +5,7 @@ use crossterm::{
ExecutableCommand,
};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::io;
use std::{fmt::Write, io};
mod state;
@ -72,7 +72,14 @@ pub fn list(app_state: &mut AppState) -> Result<()> {
ui_state.message.push_str(message);
}
KeyCode::Char('r') => {
ui_state = ui_state.with_reset_selected()?;
let Some(exercise) = ui_state.reset_selected()? else {
continue;
};
ui_state = ui_state.with_updated_rows();
ui_state
.message
.write_fmt(format_args!("The exercise {exercise} has been reset!"))?;
}
KeyCode::Char('c') => {
ui_state.selected_to_current_exercise()?;

View file

@ -6,9 +6,8 @@ use ratatui::{
widgets::{Block, Borders, HighlightSpacing, Paragraph, Row, Table, TableState},
Frame,
};
use std::fmt::Write;
use crate::{app_state::AppState, progress_bar::progress_bar_ratatui};
use crate::{app_state::AppState, exercise::Exercise, progress_bar::progress_bar_ratatui};
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Filter {
@ -35,9 +34,10 @@ impl<'a> UiState<'a> {
.app_state
.exercises()
.iter()
.zip(self.app_state.progress().iter().copied())
.enumerate()
.filter_map(|(ind, exercise)| {
let exercise_state = if exercise.done {
.filter_map(|(ind, (exercise, done))| {
let exercise_state = if done {
if self.filter == Filter::Pending {
return None;
}
@ -62,8 +62,8 @@ impl<'a> UiState<'a> {
Some(Row::new([
next,
exercise_state,
Span::raw(exercise.name),
Span::raw(exercise.path),
Span::raw(&exercise.name),
Span::raw(exercise.path.to_string_lossy()),
]))
});
@ -212,30 +212,29 @@ impl<'a> UiState<'a> {
Ok(())
}
pub fn with_reset_selected(mut self) -> Result<Self> {
pub fn reset_selected(&mut self) -> Result<Option<&'static Exercise>> {
let Some(selected) = self.table_state.selected() else {
return Ok(self);
return Ok(None);
};
let (ind, exercise) = self
.app_state
.exercises()
.iter()
.zip(self.app_state.progress())
.enumerate()
.filter_map(|(ind, exercise)| match self.filter {
Filter::Done => exercise.done.then_some((ind, exercise)),
Filter::Pending => (!exercise.done).then_some((ind, exercise)),
.filter_map(|(ind, (exercise, done))| match self.filter {
Filter::Done => done.then_some((ind, exercise)),
Filter::Pending => (!done).then_some((ind, exercise)),
Filter::None => Some((ind, exercise)),
})
.nth(selected)
.context("Invalid selection index")?;
exercise.reset()?;
self.message
.write_fmt(format_args!("The exercise {exercise} has been reset!"))?;
self.app_state.set_pending(ind)?;
exercise.reset()?;
Ok(self.with_updated_rows())
Ok(Some(exercise))
}
pub fn selected_to_current_exercise(&mut self) -> Result<()> {
@ -245,12 +244,12 @@ impl<'a> UiState<'a> {
let ind = self
.app_state
.exercises()
.progress()
.iter()
.enumerate()
.filter_map(|(ind, exercise)| match self.filter {
Filter::Done => exercise.done.then_some(ind),
Filter::Pending => (!exercise.done).then_some(ind),
.filter_map(|(ind, done)| match self.filter {
Filter::Done => done.then_some(ind),
Filter::Pending => (!done).then_some(ind),
Filter::None => Some(ind),
})
.nth(selected)

View file

@ -1,20 +1,10 @@
use anyhow::{Context, Result};
use app_state::StateFileStatus;
use clap::{Parser, Subcommand};
use crossterm::{
terminal::{Clear, ClearType},
ExecutableCommand,
};
use std::{
io::{self, BufRead, Write},
path::Path,
process::exit,
};
use std::{path::Path, process::exit};
mod app_state;
mod embedded;
mod exercise;
mod info_file;
mod init;
mod list;
mod progress_bar;
@ -23,7 +13,7 @@ mod watch;
use self::{
app_state::AppState,
info_file::InfoFile,
exercise::InfoFile,
init::init,
list::list,
run::run,
@ -36,10 +26,6 @@ use self::{
struct Args {
#[command(subcommand)]
command: Option<Subcommands>,
/// Manually run the current exercise using `r` or `run` in the watch mode.
/// Only use this if Rustlings fails to detect exercise file changes.
#[arg(long)]
manual_run: bool,
}
#[derive(Subcommand)]
@ -68,10 +54,12 @@ fn main() -> Result<()> {
which::which("cargo").context(CARGO_NOT_FOUND_ERR)?;
let info_file = InfoFile::parse()?;
let mut info_file = InfoFile::parse()?;
info_file.exercises.shrink_to_fit();
let exercises = info_file.exercises;
if matches!(args.command, Some(Subcommands::Init)) {
init(&info_file.exercises).context("Initialization failed")?;
init(&exercises).context("Initialization failed")?;
println!("{POST_INIT_MSG}");
return Ok(());
@ -80,56 +68,18 @@ fn main() -> Result<()> {
exit(1);
}
let (mut app_state, state_file_status) = AppState::new(
info_file.exercises,
info_file.final_message.unwrap_or_default(),
);
if let Some(welcome_message) = info_file.welcome_message {
match state_file_status {
StateFileStatus::NotRead => {
let mut stdout = io::stdout().lock();
stdout.execute(Clear(ClearType::All))?;
let welcome_message = welcome_message.trim();
write!(stdout, "{welcome_message}\n\nPress ENTER to continue ")?;
stdout.flush()?;
io::stdin().lock().read_until(b'\n', &mut Vec::new())?;
stdout.execute(Clear(ClearType::All))?;
}
StateFileStatus::Read => (),
}
}
let mut app_state = AppState::new(exercises, info_file.final_message.unwrap_or_default());
match args.command {
None => {
let notify_exercise_paths: Option<&'static [&'static str]> = if args.manual_run {
None
} else {
// For the the notify event handler thread.
// Leaking is not a problem because the slice lives until the end of the program.
Some(
app_state
.exercises()
.iter()
.map(|exercise| exercise.path)
.collect::<Vec<_>>()
.leak(),
)
};
loop {
match watch(&mut app_state, notify_exercise_paths)? {
WatchExit::Shutdown => break,
// It is much easier to exit the watch mode, launch the list mode and then restart
// the watch mode instead of trying to pause the watch threads and correct the
// watch state.
WatchExit::List => list(&mut app_state)?,
}
None => loop {
match watch(&mut app_state)? {
WatchExit::Shutdown => break,
// It is much easier to exit the watch mode, launch the list mode and then restart
// the watch mode instead of trying to pause the watch threads and correct the
// watch state.
WatchExit::List => list(&mut app_state)?,
}
}
},
// `Init` is handled above.
Some(Subcommands::Init) => (),
Some(Subcommands::Run { name }) => {
@ -140,10 +90,10 @@ fn main() -> Result<()> {
}
Some(Subcommands::Reset { name }) => {
app_state.set_current_exercise_by_name(&name)?;
app_state.set_pending(app_state.current_exercise_ind())?;
let exercise = app_state.current_exercise();
exercise.reset()?;
println!("The exercise {exercise} has been reset!");
app_state.set_pending(app_state.current_exercise_ind())?;
}
Some(Subcommands::Hint { name }) => {
app_state.set_current_exercise_by_name(&name)?;
@ -174,7 +124,7 @@ const POST_INIT_MSG: &str = "
Done initialization!
Run `cd rustlings` to go into the generated directory.
Then run `rustlings` to get started.";
Then run `rustlings` for further instructions on getting started.";
const FENISH_LINE: &str = "+----------------------------------------------------+
| You made it to the Fe-nish line! |

View file

@ -17,24 +17,18 @@ pub fn run(app_state: &mut AppState) -> Result<()> {
if !output.status.success() {
app_state.set_pending(app_state.current_exercise_ind())?;
bail!(
"Ran {} with errors",
app_state.current_exercise().terminal_link(),
);
bail!("Ran {exercise} with errors");
}
stdout.write_fmt(format_args!(
"{}{}\n",
"✓ Successfully ran ".green(),
exercise.path.green(),
exercise.path.to_string_lossy().green(),
))?;
match app_state.done_current_exercise(&mut stdout)? {
ExercisesProgress::AllDone => (),
ExercisesProgress::Pending => println!(
"Next exercise: {}",
app_state.current_exercise().terminal_link(),
),
ExercisesProgress::Pending => println!("Next exercise: {}", app_state.current_exercise()),
}
Ok(())

View file

@ -11,14 +11,14 @@ use std::{
time::Duration,
};
mod notify_event;
mod debounce_event;
mod state;
mod terminal_event;
use crate::app_state::{AppState, ExercisesProgress};
use self::{
notify_event::DebounceEventHandler,
debounce_event::DebounceEventHandler,
state::WatchState,
terminal_event::{terminal_event_handler, InputEvent},
};
@ -40,40 +40,24 @@ pub enum WatchExit {
List,
}
pub fn watch(
app_state: &mut AppState,
notify_exercise_paths: Option<&'static [&'static str]>,
) -> Result<WatchExit> {
pub fn watch(app_state: &mut AppState) -> Result<WatchExit> {
let (tx, rx) = channel();
let mut debouncer = new_debouncer(
Duration::from_secs(1),
DebounceEventHandler {
tx: tx.clone(),
exercises: app_state.exercises(),
},
)?;
debouncer
.watcher()
.watch(Path::new("exercises"), RecursiveMode::Recursive)?;
let mut manual_run = false;
// Prevent dropping the guard until the end of the function.
// Otherwise, the file watcher exits.
let _debouncer_guard = if let Some(exercise_paths) = notify_exercise_paths {
let mut debouncer = new_debouncer(
Duration::from_secs(1),
DebounceEventHandler {
tx: tx.clone(),
exercise_paths,
},
)
.inspect_err(|_| eprintln!("{NOTIFY_ERR}"))?;
debouncer
.watcher()
.watch(Path::new("exercises"), RecursiveMode::Recursive)
.inspect_err(|_| eprintln!("{NOTIFY_ERR}"))?;
Some(debouncer)
} else {
manual_run = true;
None
};
let mut watch_state = WatchState::new(app_state, manual_run);
let mut watch_state = WatchState::new(app_state);
watch_state.run_current_exercise()?;
thread::spawn(move || terminal_event_handler(tx, manual_run));
thread::spawn(move || terminal_event_handler(tx));
while let Ok(event) = rx.recv() {
match event {
@ -91,7 +75,6 @@ pub fn watch(
watch_state.into_writer().write_all(QUIT_MSG)?;
break;
}
WatchEvent::Input(InputEvent::Run) => watch_state.run_current_exercise()?,
WatchEvent::Input(InputEvent::Unrecognized(cmd)) => {
watch_state.handle_invalid_cmd(&cmd)?;
}
@ -102,11 +85,10 @@ pub fn watch(
watch_state.render()?;
}
WatchEvent::NotifyErr(e) => {
watch_state.into_writer().write_all(NOTIFY_ERR.as_bytes())?;
return Err(Error::from(e));
return Err(Error::from(e).context("Exercise file watcher failed"))
}
WatchEvent::TerminalEventErr(e) => {
return Err(Error::from(e).context("Terminal event listener failed"));
return Err(Error::from(e).context("Terminal event listener failed"))
}
}
}
@ -118,11 +100,3 @@ const QUIT_MSG: &[u8] = b"
We hope you're enjoying learning Rust!
If you want to continue working on the exercises at a later point, you can simply run `rustlings` again.
";
const NOTIFY_ERR: &str = "
The automatic detection of exercise file changes failed :(
Please try running `rustlings` again.
If you keep getting this error, run `rustlings --manual-run` to deactivate the file watcher.
You need to manually trigger running the current exercise using `r` or `run` then.
";

View file

@ -1,11 +1,13 @@
use notify_debouncer_mini::{DebounceEventResult, DebouncedEventKind};
use std::sync::mpsc::Sender;
use crate::exercise::Exercise;
use super::WatchEvent;
pub struct DebounceEventHandler {
pub tx: Sender<WatchEvent>,
pub exercise_paths: &'static [&'static str],
pub exercises: &'static [Exercise],
}
impl notify_debouncer_mini::DebounceEventHandler for DebounceEventHandler {
@ -21,9 +23,9 @@ impl notify_debouncer_mini::DebounceEventHandler for DebounceEventHandler {
return None;
}
self.exercise_paths
self.exercises
.iter()
.position(|path| event.path.ends_with(path))
.position(|exercise| event.path.ends_with(&exercise.path))
})
.min()
else {

View file

@ -18,11 +18,10 @@ pub struct WatchState<'a> {
stderr: Option<Vec<u8>>,
show_hint: bool,
show_done: bool,
manual_run: bool,
}
impl<'a> WatchState<'a> {
pub fn new(app_state: &'a mut AppState, manual_run: bool) -> Self {
pub fn new(app_state: &'a mut AppState) -> Self {
let writer = io::stdout().lock();
Self {
@ -32,7 +31,6 @@ impl<'a> WatchState<'a> {
stderr: None,
show_hint: false,
show_done: false,
manual_run,
}
}
@ -80,10 +78,6 @@ impl<'a> WatchState<'a> {
fn show_prompt(&mut self) -> io::Result<()> {
self.writer.write_all(b"\n")?;
if self.manual_run {
self.writer.write_fmt(format_args!("{}un/", 'r'.bold()))?;
}
if self.show_done {
self.writer.write_fmt(format_args!("{}ext/", 'n'.bold()))?;
}
@ -142,7 +136,11 @@ When you are done experimenting, enter `n` or `next` to go to the next exercise
)?;
self.writer.write_fmt(format_args!(
"{progress_bar}Current exercise: {}\n",
self.app_state.current_exercise().terminal_link(),
self.app_state
.current_exercise()
.path
.to_string_lossy()
.bold(),
))?;
self.show_prompt()?;

View file

@ -4,7 +4,6 @@ use std::sync::mpsc::Sender;
use super::WatchEvent;
pub enum InputEvent {
Run,
Next,
Hint,
List,
@ -12,7 +11,7 @@ pub enum InputEvent {
Unrecognized(String),
}
pub fn terminal_event_handler(tx: Sender<WatchEvent>, manual_run: bool) {
pub fn terminal_event_handler(tx: Sender<WatchEvent>) {
let mut input = String::with_capacity(8);
let last_input_event = loop {
@ -44,7 +43,6 @@ pub fn terminal_event_handler(tx: Sender<WatchEvent>, manual_run: bool) {
"h" | "hint" => InputEvent::Hint,
"l" | "list" => break InputEvent::List,
"q" | "quit" => break InputEvent::Quit,
"r" | "run" if manual_run => InputEvent::Run,
_ => InputEvent::Unrecognized(input.clone()),
};

View file

@ -5,39 +5,34 @@ use serde::Deserialize;
use std::fs;
#[derive(Deserialize)]
struct ExerciseInfo {
struct Exercise {
name: String,
dir: Option<String>,
path: String,
}
#[derive(Deserialize)]
struct InfoFile {
exercises: Vec<ExerciseInfo>,
struct InfoToml {
exercises: Vec<Exercise>,
}
#[test]
fn dev_cargo_bins() {
let cargo_toml = fs::read_to_string("dev/Cargo.toml").unwrap();
let content = fs::read_to_string("dev/Cargo.toml").unwrap();
let exercise_infos =
toml_edit::de::from_str::<InfoFile>(&fs::read_to_string("info.toml").unwrap())
.unwrap()
.exercises;
let exercises = toml_edit::de::from_str::<InfoToml>(&fs::read_to_string("info.toml").unwrap())
.unwrap()
.exercises;
let mut start_ind = 0;
for exercise_info in exercise_infos {
let name_start = start_ind + cargo_toml[start_ind..].find('"').unwrap() + 1;
let name_end = name_start + cargo_toml[name_start..].find('"').unwrap();
assert_eq!(exercise_info.name, &cargo_toml[name_start..name_end]);
for exercise in exercises {
let name_start = start_ind + content[start_ind..].find('"').unwrap() + 1;
let name_end = name_start + content[name_start..].find('"').unwrap();
assert_eq!(exercise.name, &content[name_start..name_end]);
let path_start = name_end + cargo_toml[name_end + 1..].find('"').unwrap() + 2;
let path_end = path_start + cargo_toml[path_start..].find('"').unwrap();
let expected_path = if let Some(dir) = exercise_info.dir {
format!("../exercises/{dir}/{}.rs", exercise_info.name)
} else {
format!("../exercises/{}.rs", exercise_info.name)
};
assert_eq!(expected_path, &cargo_toml[path_start..path_end]);
// +3 to skip `../` at the begeinning of the path.
let path_start = name_end + content[name_end + 1..].find('"').unwrap() + 5;
let path_end = path_start + content[path_start..].find('"').unwrap();
assert_eq!(exercise.path, &content[path_start..path_end]);
start_ind = path_end + 1;
}

View file

@ -1,9 +1,11 @@
[[exercises]]
name = "compFailure"
mode = "run"
path = "exercises/compFailure.rs"
mode = "compile"
hint = ""
[[exercises]]
name = "testFailure"
path = "exercises/testFailure.rs"
mode = "test"
hint = "Hello!"

View file

@ -1,14 +1,17 @@
[[exercises]]
name = "pending_exercise"
mode = "run"
path = "exercises/pending_exercise.rs"
mode = "compile"
hint = """"""
[[exercises]]
name = "pending_test_exercise"
path = "exercises/pending_test_exercise.rs"
mode = "test"
hint = """"""
[[exercises]]
name = "finished_exercise"
mode = "run"
path = "exercises/finished_exercise.rs"
mode = "compile"
hint = """"""

View file

@ -1,9 +1,11 @@
[[exercises]]
name = "compSuccess"
mode = "run"
path = "exercises/compSuccess.rs"
mode = "compile"
hint = """"""
[[exercises]]
name = "testSuccess"
path = "exercises/testSuccess.rs"
mode = "test"
hint = """"""