Compare commits

..

10 commits

Author SHA1 Message Date
mo8it 08ac11ff22 Add --require-solutions option to dev check 2024-06-02 00:11:41 +02:00
mo8it 6ae4a979f4 Check for unexpected files in the solutions dir 2024-06-02 00:03:48 +02:00
mo8it a3ada0eee8 Print the exercise solution on check 2024-06-01 21:51:45 +02:00
mo8it 50530fa3cf Don't try to check a solution that doesn't exist 2024-06-01 21:50:11 +02:00
mo8it 611f9d8722 Check that all solutions run successfully 2024-06-01 21:48:15 +02:00
mo8it 8e9c99ae5b Change condition order 2024-06-01 15:10:43 +02:00
mo8it c324ea10df Update deps 2024-06-01 15:10:17 +02:00
mo8it 1984a8d38e Update Cargo.toml with the solution bins 2024-06-01 15:01:27 +02:00
mo8it 84a818dbda Update the bins buffer capacity 2024-06-01 15:01:18 +02:00
mo8it beb7b24e8e Add solutions to bins 2024-05-25 18:19:30 +02:00
15 changed files with 393 additions and 124 deletions

16
Cargo.lock generated
View file

@ -565,9 +565,9 @@ dependencies = [
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.83" version = "1.0.84"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b33eb56c327dec362a9e55b3ad14f9d2f0904fb5a5b03b513ab5465399e9f43" checksum = "ec96c6a92621310b51366f1e28d05ef11489516e93be030060e5fc12024a49d6"
dependencies = [ dependencies = [
"unicode-ident", "unicode-ident",
] ]
@ -705,18 +705,18 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.202" version = "1.0.203"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "226b61a0d411b2ba5ff6d7f73a476ac4f8bb900373459cd00fab8512828ba395" checksum = "7253ab4de971e72fb7be983802300c30b5a7f0c2e56fab8abfc6a214307c0094"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.202" version = "1.0.203"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6048858004bcff69094cd972ed40a32500f153bd3be9f716b2eed2e8217c4838" checksum = "500cbc0ebeb6f46627f50f3f5811ccf6bf00643be300b4c3eabc0ef55dc5b5ba"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -1099,9 +1099,9 @@ checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"
[[package]] [[package]]
name = "winnow" name = "winnow"
version = "0.6.8" version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3c52e9c97a68071b23e836c9380edae937f17b9c4667bd021973efc689f618d" checksum = "86c949fede1d13936a99f14fafd3e76fd642b556dd2ce96287fbe2e0151bfac6"
dependencies = [ dependencies = [
"memchr", "memchr",
] ]

View file

@ -20,7 +20,7 @@ license = "MIT"
edition = "2021" edition = "2021"
[workspace.dependencies] [workspace.dependencies]
serde = { version = "1.0.202", features = ["derive"] } serde = { version = "1.0.203", features = ["derive"] }
toml_edit = { version = "0.22.13", default-features = false, features = ["parse", "serde"] } toml_edit = { version = "0.22.13", default-features = false, features = ["parse", "serde"] }
[package] [package]

View file

@ -1,101 +1,197 @@
# Don't edit the `bin` list manually! It is updated by `cargo run -- dev update`. This comment line will be stripped in `rustlings init`. # Don't edit the `bin` list manually! It is updated by `cargo run -- dev update`. This comment line will be stripped in `rustlings init`.
bin = [ bin = [
{ name = "intro1", path = "../exercises/00_intro/intro1.rs" }, { name = "intro1", path = "../exercises/00_intro/intro1.rs" },
{ name = "intro1_sol", path = "../solutions/00_intro/intro1.rs" },
{ name = "intro2", path = "../exercises/00_intro/intro2.rs" }, { name = "intro2", path = "../exercises/00_intro/intro2.rs" },
{ name = "intro2_sol", path = "../solutions/00_intro/intro2.rs" },
{ name = "variables1", path = "../exercises/01_variables/variables1.rs" }, { name = "variables1", path = "../exercises/01_variables/variables1.rs" },
{ name = "variables1_sol", path = "../solutions/01_variables/variables1.rs" },
{ name = "variables2", path = "../exercises/01_variables/variables2.rs" }, { name = "variables2", path = "../exercises/01_variables/variables2.rs" },
{ name = "variables2_sol", path = "../solutions/01_variables/variables2.rs" },
{ name = "variables3", path = "../exercises/01_variables/variables3.rs" }, { name = "variables3", path = "../exercises/01_variables/variables3.rs" },
{ name = "variables3_sol", path = "../solutions/01_variables/variables3.rs" },
{ name = "variables4", path = "../exercises/01_variables/variables4.rs" }, { name = "variables4", path = "../exercises/01_variables/variables4.rs" },
{ name = "variables4_sol", path = "../solutions/01_variables/variables4.rs" },
{ name = "variables5", path = "../exercises/01_variables/variables5.rs" }, { name = "variables5", path = "../exercises/01_variables/variables5.rs" },
{ name = "variables5_sol", path = "../solutions/01_variables/variables5.rs" },
{ name = "variables6", path = "../exercises/01_variables/variables6.rs" }, { name = "variables6", path = "../exercises/01_variables/variables6.rs" },
{ name = "variables6_sol", path = "../solutions/01_variables/variables6.rs" },
{ name = "functions1", path = "../exercises/02_functions/functions1.rs" }, { name = "functions1", path = "../exercises/02_functions/functions1.rs" },
{ name = "functions1_sol", path = "../solutions/02_functions/functions1.rs" },
{ name = "functions2", path = "../exercises/02_functions/functions2.rs" }, { name = "functions2", path = "../exercises/02_functions/functions2.rs" },
{ name = "functions2_sol", path = "../solutions/02_functions/functions2.rs" },
{ name = "functions3", path = "../exercises/02_functions/functions3.rs" }, { name = "functions3", path = "../exercises/02_functions/functions3.rs" },
{ name = "functions3_sol", path = "../solutions/02_functions/functions3.rs" },
{ name = "functions4", path = "../exercises/02_functions/functions4.rs" }, { name = "functions4", path = "../exercises/02_functions/functions4.rs" },
{ name = "functions4_sol", path = "../solutions/02_functions/functions4.rs" },
{ name = "functions5", path = "../exercises/02_functions/functions5.rs" }, { name = "functions5", path = "../exercises/02_functions/functions5.rs" },
{ name = "functions5_sol", path = "../solutions/02_functions/functions5.rs" },
{ name = "if1", path = "../exercises/03_if/if1.rs" }, { name = "if1", path = "../exercises/03_if/if1.rs" },
{ name = "if1_sol", path = "../solutions/03_if/if1.rs" },
{ name = "if2", path = "../exercises/03_if/if2.rs" }, { name = "if2", path = "../exercises/03_if/if2.rs" },
{ name = "if2_sol", path = "../solutions/03_if/if2.rs" },
{ name = "if3", path = "../exercises/03_if/if3.rs" }, { name = "if3", path = "../exercises/03_if/if3.rs" },
{ name = "if3_sol", path = "../solutions/03_if/if3.rs" },
{ name = "quiz1", path = "../exercises/quizzes/quiz1.rs" }, { name = "quiz1", path = "../exercises/quizzes/quiz1.rs" },
{ name = "quiz1_sol", path = "../solutions/quizzes/quiz1.rs" },
{ name = "primitive_types1", path = "../exercises/04_primitive_types/primitive_types1.rs" }, { name = "primitive_types1", path = "../exercises/04_primitive_types/primitive_types1.rs" },
{ name = "primitive_types1_sol", path = "../solutions/04_primitive_types/primitive_types1.rs" },
{ name = "primitive_types2", path = "../exercises/04_primitive_types/primitive_types2.rs" }, { name = "primitive_types2", path = "../exercises/04_primitive_types/primitive_types2.rs" },
{ name = "primitive_types2_sol", path = "../solutions/04_primitive_types/primitive_types2.rs" },
{ name = "primitive_types3", path = "../exercises/04_primitive_types/primitive_types3.rs" }, { name = "primitive_types3", path = "../exercises/04_primitive_types/primitive_types3.rs" },
{ name = "primitive_types3_sol", path = "../solutions/04_primitive_types/primitive_types3.rs" },
{ name = "primitive_types4", path = "../exercises/04_primitive_types/primitive_types4.rs" }, { name = "primitive_types4", path = "../exercises/04_primitive_types/primitive_types4.rs" },
{ name = "primitive_types4_sol", path = "../solutions/04_primitive_types/primitive_types4.rs" },
{ name = "primitive_types5", path = "../exercises/04_primitive_types/primitive_types5.rs" }, { name = "primitive_types5", path = "../exercises/04_primitive_types/primitive_types5.rs" },
{ name = "primitive_types5_sol", path = "../solutions/04_primitive_types/primitive_types5.rs" },
{ name = "primitive_types6", path = "../exercises/04_primitive_types/primitive_types6.rs" }, { name = "primitive_types6", path = "../exercises/04_primitive_types/primitive_types6.rs" },
{ name = "primitive_types6_sol", path = "../solutions/04_primitive_types/primitive_types6.rs" },
{ name = "vecs1", path = "../exercises/05_vecs/vecs1.rs" }, { name = "vecs1", path = "../exercises/05_vecs/vecs1.rs" },
{ name = "vecs1_sol", path = "../solutions/05_vecs/vecs1.rs" },
{ name = "vecs2", path = "../exercises/05_vecs/vecs2.rs" }, { name = "vecs2", path = "../exercises/05_vecs/vecs2.rs" },
{ name = "vecs2_sol", path = "../solutions/05_vecs/vecs2.rs" },
{ name = "move_semantics1", path = "../exercises/06_move_semantics/move_semantics1.rs" }, { name = "move_semantics1", path = "../exercises/06_move_semantics/move_semantics1.rs" },
{ name = "move_semantics1_sol", path = "../solutions/06_move_semantics/move_semantics1.rs" },
{ name = "move_semantics2", path = "../exercises/06_move_semantics/move_semantics2.rs" }, { name = "move_semantics2", path = "../exercises/06_move_semantics/move_semantics2.rs" },
{ name = "move_semantics2_sol", path = "../solutions/06_move_semantics/move_semantics2.rs" },
{ name = "move_semantics3", path = "../exercises/06_move_semantics/move_semantics3.rs" }, { name = "move_semantics3", path = "../exercises/06_move_semantics/move_semantics3.rs" },
{ name = "move_semantics3_sol", path = "../solutions/06_move_semantics/move_semantics3.rs" },
{ name = "move_semantics4", path = "../exercises/06_move_semantics/move_semantics4.rs" }, { name = "move_semantics4", path = "../exercises/06_move_semantics/move_semantics4.rs" },
{ name = "move_semantics4_sol", path = "../solutions/06_move_semantics/move_semantics4.rs" },
{ name = "move_semantics5", path = "../exercises/06_move_semantics/move_semantics5.rs" }, { name = "move_semantics5", path = "../exercises/06_move_semantics/move_semantics5.rs" },
{ name = "move_semantics5_sol", path = "../solutions/06_move_semantics/move_semantics5.rs" },
{ name = "move_semantics6", path = "../exercises/06_move_semantics/move_semantics6.rs" }, { name = "move_semantics6", path = "../exercises/06_move_semantics/move_semantics6.rs" },
{ name = "move_semantics6_sol", path = "../solutions/06_move_semantics/move_semantics6.rs" },
{ name = "structs1", path = "../exercises/07_structs/structs1.rs" }, { name = "structs1", path = "../exercises/07_structs/structs1.rs" },
{ name = "structs1_sol", path = "../solutions/07_structs/structs1.rs" },
{ name = "structs2", path = "../exercises/07_structs/structs2.rs" }, { name = "structs2", path = "../exercises/07_structs/structs2.rs" },
{ name = "structs2_sol", path = "../solutions/07_structs/structs2.rs" },
{ name = "structs3", path = "../exercises/07_structs/structs3.rs" }, { name = "structs3", path = "../exercises/07_structs/structs3.rs" },
{ name = "structs3_sol", path = "../solutions/07_structs/structs3.rs" },
{ name = "enums1", path = "../exercises/08_enums/enums1.rs" }, { name = "enums1", path = "../exercises/08_enums/enums1.rs" },
{ name = "enums1_sol", path = "../solutions/08_enums/enums1.rs" },
{ name = "enums2", path = "../exercises/08_enums/enums2.rs" }, { name = "enums2", path = "../exercises/08_enums/enums2.rs" },
{ name = "enums2_sol", path = "../solutions/08_enums/enums2.rs" },
{ name = "enums3", path = "../exercises/08_enums/enums3.rs" }, { name = "enums3", path = "../exercises/08_enums/enums3.rs" },
{ name = "enums3_sol", path = "../solutions/08_enums/enums3.rs" },
{ name = "strings1", path = "../exercises/09_strings/strings1.rs" }, { name = "strings1", path = "../exercises/09_strings/strings1.rs" },
{ name = "strings1_sol", path = "../solutions/09_strings/strings1.rs" },
{ name = "strings2", path = "../exercises/09_strings/strings2.rs" }, { name = "strings2", path = "../exercises/09_strings/strings2.rs" },
{ name = "strings2_sol", path = "../solutions/09_strings/strings2.rs" },
{ name = "strings3", path = "../exercises/09_strings/strings3.rs" }, { name = "strings3", path = "../exercises/09_strings/strings3.rs" },
{ name = "strings3_sol", path = "../solutions/09_strings/strings3.rs" },
{ name = "strings4", path = "../exercises/09_strings/strings4.rs" }, { name = "strings4", path = "../exercises/09_strings/strings4.rs" },
{ name = "strings4_sol", path = "../solutions/09_strings/strings4.rs" },
{ name = "modules1", path = "../exercises/10_modules/modules1.rs" }, { name = "modules1", path = "../exercises/10_modules/modules1.rs" },
{ name = "modules1_sol", path = "../solutions/10_modules/modules1.rs" },
{ name = "modules2", path = "../exercises/10_modules/modules2.rs" }, { name = "modules2", path = "../exercises/10_modules/modules2.rs" },
{ name = "modules2_sol", path = "../solutions/10_modules/modules2.rs" },
{ name = "modules3", path = "../exercises/10_modules/modules3.rs" }, { name = "modules3", path = "../exercises/10_modules/modules3.rs" },
{ name = "modules3_sol", path = "../solutions/10_modules/modules3.rs" },
{ name = "hashmaps1", path = "../exercises/11_hashmaps/hashmaps1.rs" }, { name = "hashmaps1", path = "../exercises/11_hashmaps/hashmaps1.rs" },
{ name = "hashmaps1_sol", path = "../solutions/11_hashmaps/hashmaps1.rs" },
{ name = "hashmaps2", path = "../exercises/11_hashmaps/hashmaps2.rs" }, { name = "hashmaps2", path = "../exercises/11_hashmaps/hashmaps2.rs" },
{ name = "hashmaps2_sol", path = "../solutions/11_hashmaps/hashmaps2.rs" },
{ name = "hashmaps3", path = "../exercises/11_hashmaps/hashmaps3.rs" }, { name = "hashmaps3", path = "../exercises/11_hashmaps/hashmaps3.rs" },
{ name = "hashmaps3_sol", path = "../solutions/11_hashmaps/hashmaps3.rs" },
{ name = "quiz2", path = "../exercises/quizzes/quiz2.rs" }, { name = "quiz2", path = "../exercises/quizzes/quiz2.rs" },
{ name = "quiz2_sol", path = "../solutions/quizzes/quiz2.rs" },
{ name = "options1", path = "../exercises/12_options/options1.rs" }, { name = "options1", path = "../exercises/12_options/options1.rs" },
{ name = "options1_sol", path = "../solutions/12_options/options1.rs" },
{ name = "options2", path = "../exercises/12_options/options2.rs" }, { name = "options2", path = "../exercises/12_options/options2.rs" },
{ name = "options2_sol", path = "../solutions/12_options/options2.rs" },
{ name = "options3", path = "../exercises/12_options/options3.rs" }, { name = "options3", path = "../exercises/12_options/options3.rs" },
{ name = "options3_sol", path = "../solutions/12_options/options3.rs" },
{ name = "errors1", path = "../exercises/13_error_handling/errors1.rs" }, { name = "errors1", path = "../exercises/13_error_handling/errors1.rs" },
{ name = "errors1_sol", path = "../solutions/13_error_handling/errors1.rs" },
{ name = "errors2", path = "../exercises/13_error_handling/errors2.rs" }, { name = "errors2", path = "../exercises/13_error_handling/errors2.rs" },
{ name = "errors2_sol", path = "../solutions/13_error_handling/errors2.rs" },
{ name = "errors3", path = "../exercises/13_error_handling/errors3.rs" }, { name = "errors3", path = "../exercises/13_error_handling/errors3.rs" },
{ name = "errors3_sol", path = "../solutions/13_error_handling/errors3.rs" },
{ name = "errors4", path = "../exercises/13_error_handling/errors4.rs" }, { name = "errors4", path = "../exercises/13_error_handling/errors4.rs" },
{ name = "errors4_sol", path = "../solutions/13_error_handling/errors4.rs" },
{ name = "errors5", path = "../exercises/13_error_handling/errors5.rs" }, { name = "errors5", path = "../exercises/13_error_handling/errors5.rs" },
{ name = "errors5_sol", path = "../solutions/13_error_handling/errors5.rs" },
{ name = "errors6", path = "../exercises/13_error_handling/errors6.rs" }, { name = "errors6", path = "../exercises/13_error_handling/errors6.rs" },
{ name = "errors6_sol", path = "../solutions/13_error_handling/errors6.rs" },
{ name = "generics1", path = "../exercises/14_generics/generics1.rs" }, { name = "generics1", path = "../exercises/14_generics/generics1.rs" },
{ name = "generics1_sol", path = "../solutions/14_generics/generics1.rs" },
{ name = "generics2", path = "../exercises/14_generics/generics2.rs" }, { name = "generics2", path = "../exercises/14_generics/generics2.rs" },
{ name = "generics2_sol", path = "../solutions/14_generics/generics2.rs" },
{ name = "traits1", path = "../exercises/15_traits/traits1.rs" }, { name = "traits1", path = "../exercises/15_traits/traits1.rs" },
{ name = "traits1_sol", path = "../solutions/15_traits/traits1.rs" },
{ name = "traits2", path = "../exercises/15_traits/traits2.rs" }, { name = "traits2", path = "../exercises/15_traits/traits2.rs" },
{ name = "traits2_sol", path = "../solutions/15_traits/traits2.rs" },
{ name = "traits3", path = "../exercises/15_traits/traits3.rs" }, { name = "traits3", path = "../exercises/15_traits/traits3.rs" },
{ name = "traits3_sol", path = "../solutions/15_traits/traits3.rs" },
{ name = "traits4", path = "../exercises/15_traits/traits4.rs" }, { name = "traits4", path = "../exercises/15_traits/traits4.rs" },
{ name = "traits4_sol", path = "../solutions/15_traits/traits4.rs" },
{ name = "traits5", path = "../exercises/15_traits/traits5.rs" }, { name = "traits5", path = "../exercises/15_traits/traits5.rs" },
{ name = "traits5_sol", path = "../solutions/15_traits/traits5.rs" },
{ name = "quiz3", path = "../exercises/quizzes/quiz3.rs" }, { name = "quiz3", path = "../exercises/quizzes/quiz3.rs" },
{ name = "quiz3_sol", path = "../solutions/quizzes/quiz3.rs" },
{ name = "lifetimes1", path = "../exercises/16_lifetimes/lifetimes1.rs" }, { name = "lifetimes1", path = "../exercises/16_lifetimes/lifetimes1.rs" },
{ name = "lifetimes1_sol", path = "../solutions/16_lifetimes/lifetimes1.rs" },
{ name = "lifetimes2", path = "../exercises/16_lifetimes/lifetimes2.rs" }, { name = "lifetimes2", path = "../exercises/16_lifetimes/lifetimes2.rs" },
{ name = "lifetimes2_sol", path = "../solutions/16_lifetimes/lifetimes2.rs" },
{ name = "lifetimes3", path = "../exercises/16_lifetimes/lifetimes3.rs" }, { name = "lifetimes3", path = "../exercises/16_lifetimes/lifetimes3.rs" },
{ name = "lifetimes3_sol", path = "../solutions/16_lifetimes/lifetimes3.rs" },
{ name = "tests1", path = "../exercises/17_tests/tests1.rs" }, { name = "tests1", path = "../exercises/17_tests/tests1.rs" },
{ name = "tests1_sol", path = "../solutions/17_tests/tests1.rs" },
{ name = "tests2", path = "../exercises/17_tests/tests2.rs" }, { name = "tests2", path = "../exercises/17_tests/tests2.rs" },
{ name = "tests2_sol", path = "../solutions/17_tests/tests2.rs" },
{ name = "tests3", path = "../exercises/17_tests/tests3.rs" }, { name = "tests3", path = "../exercises/17_tests/tests3.rs" },
{ name = "tests3_sol", path = "../solutions/17_tests/tests3.rs" },
{ name = "tests4", path = "../exercises/17_tests/tests4.rs" }, { name = "tests4", path = "../exercises/17_tests/tests4.rs" },
{ name = "tests4_sol", path = "../solutions/17_tests/tests4.rs" },
{ name = "iterators1", path = "../exercises/18_iterators/iterators1.rs" }, { name = "iterators1", path = "../exercises/18_iterators/iterators1.rs" },
{ name = "iterators1_sol", path = "../solutions/18_iterators/iterators1.rs" },
{ name = "iterators2", path = "../exercises/18_iterators/iterators2.rs" }, { name = "iterators2", path = "../exercises/18_iterators/iterators2.rs" },
{ name = "iterators2_sol", path = "../solutions/18_iterators/iterators2.rs" },
{ name = "iterators3", path = "../exercises/18_iterators/iterators3.rs" }, { name = "iterators3", path = "../exercises/18_iterators/iterators3.rs" },
{ name = "iterators3_sol", path = "../solutions/18_iterators/iterators3.rs" },
{ name = "iterators4", path = "../exercises/18_iterators/iterators4.rs" }, { name = "iterators4", path = "../exercises/18_iterators/iterators4.rs" },
{ name = "iterators4_sol", path = "../solutions/18_iterators/iterators4.rs" },
{ name = "iterators5", path = "../exercises/18_iterators/iterators5.rs" }, { name = "iterators5", path = "../exercises/18_iterators/iterators5.rs" },
{ name = "iterators5_sol", path = "../solutions/18_iterators/iterators5.rs" },
{ name = "box1", path = "../exercises/19_smart_pointers/box1.rs" }, { name = "box1", path = "../exercises/19_smart_pointers/box1.rs" },
{ name = "box1_sol", path = "../solutions/19_smart_pointers/box1.rs" },
{ name = "rc1", path = "../exercises/19_smart_pointers/rc1.rs" }, { name = "rc1", path = "../exercises/19_smart_pointers/rc1.rs" },
{ name = "rc1_sol", path = "../solutions/19_smart_pointers/rc1.rs" },
{ name = "arc1", path = "../exercises/19_smart_pointers/arc1.rs" }, { name = "arc1", path = "../exercises/19_smart_pointers/arc1.rs" },
{ name = "arc1_sol", path = "../solutions/19_smart_pointers/arc1.rs" },
{ name = "cow1", path = "../exercises/19_smart_pointers/cow1.rs" }, { name = "cow1", path = "../exercises/19_smart_pointers/cow1.rs" },
{ name = "cow1_sol", path = "../solutions/19_smart_pointers/cow1.rs" },
{ name = "threads1", path = "../exercises/20_threads/threads1.rs" }, { name = "threads1", path = "../exercises/20_threads/threads1.rs" },
{ name = "threads1_sol", path = "../solutions/20_threads/threads1.rs" },
{ name = "threads2", path = "../exercises/20_threads/threads2.rs" }, { name = "threads2", path = "../exercises/20_threads/threads2.rs" },
{ name = "threads2_sol", path = "../solutions/20_threads/threads2.rs" },
{ name = "threads3", path = "../exercises/20_threads/threads3.rs" }, { name = "threads3", path = "../exercises/20_threads/threads3.rs" },
{ name = "threads3_sol", path = "../solutions/20_threads/threads3.rs" },
{ name = "macros1", path = "../exercises/21_macros/macros1.rs" }, { name = "macros1", path = "../exercises/21_macros/macros1.rs" },
{ name = "macros1_sol", path = "../solutions/21_macros/macros1.rs" },
{ name = "macros2", path = "../exercises/21_macros/macros2.rs" }, { name = "macros2", path = "../exercises/21_macros/macros2.rs" },
{ name = "macros2_sol", path = "../solutions/21_macros/macros2.rs" },
{ name = "macros3", path = "../exercises/21_macros/macros3.rs" }, { name = "macros3", path = "../exercises/21_macros/macros3.rs" },
{ name = "macros3_sol", path = "../solutions/21_macros/macros3.rs" },
{ name = "macros4", path = "../exercises/21_macros/macros4.rs" }, { name = "macros4", path = "../exercises/21_macros/macros4.rs" },
{ name = "macros4_sol", path = "../solutions/21_macros/macros4.rs" },
{ name = "clippy1", path = "../exercises/22_clippy/clippy1.rs" }, { name = "clippy1", path = "../exercises/22_clippy/clippy1.rs" },
{ name = "clippy1_sol", path = "../solutions/22_clippy/clippy1.rs" },
{ name = "clippy2", path = "../exercises/22_clippy/clippy2.rs" }, { name = "clippy2", path = "../exercises/22_clippy/clippy2.rs" },
{ name = "clippy2_sol", path = "../solutions/22_clippy/clippy2.rs" },
{ name = "clippy3", path = "../exercises/22_clippy/clippy3.rs" }, { name = "clippy3", path = "../exercises/22_clippy/clippy3.rs" },
{ name = "clippy3_sol", path = "../solutions/22_clippy/clippy3.rs" },
{ name = "using_as", path = "../exercises/23_conversions/using_as.rs" }, { name = "using_as", path = "../exercises/23_conversions/using_as.rs" },
{ name = "using_as_sol", path = "../solutions/23_conversions/using_as.rs" },
{ name = "from_into", path = "../exercises/23_conversions/from_into.rs" }, { name = "from_into", path = "../exercises/23_conversions/from_into.rs" },
{ name = "from_into_sol", path = "../solutions/23_conversions/from_into.rs" },
{ name = "from_str", path = "../exercises/23_conversions/from_str.rs" }, { name = "from_str", path = "../exercises/23_conversions/from_str.rs" },
{ name = "from_str_sol", path = "../solutions/23_conversions/from_str.rs" },
{ name = "try_from_into", path = "../exercises/23_conversions/try_from_into.rs" }, { name = "try_from_into", path = "../exercises/23_conversions/try_from_into.rs" },
{ name = "try_from_into_sol", path = "../solutions/23_conversions/try_from_into.rs" },
{ name = "as_ref_mut", path = "../exercises/23_conversions/as_ref_mut.rs" }, { name = "as_ref_mut", path = "../exercises/23_conversions/as_ref_mut.rs" },
{ name = "as_ref_mut_sol", path = "../solutions/23_conversions/as_ref_mut.rs" },
] ]
[package] [package]

View file

@ -1,2 +1,5 @@
// The exercise `intro1` only requires entering `n` in the terminal to go to the next exercise. fn main() {
// It is just an introduction to how Rustlings works. // Congratulations, you finished the first exercise 🎉
// As an introduction to Rustlings, the first exercise only required
// entering `n` in the terminal to go to the next exercise.
}

View file

@ -11,7 +11,7 @@ use std::{
use crate::{ use crate::{
clear_terminal, clear_terminal,
embedded::EMBEDDED_FILES, embedded::EMBEDDED_FILES,
exercise::{Exercise, OUTPUT_CAPACITY}, exercise::{Exercise, RunnableExercise, OUTPUT_CAPACITY},
info_file::ExerciseInfo, info_file::ExerciseInfo,
DEBUG_PROFILE, DEBUG_PROFILE,
}; };
@ -40,6 +40,25 @@ struct CargoMetadata {
target_directory: PathBuf, target_directory: PathBuf,
} }
pub fn parse_target_dir() -> Result<PathBuf> {
// Get the target directory from Cargo.
let metadata_output = Command::new("cargo")
.arg("metadata")
.arg("-q")
.arg("--format-version")
.arg("1")
.arg("--no-deps")
.stdin(Stdio::null())
.stderr(Stdio::inherit())
.output()
.context(CARGO_METADATA_ERR)?
.stdout;
serde_json::de::from_slice::<CargoMetadata>(&metadata_output)
.context("Failed to read the field `target_directory` from the `cargo metadata` output")
.map(|metadata| metadata.target_directory)
}
pub struct AppState { pub struct AppState {
current_exercise_ind: usize, current_exercise_ind: usize,
exercises: Vec<Exercise>, exercises: Vec<Exercise>,
@ -104,23 +123,7 @@ impl AppState {
exercise_infos: Vec<ExerciseInfo>, exercise_infos: Vec<ExerciseInfo>,
final_message: String, final_message: String,
) -> Result<(Self, StateFileStatus)> { ) -> Result<(Self, StateFileStatus)> {
// Get the target directory from Cargo. let target_dir = parse_target_dir()?;
let metadata_output = Command::new("cargo")
.arg("metadata")
.arg("-q")
.arg("--format-version")
.arg("1")
.arg("--no-deps")
.stdin(Stdio::null())
.stderr(Stdio::inherit())
.output()
.context(CARGO_METADATA_ERR)?
.stdout;
let target_dir = serde_json::de::from_slice::<CargoMetadata>(&metadata_output)
.context(
"Failed to read the field `target_directory` from the `cargo metadata` output",
)?
.target_directory;
let exercises = exercise_infos let exercises = exercise_infos
.into_iter() .into_iter()
@ -381,7 +384,7 @@ impl AppState {
write!(writer, "Running {exercise} ... ")?; write!(writer, "Running {exercise} ... ")?;
writer.flush()?; writer.flush()?;
let success = exercise.run(&mut output, &self.target_dir)?; let success = exercise.run_exercise(&mut output, &self.target_dir)?;
if !success { if !success {
writeln!(writer, "{}\n", "FAILED".red())?; writeln!(writer, "{}\n", "FAILED".red())?;

View file

@ -1,7 +1,11 @@
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use std::path::Path;
use crate::info_file::ExerciseInfo; use crate::info_file::ExerciseInfo;
/// Initial capacity of the bins buffer.
pub const BINS_BUFFER_CAPACITY: usize = 1 << 14;
/// Return the start and end index of the content of the list `bin = […]`. /// Return the start and end index of the content of the list `bin = […]`.
/// bin = [xxxxxxxxxxxxxxxxx] /// bin = [xxxxxxxxxxxxxxxxx]
/// |start_ind | /// |start_ind |
@ -40,6 +44,24 @@ pub fn append_bins(
} }
buf.extend_from_slice(exercise_info.name.as_bytes()); buf.extend_from_slice(exercise_info.name.as_bytes());
buf.extend_from_slice(b".rs\" },\n"); buf.extend_from_slice(b".rs\" },\n");
let sol_path = exercise_info.sol_path();
if !Path::new(&sol_path).exists() {
continue;
}
buf.extend_from_slice(b" { name = \"");
buf.extend_from_slice(exercise_info.name.as_bytes());
buf.extend_from_slice(b"_sol");
buf.extend_from_slice(b"\", path = \"");
buf.extend_from_slice(exercise_path_prefix);
buf.extend_from_slice(b"solutions/");
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");
} }
} }
@ -51,7 +73,7 @@ pub fn updated_cargo_toml(
) -> Result<Vec<u8>> { ) -> Result<Vec<u8>> {
let (bins_start_ind, bins_end_ind) = bins_start_end_ind(current_cargo_toml)?; let (bins_start_ind, bins_end_ind) = bins_start_end_ind(current_cargo_toml)?;
let mut updated_cargo_toml = Vec::with_capacity(1 << 13); let mut updated_cargo_toml = Vec::with_capacity(BINS_BUFFER_CAPACITY);
updated_cargo_toml.extend_from_slice(current_cargo_toml[..bins_start_ind].as_bytes()); updated_cargo_toml.extend_from_slice(current_cargo_toml[..bins_start_ind].as_bytes());
append_bins( append_bins(
&mut updated_cargo_toml, &mut updated_cargo_toml,

View file

@ -35,7 +35,7 @@ pub fn run_cmd(mut cmd: Command, description: &str, output: &mut Vec<u8>) -> Res
pub struct CargoCmd<'a> { pub struct CargoCmd<'a> {
pub subcommand: &'a str, pub subcommand: &'a str,
pub args: &'a [&'a str], pub args: &'a [&'a str],
pub exercise_name: &'a str, pub bin_name: &'a str,
pub description: &'a str, pub description: &'a str,
/// RUSTFLAGS="-A warnings" /// RUSTFLAGS="-A warnings"
pub hide_warnings: bool, pub hide_warnings: bool,
@ -65,7 +65,7 @@ impl<'a> CargoCmd<'a> {
.arg("always") .arg("always")
.arg("-q") .arg("-q")
.arg("--bin") .arg("--bin")
.arg(self.exercise_name) .arg(self.bin_name)
.args(self.args); .args(self.args);
if self.hide_warnings { if self.hide_warnings {

View file

@ -19,7 +19,11 @@ pub enum DevCommands {
no_git: bool, no_git: bool,
}, },
/// Run checks on the exercises /// Run checks on the exercises
Check, Check {
/// Require that every exercise has a solution
#[arg(short, long)]
require_solutions: bool,
},
/// Update the `Cargo.toml` file for the exercises /// Update the `Cargo.toml` file for the exercises
Update, Update,
} }
@ -34,7 +38,7 @@ impl DevCommands {
new::new(&path, no_git).context(INIT_ERR) new::new(&path, no_git).context(INIT_ERR)
} }
Self::Check => check::check(), Self::Check { require_solutions } => check::check(require_solutions),
Self::Update => update::update(), Self::Update => update::update(),
} }
} }

View file

@ -1,20 +1,45 @@
use anyhow::{anyhow, bail, Context, Error, Result}; use anyhow::{anyhow, bail, Context, Result};
use std::{ use std::{
cmp::Ordering, cmp::Ordering,
fs::{self, read_dir, OpenOptions}, fs::{self, read_dir, OpenOptions},
io::Read, io::{self, Read, Write},
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use crate::{ use crate::{
cargo_toml::{append_bins, bins_start_end_ind}, app_state::parse_target_dir,
cargo_toml::{append_bins, bins_start_end_ind, BINS_BUFFER_CAPACITY},
exercise::{RunnableExercise, OUTPUT_CAPACITY},
info_file::{ExerciseInfo, InfoFile}, info_file::{ExerciseInfo, InfoFile},
CURRENT_FORMAT_VERSION, DEBUG_PROFILE, CURRENT_FORMAT_VERSION, DEBUG_PROFILE,
}; };
// Find a char that isn't allowed in the exercise's `name` or `dir`. // Find a char that isn't allowed in the exercise's `name` or `dir`.
fn forbidden_char(input: &str) -> Option<char> { fn forbidden_char(input: &str) -> Option<char> {
input.chars().find(|c| *c != '_' && !c.is_alphanumeric()) input.chars().find(|c| !c.is_alphanumeric() && *c != '_')
}
// Check that the Cargo.toml file is up-to-date.
fn check_cargo_toml(
exercise_infos: &[ExerciseInfo],
current_cargo_toml: &str,
exercise_path_prefix: &[u8],
) -> Result<()> {
let (bins_start_ind, bins_end_ind) = bins_start_end_ind(current_cargo_toml)?;
let old_bins = &current_cargo_toml.as_bytes()[bins_start_ind..bins_end_ind];
let mut new_bins = Vec::with_capacity(BINS_BUFFER_CAPACITY);
append_bins(&mut new_bins, exercise_infos, exercise_path_prefix);
if old_bins != new_bins {
if DEBUG_PROFILE {
bail!("The file `dev/Cargo.toml` is outdated. Please run `cargo run -- dev update` to update it");
}
bail!("The file `Cargo.toml` is outdated. Please run `rustlings dev update` to update it");
}
Ok(())
} }
// Check the info of all exercises and return their paths in a set. // Check the info of all exercises and return their paths in a set.
@ -74,14 +99,19 @@ fn check_info_file_exercises(info_file: &InfoFile) -> Result<hashbrown::HashSet<
Ok(paths) Ok(paths)
} }
// Check the `exercises` directory for unexpected files. // Check `dir` for unexpected files.
fn check_unexpected_files(info_file_paths: &hashbrown::HashSet<PathBuf>) -> Result<()> { // Only Rust files in `allowed_rust_files` and `README.md` files are allowed.
fn unexpected_file(path: &Path) -> Error { // Only one level of directory nesting is allowed.
anyhow!("Found the file `{}`. Only `README.md` and Rust files related to an exercise in `info.toml` are allowed in the `exercises` directory", path.display()) fn check_unexpected_files(
} dir: &str,
allowed_rust_files: &hashbrown::HashSet<PathBuf>,
) -> Result<()> {
let unexpected_file = |path: &Path| {
anyhow!("Found the file `{}`. Only `README.md` and Rust files related to an exercise in `info.toml` are allowed in the `{dir}` directory", path.display())
};
for entry in read_dir("exercises").context("Failed to open the `exercises` directory")? { for entry in read_dir(dir).with_context(|| format!("Failed to open the `{dir}` directory"))? {
let entry = entry.context("Failed to read the `exercises` directory")?; let entry = entry.with_context(|| format!("Failed to read the `{dir}` directory"))?;
if entry.file_type().unwrap().is_file() { if entry.file_type().unwrap().is_file() {
let path = entry.path(); let path = entry.path();
@ -90,7 +120,7 @@ fn check_unexpected_files(info_file_paths: &hashbrown::HashSet<PathBuf>) -> Resu
continue; continue;
} }
if !info_file_paths.contains(&path) { if !allowed_rust_files.contains(&path) {
return Err(unexpected_file(&path)); return Err(unexpected_file(&path));
} }
@ -114,7 +144,7 @@ fn check_unexpected_files(info_file_paths: &hashbrown::HashSet<PathBuf>) -> Resu
continue; continue;
} }
if !info_file_paths.contains(&path) { if !allowed_rust_files.contains(&path) {
return Err(unexpected_file(&path)); return Err(unexpected_file(&path));
} }
} }
@ -131,37 +161,48 @@ fn check_exercises(info_file: &InfoFile) -> Result<()> {
} }
let info_file_paths = check_info_file_exercises(info_file)?; let info_file_paths = check_info_file_exercises(info_file)?;
check_unexpected_files(&info_file_paths)?; check_unexpected_files("exercises", &info_file_paths)?;
Ok(()) Ok(())
} }
// Check that the Cargo.toml file is up-to-date. fn check_solutions(require_solutions: bool, info_file: &InfoFile) -> Result<()> {
fn check_cargo_toml( let mut paths = hashbrown::HashSet::with_capacity(info_file.exercises.len());
exercise_infos: &[ExerciseInfo], let target_dir = parse_target_dir()?;
current_cargo_toml: &str, let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
exercise_path_prefix: &[u8],
) -> Result<()> {
let (bins_start_ind, bins_end_ind) = bins_start_end_ind(current_cargo_toml)?;
let old_bins = &current_cargo_toml.as_bytes()[bins_start_ind..bins_end_ind]; for exercise_info in &info_file.exercises {
let mut new_bins = Vec::with_capacity(1 << 13); let path = exercise_info.sol_path();
append_bins(&mut new_bins, exercise_infos, exercise_path_prefix); if !Path::new(&path).exists() {
if require_solutions {
if old_bins != new_bins { bail!("Exercise {} is missing a solution", exercise_info.name);
if DEBUG_PROFILE {
bail!("The file `dev/Cargo.toml` is outdated. Please run `cargo run -- dev update` to update it");
} }
bail!("The file `Cargo.toml` is outdated. Please run `rustlings dev update` to update it"); // No solution to check.
continue;
} }
println!("Running the solution of {}", exercise_info.name);
let success = exercise_info.run_solution(&mut output, &target_dir)?;
if !success {
io::stderr().write_all(&output)?;
bail!(
"Failed to run the solution of the exercise {}",
exercise_info.name,
);
}
paths.insert(PathBuf::from(path));
}
check_unexpected_files("solutions", &paths)?;
Ok(()) Ok(())
} }
pub fn check() -> Result<()> { pub fn check(require_solutions: bool) -> Result<()> {
let info_file = InfoFile::parse()?; let info_file = InfoFile::parse()?;
check_exercises(&info_file)?;
// A hack to make `cargo run -- dev check` work when developing Rustlings. // A hack to make `cargo run -- dev check` work when developing Rustlings.
if DEBUG_PROFILE { if DEBUG_PROFILE {
@ -176,6 +217,9 @@ pub fn check() -> Result<()> {
check_cargo_toml(&info_file.exercises, &current_cargo_toml, b"")?; check_cargo_toml(&info_file.exercises, &current_cargo_toml, b"")?;
} }
check_exercises(&info_file)?;
check_solutions(require_solutions, &info_file)?;
println!("\nEverything looks fine!"); println!("\nEverything looks fine!");
Ok(()) Ok(())

View file

@ -1,6 +1,6 @@
use anyhow::{Context, Error, Result}; use anyhow::{Context, Error, Result};
use std::{ use std::{
fs::{create_dir, create_dir_all, OpenOptions}, fs::{create_dir, OpenOptions},
io::{self, Write}, io::{self, Write},
}; };
@ -43,8 +43,8 @@ struct ExerciseFiles {
} }
// A directory in the `exercises/` directory. // A directory in the `exercises/` directory.
struct ExerciseDir { pub struct ExerciseDir {
name: &'static str, pub name: &'static str,
readme: &'static [u8], readme: &'static [u8],
} }
@ -78,7 +78,7 @@ pub struct EmbeddedFiles {
/// The content of the `info.toml` file. /// The content of the `info.toml` file.
pub info_file: &'static str, pub info_file: &'static str,
exercise_files: &'static [ExerciseFiles], exercise_files: &'static [ExerciseFiles],
exercise_dirs: &'static [ExerciseDir], pub exercise_dirs: &'static [ExerciseDir],
} }
impl EmbeddedFiles { impl EmbeddedFiles {
@ -121,13 +121,9 @@ impl EmbeddedFiles {
// 14 = 10 + 1 + 3 // 14 = 10 + 1 + 3
// solutions/ + / + .rs // solutions/ + / + .rs
let mut dir_path = String::with_capacity(14 + dir.name.len() + exercise_name.len()); let mut solution_path = String::with_capacity(14 + dir.name.len() + exercise_name.len());
dir_path.push_str("solutions/"); solution_path.push_str("solutions/");
dir_path.push_str(dir.name); solution_path.push_str(dir.name);
create_dir_all(&dir_path)
.with_context(|| format!("Failed to create the directory {dir_path}"))?;
let mut solution_path = dir_path;
solution_path.push('/'); solution_path.push('/');
solution_path.push_str(exercise_name); solution_path.push_str(exercise_name);
solution_path.push_str(".rs"); solution_path.push_str(".rs");

View file

@ -17,30 +17,16 @@ use crate::{
/// The initial capacity of the output buffer. /// The initial capacity of the output buffer.
pub const OUTPUT_CAPACITY: usize = 1 << 14; pub const OUTPUT_CAPACITY: usize = 1 << 14;
/// See `info_file::ExerciseInfo` // Run an exercise binary and append its output to the `output` buffer.
pub struct Exercise { // Compilation must be done before calling this method.
pub dir: Option<&'static str>, fn run_bin(bin_name: &str, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
pub name: &'static str,
/// Path of the exercise file starting with the `exercises/` directory.
pub path: &'static str,
pub test: bool,
pub strict_clippy: bool,
pub hint: String,
pub done: bool,
}
impl Exercise {
// Run the exercise's binary and append its output to the `output` buffer.
// Compilation should be done before calling this method.
fn run_bin(&self, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
writeln!(output, "{}", "Output".underlined())?; writeln!(output, "{}", "Output".underlined())?;
// 7 = "/debug/".len() // 7 = "/debug/".len()
let mut bin_path = let mut bin_path = PathBuf::with_capacity(target_dir.as_os_str().len() + 7 + bin_name.len());
PathBuf::with_capacity(target_dir.as_os_str().len() + 7 + self.name.len());
bin_path.push(target_dir); bin_path.push(target_dir);
bin_path.push("debug"); bin_path.push("debug");
bin_path.push(self.name); bin_path.push(bin_name);
let success = run_cmd(Command::new(&bin_path), &bin_path.to_string_lossy(), output)?; let success = run_cmd(Command::new(&bin_path), &bin_path.to_string_lossy(), output)?;
@ -60,9 +46,38 @@ impl Exercise {
Ok(success) Ok(success)
} }
/// Compile, check and run the exercise. /// See `info_file::ExerciseInfo`
/// The output is written to the `output` buffer after clearing it. pub struct Exercise {
pub fn run(&self, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> { pub dir: Option<&'static str>,
pub name: &'static str,
/// Path of the exercise file starting with the `exercises/` directory.
pub path: &'static str,
pub test: bool,
pub strict_clippy: bool,
pub hint: String,
pub done: bool,
}
impl Exercise {
pub fn terminal_link(&self) -> StyledContent<TerminalFileLink<'_>> {
style(TerminalFileLink(self.path)).underlined().blue()
}
}
impl Display for Exercise {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.path.fmt(f)
}
}
pub trait RunnableExercise {
fn name(&self) -> &str;
fn strict_clippy(&self) -> bool;
fn test(&self) -> bool;
// Compile, check and run the exercise or its solution (depending on `bin_name´).
// The output is written to the `output` buffer after clearing it.
fn run(&self, bin_name: &str, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
output.clear(); output.clear();
// Developing the official Rustlings. // Developing the official Rustlings.
@ -71,7 +86,7 @@ impl Exercise {
let build_success = CargoCmd { let build_success = CargoCmd {
subcommand: "build", subcommand: "build",
args: &[], args: &[],
exercise_name: self.name, bin_name,
description: "cargo build …", description: "cargo build …",
hide_warnings: false, hide_warnings: false,
target_dir, target_dir,
@ -87,7 +102,7 @@ impl Exercise {
output.clear(); output.clear();
// `--profile test` is required to also check code with `[cfg(test)]`. // `--profile test` is required to also check code with `[cfg(test)]`.
let clippy_args: &[&str] = if self.strict_clippy { let clippy_args: &[&str] = if self.strict_clippy() {
&["--profile", "test", "--", "-D", "warnings"] &["--profile", "test", "--", "-D", "warnings"]
} else { } else {
&["--profile", "test"] &["--profile", "test"]
@ -95,7 +110,7 @@ impl Exercise {
let clippy_success = CargoCmd { let clippy_success = CargoCmd {
subcommand: "clippy", subcommand: "clippy",
args: clippy_args, args: clippy_args,
exercise_name: self.name, bin_name,
description: "cargo clippy …", description: "cargo clippy …",
hide_warnings: false, hide_warnings: false,
target_dir, target_dir,
@ -107,14 +122,14 @@ impl Exercise {
return Ok(false); return Ok(false);
} }
if !self.test { if !self.test() {
return self.run_bin(output, target_dir); return run_bin(bin_name, output, target_dir);
} }
let test_success = CargoCmd { let test_success = CargoCmd {
subcommand: "test", subcommand: "test",
args: &["--", "--color", "always", "--show-output"], args: &["--", "--color", "always", "--show-output"],
exercise_name: self.name, bin_name,
description: "cargo test …", description: "cargo test …",
// Hide warnings because they are shown by Clippy. // Hide warnings because they are shown by Clippy.
hide_warnings: true, hide_warnings: true,
@ -124,18 +139,43 @@ impl Exercise {
} }
.run()?; .run()?;
let run_success = self.run_bin(output, target_dir)?; let run_success = run_bin(bin_name, output, target_dir)?;
Ok(test_success && run_success) Ok(test_success && run_success)
} }
pub fn terminal_link(&self) -> StyledContent<TerminalFileLink<'_>> { /// Compile, check and run the exercise.
style(TerminalFileLink(self.path)).underlined().blue() /// The output is written to the `output` buffer after clearing it.
#[inline]
fn run_exercise(&self, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
self.run(self.name(), output, target_dir)
}
/// Compile, check and run the exercise's solution.
/// The output is written to the `output` buffer after clearing it.
fn run_solution(&self, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
let name = self.name();
let mut bin_name = String::with_capacity(name.len());
bin_name.push_str(name);
bin_name.push_str("_sol");
self.run(&bin_name, output, target_dir)
} }
} }
impl Display for Exercise { impl RunnableExercise for Exercise {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { #[inline]
self.path.fmt(f) fn name(&self) -> &str {
self.name
}
#[inline]
fn strict_clippy(&self) -> bool {
self.strict_clippy
}
#[inline]
fn test(&self) -> bool {
self.test
} }
} }

View file

@ -2,7 +2,7 @@ use anyhow::{bail, Context, Error, Result};
use serde::Deserialize; use serde::Deserialize;
use std::{fs, io::ErrorKind}; use std::{fs, io::ErrorKind};
use crate::embedded::EMBEDDED_FILES; use crate::{embedded::EMBEDDED_FILES, exercise::RunnableExercise};
/// Deserialized from the `info.toml` file. /// Deserialized from the `info.toml` file.
#[derive(Deserialize)] #[derive(Deserialize)]
@ -49,6 +49,47 @@ impl ExerciseInfo {
path path
} }
/// Path to the solution file starting with the `solutions/` directory.
pub fn sol_path(&self) -> String {
let mut path = if let Some(dir) = &self.dir {
// 14 = 10 + 1 + 3
// solutions/ + / + .rs
let mut path = String::with_capacity(14 + dir.len() + self.name.len());
path.push_str("solutions/");
path.push_str(dir);
path.push('/');
path
} else {
// 13 = 10 + 3
// solutions/ + .rs
let mut path = String::with_capacity(13 + self.name.len());
path.push_str("solutions/");
path
};
path.push_str(&self.name);
path.push_str(".rs");
path
}
}
impl RunnableExercise for ExerciseInfo {
#[inline]
fn name(&self) -> &str {
&self.name
}
#[inline]
fn strict_clippy(&self) -> bool {
self.strict_clippy
}
#[inline]
fn test(&self) -> bool {
self.test
}
} }
/// The deserialized `info.toml` file. /// The deserialized `info.toml` file.

View file

@ -34,6 +34,20 @@ pub fn init() -> Result<()> {
.init_exercises_dir(&info_file.exercises) .init_exercises_dir(&info_file.exercises)
.context("Failed to initialize the `rustlings/exercises` directory")?; .context("Failed to initialize the `rustlings/exercises` directory")?;
create_dir("solutions").context("Failed to create the `solutions/` directory")?;
for dir in EMBEDDED_FILES.exercise_dirs {
let mut dir_path = String::with_capacity(10 + dir.name.len());
dir_path.push_str("solutions/");
dir_path.push_str(dir.name);
create_dir(&dir_path)
.with_context(|| format!("Failed to create the directory {dir_path}"))?;
}
for exercise_info in &info_file.exercises {
let solution_path = exercise_info.sol_path();
fs::write(&solution_path, INIT_SOLUTION_FILE)
.with_context(|| format!("Failed to create the file {solution_path}"))?;
}
let current_cargo_toml = include_str!("../dev-Cargo.toml"); let current_cargo_toml = include_str!("../dev-Cargo.toml");
// Skip the first line (comment). // Skip the first line (comment).
let newline_ind = current_cargo_toml let newline_ind = current_cargo_toml
@ -72,6 +86,12 @@ pub fn init() -> Result<()> {
Ok(()) Ok(())
} }
const INIT_SOLUTION_FILE: &[u8] = b"fn main() {
// DON'T EDIT THIS SOLUTION FILE!
// It will be automatically filled after you finish the exercise.
}
";
const GITIGNORE: &[u8] = b".rustlings-state.txt const GITIGNORE: &[u8] = b".rustlings-state.txt
solutions solutions
Cargo.lock Cargo.lock

View file

@ -4,14 +4,14 @@ use std::io::{self, Write};
use crate::{ use crate::{
app_state::{AppState, ExercisesProgress}, app_state::{AppState, ExercisesProgress},
exercise::OUTPUT_CAPACITY, exercise::{RunnableExercise, OUTPUT_CAPACITY},
terminal_link::TerminalFileLink, terminal_link::TerminalFileLink,
}; };
pub fn run(app_state: &mut AppState) -> Result<()> { pub fn run(app_state: &mut AppState) -> Result<()> {
let exercise = app_state.current_exercise(); let exercise = app_state.current_exercise();
let mut output = Vec::with_capacity(OUTPUT_CAPACITY); let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
let success = exercise.run(&mut output, app_state.target_dir())?; let success = exercise.run_exercise(&mut output, app_state.target_dir())?;
let mut stdout = io::stdout().lock(); let mut stdout = io::stdout().lock();
stdout.write_all(&output)?; stdout.write_all(&output)?;

View file

@ -8,7 +8,7 @@ use std::io::{self, StdoutLock, Write};
use crate::{ use crate::{
app_state::{AppState, ExercisesProgress}, app_state::{AppState, ExercisesProgress},
clear_terminal, clear_terminal,
exercise::OUTPUT_CAPACITY, exercise::{RunnableExercise, OUTPUT_CAPACITY},
progress_bar::progress_bar, progress_bar::progress_bar,
terminal_link::TerminalFileLink, terminal_link::TerminalFileLink,
}; };
@ -54,7 +54,7 @@ impl<'a> WatchState<'a> {
let success = self let success = self
.app_state .app_state
.current_exercise() .current_exercise()
.run(&mut self.output, self.app_state.target_dir())?; .run_exercise(&mut self.output, self.app_state.target_dir())?;
if success { if success {
self.done_status = self.done_status =
if let Some(solution_path) = self.app_state.current_solution_path()? { if let Some(solution_path) = self.app_state.current_solution_path()? {