mirror of
https://github.com/rust-lang/rustlings.git
synced 2025-12-26 00:11:49 +02:00
Compare commits
133 Commits
v6.0.1
...
rustlings-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4472d50eba | ||
|
|
a1d5702ba0 | ||
|
|
52a231ce2f | ||
|
|
16af981772 | ||
|
|
fc141b8dfc | ||
|
|
82ebd29ff6 | ||
|
|
f5737b5a49 | ||
|
|
55e68d2c63 | ||
|
|
479f45da9b | ||
|
|
140c4e4812 | ||
|
|
337460d299 | ||
|
|
e41c3a7c92 | ||
|
|
1b9faa4d61 | ||
|
|
9f9a754a64 | ||
|
|
f7b0cfe8d1 | ||
|
|
4ce8667b9d | ||
|
|
0785b24192 | ||
|
|
34f02cf83d | ||
|
|
8b43d79257 | ||
|
|
dc086c6bf1 | ||
|
|
dc0ffbe16e | ||
|
|
8df66f7991 | ||
|
|
39580381fa | ||
|
|
06a0f278e5 | ||
|
|
fd97470f35 | ||
|
|
11fc3f1e56 | ||
|
|
693bb708b2 | ||
|
|
97719fe8da | ||
|
|
4933ace50b | ||
|
|
81bf0a6430 | ||
|
|
24aed1b14e | ||
|
|
09c3ac02f8 | ||
|
|
45a39585b3 | ||
|
|
286a455fa9 | ||
|
|
bdf4960b6a | ||
|
|
13124aafe3 | ||
|
|
2128be8b28 | ||
|
|
175294fa5d | ||
|
|
5016c7cf7c | ||
|
|
1468206052 | ||
|
|
d1ff4b5cf0 | ||
|
|
700a065abd | ||
|
|
3fc462f90f | ||
|
|
65a8f6bb4b | ||
|
|
e0f0944bff | ||
|
|
c7590dd752 | ||
|
|
33a5680328 | ||
|
|
455d87cadd | ||
|
|
e65ae09789 | ||
|
|
dacdce1ea2 | ||
|
|
766f3c50ec | ||
|
|
802b97b2ed | ||
|
|
2ad408f2b8 | ||
|
|
c8fddd8f62 | ||
|
|
74fab994e2 | ||
|
|
3a99542f73 | ||
|
|
2ae9f3555b | ||
|
|
1937b4bf66 | ||
|
|
8beb290842 | ||
|
|
8fec5155c7 | ||
|
|
3f49decce9 | ||
|
|
e2492f65a0 | ||
|
|
5116a812fb | ||
|
|
82409c060f | ||
|
|
183ed3f88f | ||
|
|
447ac3c40b | ||
|
|
96f96927da | ||
|
|
2c79e29483 | ||
|
|
362473dde0 | ||
|
|
8339682112 | ||
|
|
3f06d767b5 | ||
|
|
2854dc9ab3 | ||
|
|
516fcf9168 | ||
|
|
12d1971b0d | ||
|
|
3e09e509d6 | ||
|
|
99fb11cc72 | ||
|
|
d176ddd27e | ||
|
|
0847b3a4bf | ||
|
|
6d2ea8dae3 | ||
|
|
47ba4502e0 | ||
|
|
6263cb6456 | ||
|
|
d7024d80ce | ||
|
|
59d6b852af | ||
|
|
e512928df5 | ||
|
|
a38029e3e7 | ||
|
|
b12b652a57 | ||
|
|
c793416495 | ||
|
|
01343f187b | ||
|
|
69021e1497 | ||
|
|
08c408aae0 | ||
|
|
bf698659b0 | ||
|
|
2d5d70693a | ||
|
|
a4091ade5c | ||
|
|
a7a881809f | ||
|
|
0f4cb94cfe | ||
|
|
6469e9734b | ||
|
|
5372caefb3 | ||
|
|
9d7b973a62 | ||
|
|
a5f221aa39 | ||
|
|
e764b75aef | ||
|
|
708cfef3f7 | ||
|
|
01b8432d58 | ||
|
|
9b5b652c71 | ||
|
|
981a4778a9 | ||
|
|
5d4363d58d | ||
|
|
48697b8225 | ||
|
|
1652bb67d9 | ||
|
|
1499f681a3 | ||
|
|
a21fa6ff40 | ||
|
|
186dc3c1ab | ||
|
|
6b7a27d080 | ||
|
|
c9017f9f7a | ||
|
|
fdada8b3d4 | ||
|
|
9e2ff7d037 | ||
|
|
65834fc420 | ||
|
|
f5a4965de7 | ||
|
|
db5911eb73 | ||
|
|
2f4e63b443 | ||
|
|
584164a6ff | ||
|
|
e6f6d26d13 | ||
|
|
67d8d5848c | ||
|
|
43d15f09f0 | ||
|
|
7123c7ae3a | ||
|
|
4d9c346a17 | ||
|
|
deed9d3943 | ||
|
|
652f0c7676 | ||
|
|
e479ec8fb6 | ||
|
|
a33501e6a7 | ||
|
|
47f8199a99 | ||
|
|
4bf0ddc0e1 | ||
|
|
4cd0ccce83 | ||
|
|
a3657188b6 | ||
|
|
77b687d501 |
4
.github/workflows/rust.yml
vendored
4
.github/workflows/rust.yml
vendored
@@ -23,7 +23,7 @@ jobs:
|
||||
with:
|
||||
globs: "exercises/**/*.md"
|
||||
- name: Run cargo fmt
|
||||
run: cargo fmt --all -- --check
|
||||
run: cargo fmt --all --check
|
||||
test:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: swatinem/rust-cache@v2
|
||||
- name: Run cargo test
|
||||
run: cargo test
|
||||
run: cargo test --workspace
|
||||
dev-check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
39
CHANGELOG.md
39
CHANGELOG.md
@@ -1,3 +1,40 @@
|
||||
<a name="6.2.0"></a>
|
||||
|
||||
## 6.2.0 (2024-08-09)
|
||||
|
||||
### Added
|
||||
|
||||
- Show a message before checking and running an exercise. This gives the user instant feedback and avoids confusion if the checks take too long.
|
||||
- Show a helpful error message when trying to install Rustlings with a Rust version lower than the minimum one that Rustlings supports.
|
||||
- Add a `README.md` file to the `solutions/` directory.
|
||||
- Allow initializing Rustlings in a Cargo workspace.
|
||||
- `dev check`: Check that all solutions are formatted with `rustfmt`.
|
||||
|
||||
### Changed
|
||||
|
||||
- Remove the state file and the solutions directory from the generated `.gitignore` file.
|
||||
- Run the final check of all exercises in parallel.
|
||||
- Small exercise improvements.
|
||||
|
||||
<a name="6.1.0"></a>
|
||||
|
||||
## 6.1.0 (2024-07-10)
|
||||
|
||||
#### Added
|
||||
|
||||
- `dev check`: Check that all exercises (including third-party ones) include at least one `TODO` comment.
|
||||
- `dev check`: Check that all exercises actually fail to run (not already solved).
|
||||
|
||||
#### Changed
|
||||
|
||||
- Make enum variants more consistent between enum exercises.
|
||||
- `iterators3`: Teach about the possible case of integer overflow during division.
|
||||
|
||||
#### Fixed
|
||||
|
||||
- Exit with a helpful error message on missing/unsupported terminal/TTY.
|
||||
- Mark the last exercise as done.
|
||||
|
||||
<a name="6.0.1"></a>
|
||||
|
||||
## 6.0.1 (2024-07-04)
|
||||
@@ -64,7 +101,7 @@ This should avoid issues related to the language server or to running exercises,
|
||||
Clippy lints are now shown on all exercises, not only the Clippy exercises 📎
|
||||
Make Clippy your friend from early on 🥰
|
||||
|
||||
### Third party exercises
|
||||
### Third-party exercises
|
||||
|
||||
Rustlings now supports third-party exercises!
|
||||
|
||||
|
||||
379
Cargo.lock
generated
379
Cargo.lock
generated
@@ -14,15 +14,6 @@ dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "allocator-api2"
|
||||
version = "0.2.18"
|
||||
@@ -31,9 +22,9 @@ checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f"
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "0.6.14"
|
||||
version = "0.6.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b"
|
||||
checksum = "64e15c1ab1f89faffbf04a634d5e1962e9074f2741eef6d97f3c4e322426d526"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"anstyle-parse",
|
||||
@@ -46,33 +37,33 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.7"
|
||||
version = "1.0.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b"
|
||||
checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-parse"
|
||||
version = "0.2.4"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4"
|
||||
checksum = "eb47de1e80c2b463c735db5b217a0ddc39d612e7ac9e2e96a5aed1f57616c1cb"
|
||||
dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-query"
|
||||
version = "1.1.0"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad186efb764318d35165f1758e7dcef3b10628e26d41a44bc5550652e6804391"
|
||||
checksum = "6d36fc52c7f6c869915e99412912f22093507da8d9e942ceaf66fe4b7c14422a"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-wincon"
|
||||
version = "3.0.3"
|
||||
version = "3.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19"
|
||||
checksum = "5bf74e1b6e971609db8ca7a9ce79fd5768ab6ae46441c572e46cf596f59e57f8"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"windows-sys 0.52.0",
|
||||
@@ -84,21 +75,6 @@ version = "1.0.86"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da"
|
||||
|
||||
[[package]]
|
||||
name = "assert_cmd"
|
||||
version = "2.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed72493ac66d5804837f480ab3766c72bdfab91a65e565fc54fa9e42db0073a8"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"bstr",
|
||||
"doc-comment",
|
||||
"predicates",
|
||||
"predicates-core",
|
||||
"predicates-tree",
|
||||
"wait-timeout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.3.0"
|
||||
@@ -117,17 +93,6 @@ version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
|
||||
|
||||
[[package]]
|
||||
name = "bstr"
|
||||
version = "1.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "05efc5cfd9110c8416e471df0e96702d58690178e206e61b7173706673c93706"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cassowary"
|
||||
version = "0.3.0"
|
||||
@@ -151,9 +116,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.5.8"
|
||||
version = "4.5.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84b3edb18336f4df585bc9aa31dd99c036dfa5dc5e9a2939a722a188f3a8970d"
|
||||
checksum = "c937d4061031a6d0c8da4b9a4f98a172fc2976dfb1c19213a9cf7d0d3c837e36"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
@@ -161,9 +126,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.5.8"
|
||||
version = "4.5.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1c09dd5ada6c6c78075d6fd0da3f90d8080651e2d6cc8eb2f1aaa4034ced708"
|
||||
checksum = "85379ba512b21a328adf887e85f7742d12e96eb31f3ef077df4ffc26b506ffed"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -173,9 +138,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.5.8"
|
||||
version = "4.5.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bac35c6dafb060fd4d275d9a4ffae97917c13a6327903a8be2153cd964f7085"
|
||||
checksum = "501d359d5f3dcaf6ecdeee48833ae73ec6e42723a1e52419c79abf9507eec0a0"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
@@ -185,25 +150,26 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "0.7.1"
|
||||
version = "0.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b82cf0babdbd58558212896d1a4272303a57bdb245c2bf1147185fb45640e70"
|
||||
checksum = "1462739cb27611015575c0c11df5df7601141071f07518d56fcc1be504cbec97"
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.1"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422"
|
||||
checksum = "d3fd119d74b830634cea2a0f58bbd0d54540518a14397557951e79340abc28c0"
|
||||
|
||||
[[package]]
|
||||
name = "compact_str"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f86b9c4c00838774a6d902ef931eff7470720c51d90c2e32cfe15dc304737b3f"
|
||||
checksum = "6050c3a16ddab2e412160b31f2c871015704239bca62f72f6e5f0be631d3f644"
|
||||
dependencies = [
|
||||
"castaway",
|
||||
"cfg-if",
|
||||
"itoa",
|
||||
"rustversion",
|
||||
"ryu",
|
||||
"static_assertions",
|
||||
]
|
||||
@@ -225,15 +191,15 @@ checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80"
|
||||
|
||||
[[package]]
|
||||
name = "crossterm"
|
||||
version = "0.27.0"
|
||||
version = "0.28.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df"
|
||||
checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"
|
||||
dependencies = [
|
||||
"bitflags 2.6.0",
|
||||
"crossterm_winapi",
|
||||
"libc",
|
||||
"mio",
|
||||
"mio 1.0.1",
|
||||
"parking_lot",
|
||||
"rustix",
|
||||
"signal-hook",
|
||||
"signal-hook-mio",
|
||||
"winapi",
|
||||
@@ -248,18 +214,6 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "difflib"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8"
|
||||
|
||||
[[package]]
|
||||
name = "doc-comment"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10"
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.13.0"
|
||||
@@ -272,6 +226,22 @@ version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a"
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.23"
|
||||
@@ -284,15 +254,6 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "float-cmp"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fsevent-sys"
|
||||
version = "4.1.0"
|
||||
@@ -319,10 +280,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.2.6"
|
||||
name = "hermit-abi"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26"
|
||||
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "de3fc2e30ba82dd1b3911c8de1ffc143c74a914a14e99514d7637e3099df5ea0"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
@@ -349,19 +316,20 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.0"
|
||||
name = "instability"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800"
|
||||
checksum = "b23a0c8dfe501baac4adf6ebbfa6eddf8f0c07f56b058cc1288017e32397846c"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.12.1"
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
@@ -404,6 +372,12 @@ version = "0.2.155"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.12"
|
||||
@@ -422,9 +396,9 @@ checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
|
||||
|
||||
[[package]]
|
||||
name = "lru"
|
||||
version = "0.12.3"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3262e75e648fce39813cb56ac41f3c3e3f65217ebf3844d818d1f9398cfb0dc"
|
||||
checksum = "37ee39891760e7d94734f6f63fedc29a2e4a152f836120753a72503f09fcf904"
|
||||
dependencies = [
|
||||
"hashbrown",
|
||||
]
|
||||
@@ -448,10 +422,17 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "normalize-line-endings"
|
||||
version = "0.3.0"
|
||||
name = "mio"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be"
|
||||
checksum = "4569e456d394deccd22ce1c1913e6ea0e54519f577285001215d33557431afe4"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"log",
|
||||
"wasi",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "notify"
|
||||
@@ -467,7 +448,7 @@ dependencies = [
|
||||
"kqueue",
|
||||
"libc",
|
||||
"log",
|
||||
"mio",
|
||||
"mio 0.8.11",
|
||||
"walkdir",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
@@ -482,15 +463,6 @@ dependencies = [
|
||||
"notify",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.19.0"
|
||||
@@ -499,12 +471,12 @@ checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
|
||||
|
||||
[[package]]
|
||||
name = "os_pipe"
|
||||
version = "1.2.0"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29d73ba8daf8fac13b0501d1abeddcfe21ba7401ada61a819144b6c2a4f32209"
|
||||
checksum = "5ffd2b0a5634335b135d5728d84c5e0fd726954b87111f7506a61c502280d982"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -525,7 +497,7 @@ checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall 0.5.2",
|
||||
"redox_syscall 0.5.3",
|
||||
"smallvec",
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
@@ -536,36 +508,6 @@ version = "1.0.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
||||
|
||||
[[package]]
|
||||
name = "predicates"
|
||||
version = "3.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68b87bfd4605926cdfefc1c3b5f8fe560e3feca9d5552cf68c466d3d8236c7e8"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"difflib",
|
||||
"float-cmp",
|
||||
"normalize-line-endings",
|
||||
"predicates-core",
|
||||
"regex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "predicates-core"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b794032607612e7abeb4db69adb4e33590fa6cf1149e95fd7cb00e634b92f174"
|
||||
|
||||
[[package]]
|
||||
name = "predicates-tree"
|
||||
version = "1.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "368ba315fb8c5052ab692e68a0eefec6ec57b23a36959c14496f0b0df2c0cecf"
|
||||
dependencies = [
|
||||
"predicates-core",
|
||||
"termtree",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.86"
|
||||
@@ -586,18 +528,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ratatui"
|
||||
version = "0.27.0"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d16546c5b5962abf8ce6e2881e722b4e0ae3b6f1a08a26ae3573c55853ca68d3"
|
||||
checksum = "5ba6a365afbe5615999275bea2446b970b10a41102500e27ce7678d50d978303"
|
||||
dependencies = [
|
||||
"bitflags 2.6.0",
|
||||
"cassowary",
|
||||
"compact_str",
|
||||
"crossterm",
|
||||
"itertools 0.13.0",
|
||||
"instability",
|
||||
"itertools",
|
||||
"lru",
|
||||
"paste",
|
||||
"stability",
|
||||
"strum",
|
||||
"strum_macros",
|
||||
"unicode-segmentation",
|
||||
@@ -616,64 +558,46 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.5.2"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c82cf8cff14456045f55ec4241383baeff27af886adb72ffb2162f99911de0fd"
|
||||
checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4"
|
||||
dependencies = [
|
||||
"bitflags 2.6.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.10.5"
|
||||
name = "rustix"
|
||||
version = "0.38.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f"
|
||||
checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
"bitflags 2.6.0",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b"
|
||||
|
||||
[[package]]
|
||||
name = "rustlings"
|
||||
version = "6.0.1"
|
||||
version = "6.2.0"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"anyhow",
|
||||
"assert_cmd",
|
||||
"clap",
|
||||
"crossterm",
|
||||
"hashbrown",
|
||||
"notify-debouncer-mini",
|
||||
"os_pipe",
|
||||
"predicates",
|
||||
"ratatui",
|
||||
"rustlings-macros",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustlings-macros"
|
||||
version = "6.0.1"
|
||||
version = "6.2.0"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"serde",
|
||||
@@ -709,18 +633,18 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.203"
|
||||
version = "1.0.205"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7253ab4de971e72fb7be983802300c30b5a7f0c2e56fab8abfc6a214307c0094"
|
||||
checksum = "e33aedb1a7135da52b7c21791455563facbbcc43d0f0f66165b42c21b3dfb150"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.203"
|
||||
version = "1.0.205"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "500cbc0ebeb6f46627f50f3f5811ccf6bf00643be300b4c3eabc0ef55dc5b5ba"
|
||||
checksum = "692d6f5ac90220161d6774db30c662202721e64aed9058d2c394f451261420c1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -729,20 +653,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.120"
|
||||
version = "1.0.122"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e0d21c9a8cae1235ad58a00c11cb40d4b1e5c784f1ef2c537876ed6ffd8b7c5"
|
||||
checksum = "784b6203951c57ff748476b126ccb5e8e2959a5c19e5c617ab1956be3dbc68da"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"ryu",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_spanned"
|
||||
version = "0.6.6"
|
||||
version = "0.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "79e674e01f999af37c49f70a6ede167a8a60b2503e56c5599532a65baa5969a0"
|
||||
checksum = "eb5b1b31579f3811bf615c144393417496f152e12ac8b7663bf664f4a815306d"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -759,12 +684,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-mio"
|
||||
version = "0.2.3"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af"
|
||||
checksum = "34db1a06d485c9142248b7a054f034b349b212551f3dfd19c94d45a754a217cd"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"mio",
|
||||
"mio 1.0.1",
|
||||
"signal-hook",
|
||||
]
|
||||
|
||||
@@ -783,16 +708,6 @@ version = "1.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
|
||||
|
||||
[[package]]
|
||||
name = "stability"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ff9eaf853dec4c8802325d8b6d3dffa86cc707fd7a1a4cdbf416e13b061787a"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "static_assertions"
|
||||
version = "1.1.0"
|
||||
@@ -829,9 +744,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.68"
|
||||
version = "2.0.72"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "901fa70d88b9d6c98022e23b4136f9f3e54e4662c3bc1bd1d84a42a9a0f0c1e9"
|
||||
checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -839,25 +754,32 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "termtree"
|
||||
version = "0.4.1"
|
||||
name = "tempfile"
|
||||
version = "3.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76"
|
||||
checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"fastrand",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "0.6.6"
|
||||
version = "0.6.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4badfd56924ae69bcc9039335b2e017639ce3f9b001c393c1b2d1ef846ce2cbf"
|
||||
checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_edit"
|
||||
version = "0.22.14"
|
||||
version = "0.22.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f21c7aaf97f1bd9ca9d4f9e73b0a6c74bd5afef56f2bc931943a6e1c37e04e38"
|
||||
checksum = "583c44c02ad26b0c3f3066fe629275e50627026c51ac2e595cca4c230ce1ce1d"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"serde",
|
||||
@@ -880,11 +802,12 @@ checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-truncate"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a5fbabedabe362c618c714dbefda9927b5afc8e2a8102f47f081089a9019226"
|
||||
checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf"
|
||||
dependencies = [
|
||||
"itertools 0.12.1",
|
||||
"itertools",
|
||||
"unicode-segmentation",
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
@@ -902,18 +825,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.4"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
|
||||
|
||||
[[package]]
|
||||
name = "wait-timeout"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "walkdir"
|
||||
@@ -949,11 +863,11 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.8"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b"
|
||||
checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -980,6 +894,15 @@ dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
|
||||
dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.48.5"
|
||||
@@ -1103,9 +1026,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "0.6.13"
|
||||
version = "0.6.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59b5e5f6c299a3c7890b876a2a587f3115162487e704907d9b6cd29473052ba1"
|
||||
checksum = "68a9bda4691f099d435ad181000724da8e5899daa10713c2d432552b9ccd3a6f"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
40
Cargo.toml
40
Cargo.toml
@@ -1,27 +1,26 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
exclude = [
|
||||
"tests/fixture/failure",
|
||||
"tests/fixture/state",
|
||||
"tests/fixture/success",
|
||||
"tests/test_exercises",
|
||||
"dev",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "6.0.1"
|
||||
version = "6.2.0"
|
||||
authors = [
|
||||
"Liv <mokou@fastmail.com>",
|
||||
"Mo Bitar <mo8it@proton.me>",
|
||||
"Mo Bitar <mo8it@proton.me>", # https://github.com/mo8it
|
||||
"Liv <mokou@fastmail.com>", # https://github.com/shadows-withal
|
||||
# Alumni
|
||||
"Carol (Nichols || Goulding) <carol.nichols@gmail.com>",
|
||||
"Carol (Nichols || Goulding) <carol.nichols@gmail.com>", # https://github.com/carols10cents
|
||||
]
|
||||
repository = "https://github.com/rust-lang/rustlings"
|
||||
license = "MIT"
|
||||
edition = "2021"
|
||||
edition = "2021" # On Update: Update the edition of the `rustfmt` command that checks the solutions.
|
||||
rust-version = "1.80"
|
||||
|
||||
[workspace.dependencies]
|
||||
serde = { version = "1.0.203", features = ["derive"] }
|
||||
toml_edit = { version = "0.22.14", default-features = false, features = ["parse", "serde"] }
|
||||
serde = { version = "1.0.205", features = ["derive"] }
|
||||
toml_edit = { version = "0.22.20", default-features = false, features = ["parse", "serde"] }
|
||||
|
||||
[package]
|
||||
name = "rustlings"
|
||||
@@ -31,6 +30,7 @@ authors.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
keywords = [
|
||||
"exercise",
|
||||
"learning",
|
||||
@@ -46,21 +46,19 @@ include = [
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
ahash = { version = "0.8.11", default-features = false }
|
||||
anyhow = "1.0.86"
|
||||
clap = { version = "4.5.8", features = ["derive"] }
|
||||
crossterm = "0.27.0"
|
||||
hashbrown = "0.14.5"
|
||||
clap = { version = "4.5.14", features = ["derive"] }
|
||||
notify-debouncer-mini = { version = "0.4.1", default-features = false }
|
||||
os_pipe = "1.2.0"
|
||||
ratatui = { version = "0.27.0", default-features = false, features = ["crossterm"] }
|
||||
rustlings-macros = { path = "rustlings-macros", version = "=6.0.1" }
|
||||
serde_json = "1.0.120"
|
||||
os_pipe = "1.2.1"
|
||||
ratatui = { version = "0.28.0", default-features = false, features = ["crossterm"] }
|
||||
rustlings-macros = { path = "rustlings-macros", version = "=6.2.0" }
|
||||
serde_json = "1.0.122"
|
||||
serde.workspace = true
|
||||
toml_edit.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
assert_cmd = "2.0.14"
|
||||
predicates = "3.1.0"
|
||||
tempfile = "3.12.0"
|
||||
|
||||
[profile.release]
|
||||
panic = "abort"
|
||||
@@ -70,3 +68,7 @@ panic = "abort"
|
||||
|
||||
[package.metadata.release]
|
||||
pre-release-hook = ["./release-hook.sh"]
|
||||
|
||||
# TODO: Remove after the following fix is released: https://github.com/rust-lang/rust-clippy/pull/13102
|
||||
[lints.clippy]
|
||||
needless_option_as_deref = "allow"
|
||||
|
||||
23
README.md
23
README.md
@@ -17,9 +17,9 @@ It contains code examples and exercises similar to Rustlings, but online.
|
||||
|
||||
### Installing Rust
|
||||
|
||||
Before installing Rustlings, you need to have _Rust installed_.
|
||||
Before installing Rustlings, you need to have the **latest version of Rust** installed.
|
||||
Visit [www.rust-lang.org/tools/install](https://www.rust-lang.org/tools/install) for further instructions on installing Rust.
|
||||
This'll also install _Cargo_, Rust's package/project manager.
|
||||
This will also install _Cargo_, Rust's package/project manager.
|
||||
|
||||
> 🐧 If you're on Linux, make sure you've installed `gcc` (for a linker).
|
||||
>
|
||||
@@ -53,6 +53,21 @@ After installing Rustlings, run the following command to initialize the `rustlin
|
||||
rustlings init
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><strong>If the command <code>rustlings</code> can't be found…</strong> (<em>click to expand</em>)</summary>
|
||||
|
||||
You are probably using Linux and installed Rust using your package manager.
|
||||
|
||||
Cargo installs binaries to the directory `~/.cargo/bin`.
|
||||
Sadly, package managers often don't add `~/.cargo/bin` to your `PATH` environment variable.
|
||||
|
||||
The solution is to …
|
||||
|
||||
- either add `~/.cargo/bin` manually to `PATH`
|
||||
- or to uninstall Rust from the package manager and install it using the official way with `rustup`: https://www.rust-lang.org/tools/install
|
||||
|
||||
</details>
|
||||
|
||||
Now, go into the newly initialized directory and launch Rustlings for further instructions on getting started with the exercises:
|
||||
|
||||
```bash
|
||||
@@ -73,8 +88,6 @@ While working with Rustlings, please use a modern terminal for the best user exp
|
||||
The default terminal on Linux and Mac should be sufficient.
|
||||
On Windows, we recommend the [Windows Terminal](https://aka.ms/terminal).
|
||||
|
||||
If you use VS Code, the builtin terminal should also be fine.
|
||||
|
||||
## Doing exercises
|
||||
|
||||
The exercises are sorted by topic and can be found in the subdirectory `exercises/<topic>`.
|
||||
@@ -124,7 +137,7 @@ Continue practicing your Rust skills by building your own projects, contributing
|
||||
|
||||
Do you want to create your own set of Rustlings exercises to focus on some specific topic?
|
||||
Or do you want to translate the original Rustlings exercises?
|
||||
Then follow the link to the guide about [third-party exercises](THIRD_PARTY_EXERCISES.md)!
|
||||
Then follow the link to the guide about [third-party exercises](https://github.com/rust-lang/rustlings/blob/main/THIRD_PARTY_EXERCISES.md)!
|
||||
|
||||
## Uninstalling Rustlings
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Third-Party Exercises
|
||||
|
||||
The support of Rustlings for third-party exercises allows you to create your own set of Rustlings exercises to focus on some specific topic.
|
||||
You could also offer a translatation of the original Rustlings exercises as third-party exercises.
|
||||
You could also offer a translation of the original Rustlings exercises as third-party exercises.
|
||||
|
||||
## Getting started
|
||||
|
||||
|
||||
@@ -195,3 +195,9 @@ name = "exercises"
|
||||
edition = "2021"
|
||||
# Don't publish the exercises on crates.io!
|
||||
publish = false
|
||||
|
||||
[profile.release]
|
||||
panic = "abort"
|
||||
|
||||
[profile.dev]
|
||||
panic = "abort"
|
||||
|
||||
@@ -1 +1 @@
|
||||
This file is used to check if the user tries to run Rustlings in the repository (the method before v6)
|
||||
This file is used to check if the user tries to run Rustlings in the repository (the method before version 6)
|
||||
|
||||
@@ -5,5 +5,5 @@ compiler. In this section, we'll go through the most important ones.
|
||||
|
||||
## Further information
|
||||
|
||||
- [Data Types](https://doc.rust-lang.org/stable/book/ch03-02-data-types.html)
|
||||
- [The Slice Type](https://doc.rust-lang.org/stable/book/ch04-03-slices.html)
|
||||
- [Data Types](https://doc.rust-lang.org/book/ch03-02-data-types.html)
|
||||
- [The Slice Type](https://doc.rust-lang.org/book/ch04-03-slices.html)
|
||||
|
||||
@@ -12,6 +12,6 @@ the other useful data structure, hash maps, later.
|
||||
|
||||
## Further information
|
||||
|
||||
- [Storing Lists of Values with Vectors](https://doc.rust-lang.org/stable/book/ch08-01-vectors.html)
|
||||
- [Storing Lists of Values with Vectors](https://doc.rust-lang.org/book/ch08-01-vectors.html)
|
||||
- [`iter_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.iter_mut)
|
||||
- [`map`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map)
|
||||
|
||||
@@ -7,12 +7,12 @@ mod tests {
|
||||
// TODO: Fix the compiler errors only by reordering the lines in the test.
|
||||
// Don't add, change or remove any line.
|
||||
#[test]
|
||||
fn move_semantics5() {
|
||||
let mut x = 100;
|
||||
fn move_semantics4() {
|
||||
let mut x = Vec::new();
|
||||
let y = &mut x;
|
||||
let z = &mut x;
|
||||
*y += 100;
|
||||
*z += 1000;
|
||||
assert_eq!(x, 1200);
|
||||
y.push(42);
|
||||
z.push(13);
|
||||
assert_eq!(x, [42, 13]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,14 +3,6 @@
|
||||
// TODO: Fix the compiler errors without changing anything except adding or
|
||||
// removing references (the character `&`).
|
||||
|
||||
fn main() {
|
||||
let data = "Rust is great!".to_string();
|
||||
|
||||
get_char(data);
|
||||
|
||||
string_uppercase(&data);
|
||||
}
|
||||
|
||||
// Shouldn't take ownership
|
||||
fn get_char(data: String) -> char {
|
||||
data.chars().last().unwrap()
|
||||
@@ -22,3 +14,11 @@ fn string_uppercase(mut data: &String) {
|
||||
|
||||
println!("{data}");
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let data = "Rust is great!".to_string();
|
||||
|
||||
get_char(data);
|
||||
|
||||
string_uppercase(&data);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Structs contain data, but can also have logic. In this exercise we have
|
||||
// defined the `Package` struct and we want to test some logic attached to it.
|
||||
// Structs contain data, but can also have logic. In this exercise, we have
|
||||
// defined the `Package` struct, and we want to test some logic attached to it.
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Package {
|
||||
|
||||
@@ -4,8 +4,9 @@ enum Message {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{:?}", Message::Quit);
|
||||
println!("{:?}", Message::Echo);
|
||||
println!("{:?}", Message::Resize);
|
||||
println!("{:?}", Message::Move);
|
||||
println!("{:?}", Message::Echo);
|
||||
println!("{:?}", Message::ChangeColor);
|
||||
println!("{:?}", Message::Quit);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
#[allow(dead_code)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Point {
|
||||
x: u64,
|
||||
y: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Message {
|
||||
// TODO: Define the different variants used below.
|
||||
@@ -12,7 +19,11 @@ impl Message {
|
||||
|
||||
fn main() {
|
||||
let messages = [
|
||||
Message::Move { x: 10, y: 30 },
|
||||
Message::Resize {
|
||||
width: 10,
|
||||
height: 30,
|
||||
},
|
||||
Message::Move(Point { x: 10, y: 15 }),
|
||||
Message::Echo(String::from("hello world")),
|
||||
Message::ChangeColor(200, 255, 255),
|
||||
Message::Quit,
|
||||
|
||||
@@ -1,40 +1,47 @@
|
||||
struct Point {
|
||||
x: u64,
|
||||
y: u64,
|
||||
}
|
||||
|
||||
enum Message {
|
||||
// TODO: Implement the message variant types based on their usage below.
|
||||
}
|
||||
|
||||
struct Point {
|
||||
x: u8,
|
||||
y: u8,
|
||||
}
|
||||
|
||||
struct State {
|
||||
color: (u8, u8, u8),
|
||||
width: u64,
|
||||
height: u64,
|
||||
position: Point,
|
||||
quit: bool,
|
||||
message: String,
|
||||
// RGB color composed of red, green and blue.
|
||||
color: (u8, u8, u8),
|
||||
quit: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn change_color(&mut self, color: (u8, u8, u8)) {
|
||||
self.color = color;
|
||||
}
|
||||
|
||||
fn quit(&mut self) {
|
||||
self.quit = true;
|
||||
}
|
||||
|
||||
fn echo(&mut self, s: String) {
|
||||
self.message = s;
|
||||
fn resize(&mut self, width: u64, height: u64) {
|
||||
self.width = width;
|
||||
self.height = height;
|
||||
}
|
||||
|
||||
fn move_position(&mut self, point: Point) {
|
||||
self.position = point;
|
||||
}
|
||||
|
||||
fn echo(&mut self, s: String) {
|
||||
self.message = s;
|
||||
}
|
||||
|
||||
fn change_color(&mut self, red: u8, green: u8, blue: u8) {
|
||||
self.color = (red, green, blue);
|
||||
}
|
||||
|
||||
fn quit(&mut self) {
|
||||
self.quit = true;
|
||||
}
|
||||
|
||||
fn process(&mut self, message: Message) {
|
||||
// TODO: Create a match expression to process the different message variants.
|
||||
// Remember: When passing a tuple as a function argument, you'll need extra parentheses:
|
||||
// e.g. `foo((t, u, p, l, e))`
|
||||
// TODO: Create a match expression to process the different message
|
||||
// variants using the methods defined above.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,21 +56,29 @@ mod tests {
|
||||
#[test]
|
||||
fn test_match_message_call() {
|
||||
let mut state = State {
|
||||
quit: false,
|
||||
width: 0,
|
||||
height: 0,
|
||||
position: Point { x: 0, y: 0 },
|
||||
color: (0, 0, 0),
|
||||
message: String::from("hello world"),
|
||||
color: (0, 0, 0),
|
||||
quit: false,
|
||||
};
|
||||
|
||||
state.process(Message::ChangeColor(255, 0, 255));
|
||||
state.process(Message::Echo(String::from("Hello world!")));
|
||||
state.process(Message::Resize {
|
||||
width: 10,
|
||||
height: 30,
|
||||
});
|
||||
state.process(Message::Move(Point { x: 10, y: 15 }));
|
||||
state.process(Message::Echo(String::from("Hello world!")));
|
||||
state.process(Message::ChangeColor(255, 0, 255));
|
||||
state.process(Message::Quit);
|
||||
|
||||
assert_eq!(state.color, (255, 0, 255));
|
||||
assert_eq!(state.width, 10);
|
||||
assert_eq!(state.height, 30);
|
||||
assert_eq!(state.position.x, 10);
|
||||
assert_eq!(state.position.y, 15);
|
||||
assert!(state.quit);
|
||||
assert_eq!(state.message, "Hello world!");
|
||||
assert_eq!(state.color, (255, 0, 255));
|
||||
assert!(state.quit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ fn placeholder() {}
|
||||
fn string_slice(arg: &str) {
|
||||
println!("{arg}");
|
||||
}
|
||||
|
||||
fn string(arg: String) {
|
||||
println!("{arg}");
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
// Apple (4), Mango (2) and Lychee (5) are already in the basket hash map. You
|
||||
// must add fruit to the basket so that there is at least one of each kind and
|
||||
// more than 11 in total - we have a lot of mouths to feed. You are not allowed
|
||||
// to insert any more of these fruits!
|
||||
// to insert any more of the fruits that are already in the basket (Apple,
|
||||
// Mango, and Lychee).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
|
||||
@@ -10,12 +10,12 @@ use std::collections::HashMap;
|
||||
|
||||
// A structure to store the goal details of a team.
|
||||
#[derive(Default)]
|
||||
struct Team {
|
||||
struct TeamScores {
|
||||
goals_scored: u8,
|
||||
goals_conceded: u8,
|
||||
}
|
||||
|
||||
fn build_scores_table(results: &str) -> HashMap<&str, Team> {
|
||||
fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> {
|
||||
// The name of the team is the key and its associated struct is the value.
|
||||
let mut scores = HashMap::new();
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Option types are very common in Rust code, as they have a number of uses:
|
||||
|
||||
## Further Information
|
||||
|
||||
- [Option Enum Format](https://doc.rust-lang.org/stable/book/ch10-01-syntax.html#in-enum-definitions)
|
||||
- [Option Enum Format](https://doc.rust-lang.org/book/ch10-01-syntax.html#in-enum-definitions)
|
||||
- [Option Module Documentation](https://doc.rust-lang.org/std/option/)
|
||||
- [Option Enum Documentation](https://doc.rust-lang.org/std/option/enum.Option.html)
|
||||
- [if let](https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html)
|
||||
|
||||
@@ -19,6 +19,7 @@ fn main() {
|
||||
let mut tokens = 100;
|
||||
let pretend_user_input = "8";
|
||||
|
||||
// Don't change this line.
|
||||
let cost = total_cost(pretend_user_input)?;
|
||||
|
||||
if cost > tokens {
|
||||
|
||||
@@ -39,8 +39,8 @@ struct PositiveNonzeroInteger(u64);
|
||||
impl PositiveNonzeroInteger {
|
||||
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
|
||||
match value {
|
||||
0 => Err(CreationError::Zero),
|
||||
x if x < 0 => Err(CreationError::Negative),
|
||||
0 => Err(CreationError::Zero),
|
||||
x => Ok(PositiveNonzeroInteger(x as u64)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ impl ParsePosNonzeroError {
|
||||
}
|
||||
|
||||
// TODO: Add another error conversion function here.
|
||||
// fn from_parseint(???) -> Self { ??? }
|
||||
// fn from_parse_int(???) -> Self { ??? }
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
|
||||
@@ -7,5 +7,5 @@ The simplest and most common use of generics is for type parameters.
|
||||
|
||||
## Further information
|
||||
|
||||
- [Generic Data Types](https://doc.rust-lang.org/stable/book/ch10-01-syntax.html)
|
||||
- [Generic Data Types](https://doc.rust-lang.org/book/ch10-01-syntax.html)
|
||||
- [Bounds](https://doc.rust-lang.org/rust-by-example/generics/bounds.html)
|
||||
|
||||
@@ -9,7 +9,7 @@ impl Rectangle {
|
||||
if width <= 0 || height <= 0 {
|
||||
// Returning a `Result` would be better here. But we want to learn
|
||||
// how to test functions that can panic.
|
||||
panic!("Rectangle width and height can't be negative");
|
||||
panic!("Rectangle width and height must be positive");
|
||||
}
|
||||
|
||||
Rectangle { width, height }
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum DivisionError {
|
||||
// Example: 42 / 0
|
||||
DivideByZero,
|
||||
// Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1`
|
||||
IntegerOverflow,
|
||||
// Example: 5 / 2 = 2.5
|
||||
NotDivisible,
|
||||
}
|
||||
|
||||
// TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
|
||||
// Otherwise, return a suitable error.
|
||||
fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
|
||||
fn divide(a: i64, b: i64) -> Result<i64, DivisionError> {
|
||||
todo!();
|
||||
}
|
||||
|
||||
@@ -42,6 +46,11 @@ mod tests {
|
||||
assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_integer_overflow() {
|
||||
assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_not_divisible() {
|
||||
assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible));
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
fn factorial(num: u8) -> u64 {
|
||||
// TODO: Complete this function to return the factorial of `num`.
|
||||
fn factorial(num: u64) -> u64 {
|
||||
// TODO: Complete this function to return the factorial of `num` which is
|
||||
// defined as `1 * 2 * 3 * … * num`.
|
||||
// https://en.wikipedia.org/wiki/Factorial
|
||||
//
|
||||
// Do not use:
|
||||
// - early returns (using the `return` keyword explicitly)
|
||||
// Try not to use:
|
||||
|
||||
@@ -45,8 +45,9 @@ mod tests {
|
||||
#[test]
|
||||
fn owned_no_mutation() {
|
||||
// We can also pass `vec` without `&` so `Cow` owns it directly. In this
|
||||
// case, no mutation occurs and thus also no clone. But the result is
|
||||
// still owned because it was never borrowed or mutated.
|
||||
// case, no mutation occurs (all numbers are already absolute) and thus
|
||||
// also no clone. But the result is still owned because it was never
|
||||
// borrowed or mutated.
|
||||
let vec = vec![0, 1, 2];
|
||||
let mut input = Cow::from(vec);
|
||||
abs_all(&mut input);
|
||||
@@ -56,9 +57,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn owned_mutation() {
|
||||
// Of course this is also the case if a mutation does occur. In this
|
||||
// case, the call to `to_mut()` in the `abs_all` function returns a
|
||||
// reference to the same data as before.
|
||||
// Of course this is also the case if a mutation does occur (not all
|
||||
// numbers are absolute). In this case, the call to `to_mut()` in the
|
||||
// `abs_all` function returns a reference to the same data as before.
|
||||
let vec = vec![-1, 0, 1];
|
||||
let mut input = Cow::from(vec);
|
||||
abs_all(&mut input);
|
||||
|
||||
@@ -5,12 +5,12 @@
|
||||
//
|
||||
// Mary is buying apples. The price of an apple is calculated as follows:
|
||||
// - An apple costs 2 rustbucks.
|
||||
// - If Mary buys more than 40 apples, each apple only costs 1 rustbuck!
|
||||
// - However, if Mary buys more than 40 apples, the price of each apple in the
|
||||
// entire order is reduced to only 1 rustbuck!
|
||||
|
||||
// TODO: Write a function that calculates the price of an order of apples given
|
||||
// the quantity bought.
|
||||
|
||||
// Put your function here!
|
||||
// fn calculate_price_of_apples(???) -> ??? {
|
||||
// fn calculate_price_of_apples(???) -> ??? { ??? }
|
||||
|
||||
fn main() {
|
||||
// You can optionally experiment here.
|
||||
|
||||
@@ -26,7 +26,7 @@ enum Command {
|
||||
mod my_module {
|
||||
use super::Command;
|
||||
|
||||
// TODO: Complete the function.
|
||||
// TODO: Complete the function as described above.
|
||||
// pub fn transformer(input: ???) -> ??? { ??? }
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,11 @@
|
||||
# Error out if any command fails
|
||||
set -e
|
||||
|
||||
cargo run -- dev check
|
||||
typos
|
||||
cargo outdated -w --exit-code 1
|
||||
cargo upgrades
|
||||
|
||||
# Similar to CI
|
||||
cargo clippy -- --deny warnings
|
||||
cargo fmt --all --check
|
||||
cargo test --workspace --all-targets
|
||||
cargo run -- dev check --require-solutions
|
||||
|
||||
@@ -6,6 +6,7 @@ authors.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
include = [
|
||||
"/src/",
|
||||
"/info.toml",
|
||||
|
||||
@@ -31,6 +31,7 @@ https://github.com/rust-lang/rustlings/blob/main/CONTRIBUTING.md"""
|
||||
name = "intro1"
|
||||
dir = "00_intro"
|
||||
test = false
|
||||
skip_check_unsolved = true
|
||||
hint = """
|
||||
Enter `n` to move on to the next exercise.
|
||||
You might need to press ENTER after typing `n`."""
|
||||
@@ -308,7 +309,7 @@ In Rust, there are two ways to define a Vector.
|
||||
inside the square brackets. This way is simpler when you exactly know
|
||||
the initial values.
|
||||
|
||||
Check this chapter: https://doc.rust-lang.org/stable/book/ch08-01-vectors.html
|
||||
Check this chapter: https://doc.rust-lang.org/book/ch08-01-vectors.html
|
||||
of the Rust book to learn more."""
|
||||
|
||||
[[exercises]]
|
||||
@@ -350,7 +351,7 @@ We call this "moving" a variable. When we pass `vec0` into `fill_vec`, it's
|
||||
being "moved" into `vec1`, meaning we can't access `vec0` anymore.
|
||||
|
||||
You could make another, separate version of the data that's in `vec0` and
|
||||
pass it to `fill_vec` instead."""
|
||||
pass it to `fill_vec` instead. This is called cloning in Rust."""
|
||||
|
||||
[[exercises]]
|
||||
name = "move_semantics3"
|
||||
@@ -377,7 +378,7 @@ dir = "06_move_semantics"
|
||||
test = false
|
||||
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
|
||||
https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
|
||||
|
||||
The first problem is that `get_char` is taking ownership of the string. So
|
||||
`data` is moved and can't be used for `string_uppercase`. `data` is moved to
|
||||
@@ -415,7 +416,7 @@ to its fields.
|
||||
|
||||
There are however some shortcuts that can be taken when instantiating structs.
|
||||
Have a look in The Book to find out more:
|
||||
https://doc.rust-lang.org/stable/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax"""
|
||||
https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax"""
|
||||
|
||||
[[exercises]]
|
||||
name = "structs3"
|
||||
@@ -444,7 +445,7 @@ dir = "08_enums"
|
||||
test = false
|
||||
hint = """
|
||||
You can create enumerations that have different variants with different types
|
||||
such as no data, anonymous structs, a single string, tuples, etc."""
|
||||
such as anonymous structs, structs, a single string, tuples, no data, etc."""
|
||||
|
||||
[[exercises]]
|
||||
name = "enums3"
|
||||
@@ -486,7 +487,7 @@ to add one character to the `if` statement, though, that will coerce the
|
||||
Side note: If you're interested in learning about how this kind of reference
|
||||
conversion works, you can jump ahead in the book and read this part in the
|
||||
smart pointers chapter:
|
||||
https://doc.rust-lang.org/stable/book/ch15-02-deref.html#implicit-deref-coercions-with-functions-and-methods"""
|
||||
https://doc.rust-lang.org/book/ch15-02-deref.html#implicit-deref-coercions-with-functions-and-methods"""
|
||||
|
||||
[[exercises]]
|
||||
name = "strings3"
|
||||
@@ -497,7 +498,10 @@ some of them:
|
||||
https://doc.rust-lang.org/std/string/struct.String.html#method.trim
|
||||
|
||||
For the `compose_me` method: You can either use the `format!` macro, or convert
|
||||
the string slice into an owned string, which you can then freely extend."""
|
||||
the string slice into an owned string, which you can then freely extend.
|
||||
|
||||
For the `replace_me` method, you can check out the `replace` method:
|
||||
https://doc.rust-lang.org/std/string/struct.String.html#method.replace"""
|
||||
|
||||
[[exercises]]
|
||||
name = "strings4"
|
||||
@@ -560,18 +564,18 @@ hint = """
|
||||
Use the `entry()` and `or_insert()` methods of `HashMap` to achieve this.
|
||||
|
||||
Learn more in The Book:
|
||||
https://doc.rust-lang.org/stable/book/ch08-03-hash-maps.html#only-inserting-a-value-if-the-key-has-no-value"""
|
||||
https://doc.rust-lang.org/book/ch08-03-hash-maps.html#only-inserting-a-value-if-the-key-has-no-value"""
|
||||
|
||||
[[exercises]]
|
||||
name = "hashmaps3"
|
||||
dir = "11_hashmaps"
|
||||
hint = """
|
||||
Hint 1: Use the `entry()` and `or_insert()` (or `or_insert_with()`) methods of
|
||||
`HashMap` to insert the default value of `Team` if a team doesn't
|
||||
`HashMap` to insert the default value of `TeamScores` if a team doesn't
|
||||
exist in the table yet.
|
||||
|
||||
Learn more in The Book:
|
||||
https://doc.rust-lang.org/stable/book/ch08-03-hash-maps.html#only-inserting-a-value-if-the-key-has-no-value
|
||||
https://doc.rust-lang.org/book/ch08-03-hash-maps.html#only-inserting-a-value-if-the-key-has-no-value
|
||||
|
||||
Hint 2: If there is already an entry for a given key, the value returned by
|
||||
`entry()` can be updated based on the existing value.
|
||||
@@ -584,7 +588,7 @@ https://doc.rust-lang.org/book/ch08-03-hash-maps.html#updating-a-value-based-on-
|
||||
[[exercises]]
|
||||
name = "quiz2"
|
||||
dir = "quizzes"
|
||||
hint = "No hints this time ;)"
|
||||
hint = "The `+` operator can concatenate a `String` with a `&str`."
|
||||
|
||||
# OPTIONS
|
||||
|
||||
@@ -738,7 +742,7 @@ name = "generics2"
|
||||
dir = "14_generics"
|
||||
hint = """
|
||||
Related section in The Book:
|
||||
https://doc.rust-lang.org/stable/book/ch10-01-syntax.html#in-method-definitions"""
|
||||
https://doc.rust-lang.org/book/ch10-01-syntax.html#in-method-definitions"""
|
||||
|
||||
# TRAITS
|
||||
|
||||
@@ -747,7 +751,9 @@ name = "traits1"
|
||||
dir = "15_traits"
|
||||
hint = """
|
||||
More about traits in The Book:
|
||||
https://doc.rust-lang.org/book/ch10-02-traits.html"""
|
||||
https://doc.rust-lang.org/book/ch10-02-traits.html
|
||||
|
||||
The `+` operator can concatenate a `String` with a `&str`."""
|
||||
|
||||
[[exercises]]
|
||||
name = "traits2"
|
||||
@@ -868,7 +874,7 @@ We expect the method `Rectangle::new` to panic for negative values.
|
||||
To handle that, you need to add a special attribute to the test function.
|
||||
|
||||
You can refer to the docs:
|
||||
https://doc.rust-lang.org/stable/book/ch11-01-writing-tests.html#checking-for-panics-with-should_panic"""
|
||||
https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-for-panics-with-should_panic"""
|
||||
|
||||
# STANDARD LIBRARY TYPES
|
||||
|
||||
@@ -887,9 +893,9 @@ hint = """
|
||||
`capitalize_first`:
|
||||
|
||||
The variable `first` is a `char`. It needs to be capitalized and added to the
|
||||
remaining characters in `c` in order to return the correct `String`.
|
||||
remaining characters in `chars` in order to return the correct `String`.
|
||||
|
||||
The remaining characters in `c` can be viewed as a string slice using the
|
||||
The remaining characters in `chars` can be viewed as a string slice using the
|
||||
`as_str` method.
|
||||
|
||||
The documentation for `char` contains many useful methods.
|
||||
@@ -1004,7 +1010,7 @@ thread-local copy of the numbers.
|
||||
This is a simple exercise if you understand the underlying concepts, but if this
|
||||
is too much of a struggle, consider reading through all of Chapter 16 in The
|
||||
Book:
|
||||
https://doc.rust-lang.org/stable/book/ch16-00-concurrency.html"""
|
||||
https://doc.rust-lang.org/book/ch16-00-concurrency.html"""
|
||||
|
||||
[[exercises]]
|
||||
name = "cow1"
|
||||
@@ -1142,7 +1148,11 @@ test = false
|
||||
strict_clippy = true
|
||||
hint = """
|
||||
`for` loops over `Option` values are more clearly expressed as an `if-let`
|
||||
statement."""
|
||||
statement.
|
||||
|
||||
Not required to solve this exercise, but if you are interested in when iterating
|
||||
over `Option` can be useful, read the following section in the documentation:
|
||||
https://doc.rust-lang.org/std/option/#iterating-over-option"""
|
||||
|
||||
[[exercises]]
|
||||
name = "clippy3"
|
||||
|
||||
@@ -7,15 +7,15 @@ mod tests {
|
||||
// TODO: Fix the compiler errors only by reordering the lines in the test.
|
||||
// Don't add, change or remove any line.
|
||||
#[test]
|
||||
fn move_semantics5() {
|
||||
let mut x = 100;
|
||||
fn move_semantics4() {
|
||||
let mut x = Vec::new();
|
||||
let y = &mut x;
|
||||
// `y` used here.
|
||||
*y += 100;
|
||||
y.push(42);
|
||||
// The mutable reference `y` is not used anymore,
|
||||
// therefore a new reference can be created.
|
||||
let z = &mut x;
|
||||
*z += 1000;
|
||||
assert_eq!(x, 1200);
|
||||
z.push(13);
|
||||
assert_eq!(x, [42, 13]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
#![allow(clippy::ptr_arg)]
|
||||
|
||||
fn main() {
|
||||
let data = "Rust is great!".to_string();
|
||||
|
||||
get_char(&data);
|
||||
|
||||
string_uppercase(data);
|
||||
}
|
||||
|
||||
// Borrows instead of taking ownership.
|
||||
// It is recommended to use `&str` instead of `&String` here. But this is
|
||||
// enough for now because we didn't handle strings yet.
|
||||
@@ -21,3 +13,11 @@ fn string_uppercase(mut data: String) {
|
||||
|
||||
println!("{data}");
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let data = "Rust is great!".to_string();
|
||||
|
||||
get_char(&data);
|
||||
|
||||
string_uppercase(data);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
#[derive(Debug)]
|
||||
enum Message {
|
||||
Quit,
|
||||
Echo,
|
||||
Resize,
|
||||
Move,
|
||||
Echo,
|
||||
ChangeColor,
|
||||
Quit,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{:?}", Message::Quit);
|
||||
println!("{:?}", Message::Echo);
|
||||
println!("{:?}", Message::Resize);
|
||||
println!("{:?}", Message::Move);
|
||||
println!("{:?}", Message::Echo);
|
||||
println!("{:?}", Message::ChangeColor);
|
||||
println!("{:?}", Message::Quit);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
#[allow(dead_code)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Point {
|
||||
x: u64,
|
||||
y: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Message {
|
||||
Move { x: i64, y: i64 },
|
||||
Resize { width: u64, height: u64 },
|
||||
Move(Point),
|
||||
Echo(String),
|
||||
ChangeColor(u8, u8, u8),
|
||||
Quit,
|
||||
@@ -15,7 +23,11 @@ impl Message {
|
||||
|
||||
fn main() {
|
||||
let messages = [
|
||||
Message::Move { x: 10, y: 30 },
|
||||
Message::Resize {
|
||||
width: 10,
|
||||
height: 30,
|
||||
},
|
||||
Message::Move(Point { x: 10, y: 15 }),
|
||||
Message::Echo(String::from("hello world")),
|
||||
Message::ChangeColor(200, 255, 255),
|
||||
Message::Quit,
|
||||
|
||||
@@ -1,44 +1,53 @@
|
||||
struct Point {
|
||||
x: u64,
|
||||
y: u64,
|
||||
}
|
||||
|
||||
enum Message {
|
||||
ChangeColor(u8, u8, u8),
|
||||
Echo(String),
|
||||
Resize { width: u64, height: u64 },
|
||||
Move(Point),
|
||||
Echo(String),
|
||||
ChangeColor(u8, u8, u8),
|
||||
Quit,
|
||||
}
|
||||
|
||||
struct Point {
|
||||
x: u8,
|
||||
y: u8,
|
||||
}
|
||||
|
||||
struct State {
|
||||
color: (u8, u8, u8),
|
||||
width: u64,
|
||||
height: u64,
|
||||
position: Point,
|
||||
quit: bool,
|
||||
message: String,
|
||||
color: (u8, u8, u8),
|
||||
quit: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn change_color(&mut self, color: (u8, u8, u8)) {
|
||||
self.color = color;
|
||||
}
|
||||
|
||||
fn quit(&mut self) {
|
||||
self.quit = true;
|
||||
}
|
||||
|
||||
fn echo(&mut self, s: String) {
|
||||
self.message = s;
|
||||
fn resize(&mut self, width: u64, height: u64) {
|
||||
self.width = width;
|
||||
self.height = height;
|
||||
}
|
||||
|
||||
fn move_position(&mut self, point: Point) {
|
||||
self.position = point;
|
||||
}
|
||||
|
||||
fn echo(&mut self, s: String) {
|
||||
self.message = s;
|
||||
}
|
||||
|
||||
fn change_color(&mut self, red: u8, green: u8, blue: u8) {
|
||||
self.color = (red, green, blue);
|
||||
}
|
||||
|
||||
fn quit(&mut self) {
|
||||
self.quit = true;
|
||||
}
|
||||
|
||||
fn process(&mut self, message: Message) {
|
||||
match message {
|
||||
Message::ChangeColor(r, g, b) => self.change_color((r, g, b)),
|
||||
Message::Echo(s) => self.echo(s),
|
||||
Message::Resize { width, height } => self.resize(width, height),
|
||||
Message::Move(point) => self.move_position(point),
|
||||
Message::Echo(s) => self.echo(s),
|
||||
Message::ChangeColor(r, g, b) => self.change_color(r, g, b),
|
||||
Message::Quit => self.quit(),
|
||||
}
|
||||
}
|
||||
@@ -55,21 +64,29 @@ mod tests {
|
||||
#[test]
|
||||
fn test_match_message_call() {
|
||||
let mut state = State {
|
||||
quit: false,
|
||||
width: 0,
|
||||
height: 0,
|
||||
position: Point { x: 0, y: 0 },
|
||||
color: (0, 0, 0),
|
||||
message: String::from("hello world"),
|
||||
color: (0, 0, 0),
|
||||
quit: false,
|
||||
};
|
||||
|
||||
state.process(Message::ChangeColor(255, 0, 255));
|
||||
state.process(Message::Echo(String::from("Hello world!")));
|
||||
state.process(Message::Resize {
|
||||
width: 10,
|
||||
height: 30,
|
||||
});
|
||||
state.process(Message::Move(Point { x: 10, y: 15 }));
|
||||
state.process(Message::Echo(String::from("Hello world!")));
|
||||
state.process(Message::ChangeColor(255, 0, 255));
|
||||
state.process(Message::Quit);
|
||||
|
||||
assert_eq!(state.color, (255, 0, 255));
|
||||
assert_eq!(state.width, 10);
|
||||
assert_eq!(state.height, 30);
|
||||
assert_eq!(state.position.x, 10);
|
||||
assert_eq!(state.position.y, 15);
|
||||
assert!(state.quit);
|
||||
assert_eq!(state.message, "Hello world!");
|
||||
assert_eq!(state.color, (255, 0, 255));
|
||||
assert!(state.quit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
fn string_slice(arg: &str) {
|
||||
println!("{arg}");
|
||||
}
|
||||
|
||||
fn string(arg: String) {
|
||||
println!("{arg}");
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
// Apple (4), Mango (2) and Lychee (5) are already in the basket hash map. You
|
||||
// must add fruit to the basket so that there is at least one of each kind and
|
||||
// more than 11 in total - we have a lot of mouths to feed. You are not allowed
|
||||
// to insert any more of these fruits!
|
||||
// to insert any more of the fruits that are already in the basket (Apple,
|
||||
// Mango, and Lychee).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
|
||||
@@ -10,12 +10,12 @@ use std::collections::HashMap;
|
||||
|
||||
// A structure to store the goal details of a team.
|
||||
#[derive(Default)]
|
||||
struct Team {
|
||||
struct TeamScores {
|
||||
goals_scored: u8,
|
||||
goals_conceded: u8,
|
||||
}
|
||||
|
||||
fn build_scores_table(results: &str) -> HashMap<&str, Team> {
|
||||
fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> {
|
||||
// The name of the team is the key and its associated struct is the value.
|
||||
let mut scores = HashMap::new();
|
||||
|
||||
@@ -28,13 +28,17 @@ fn build_scores_table(results: &str) -> HashMap<&str, Team> {
|
||||
let team_2_score: u8 = split_iterator.next().unwrap().parse().unwrap();
|
||||
|
||||
// Insert the default with zeros if a team doesn't exist yet.
|
||||
let team_1 = scores.entry(team_1_name).or_insert_with(Team::default);
|
||||
let team_1 = scores
|
||||
.entry(team_1_name)
|
||||
.or_insert_with(TeamScores::default);
|
||||
// Update the values.
|
||||
team_1.goals_scored += team_1_score;
|
||||
team_1.goals_conceded += team_2_score;
|
||||
|
||||
// Similarely for the second team.
|
||||
let team_2 = scores.entry(team_2_name).or_insert_with(Team::default);
|
||||
let team_2 = scores
|
||||
.entry(team_2_name)
|
||||
.or_insert_with(TeamScores::default);
|
||||
team_2.goals_scored += team_2_score;
|
||||
team_2.goals_conceded += team_1_score;
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ impl ParsePosNonzeroError {
|
||||
Self::Creation(err)
|
||||
}
|
||||
|
||||
fn from_parseint(err: ParseIntError) -> Self {
|
||||
fn from_parse_int(err: ParseIntError) -> Self {
|
||||
Self::ParseInt(err)
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ impl PositiveNonzeroInteger {
|
||||
fn parse(s: &str) -> Result<Self, ParsePosNonzeroError> {
|
||||
// Return an appropriate error instead of panicking when `parse()`
|
||||
// returns an error.
|
||||
let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parseint)?;
|
||||
let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parse_int)?;
|
||||
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
Self::new(x).map_err(ParsePosNonzeroError::from_creation)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ impl Rectangle {
|
||||
if width <= 0 || height <= 0 {
|
||||
// Returning a `Result` would be better here. But we want to learn
|
||||
// how to test functions that can panic.
|
||||
panic!("Rectangle width and height can't be negative");
|
||||
panic!("Rectangle width and height must be positive");
|
||||
}
|
||||
|
||||
Rectangle { width, height }
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum DivisionError {
|
||||
// Example: 42 / 0
|
||||
DivideByZero,
|
||||
// Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1`
|
||||
IntegerOverflow,
|
||||
// Example: 5 / 2 = 2.5
|
||||
NotDivisible,
|
||||
}
|
||||
|
||||
@@ -9,6 +13,10 @@ fn divide(a: i64, b: i64) -> Result<i64, DivisionError> {
|
||||
return Err(DivisionError::DivideByZero);
|
||||
}
|
||||
|
||||
if a == i64::MIN && b == -1 {
|
||||
return Err(DivisionError::IntegerOverflow);
|
||||
}
|
||||
|
||||
if a % b != 0 {
|
||||
return Err(DivisionError::NotDivisible);
|
||||
}
|
||||
@@ -51,6 +59,11 @@ mod tests {
|
||||
assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_integer_overflow() {
|
||||
assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_not_divisible() {
|
||||
assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible));
|
||||
|
||||
@@ -47,6 +47,23 @@ fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Pr
|
||||
.sum()
|
||||
}
|
||||
|
||||
// Equivalent to `count_collection_iterator` and `count_iterator`, iterating as
|
||||
// if the collection was a single container instead of a container of containers
|
||||
// (and more accurately, a single iterator instead of an iterator of iterators).
|
||||
fn count_collection_iterator_flat(
|
||||
collection: &[HashMap<String, Progress>],
|
||||
value: Progress,
|
||||
) -> usize {
|
||||
// `collection` is a slice of hash maps.
|
||||
// collection = [{ "variables1": Complete, "from_str": None, … },
|
||||
// { "variables2": Complete, … }, … ]
|
||||
collection
|
||||
.iter()
|
||||
.flat_map(HashMap::values) // or just `.flatten()` when wanting the default iterator (`HashMap::iter`)
|
||||
.filter(|val| **val == value)
|
||||
.count()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// You can optionally experiment here.
|
||||
}
|
||||
@@ -54,10 +71,9 @@ fn main() {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use Progress::*;
|
||||
|
||||
fn get_map() -> HashMap<String, Progress> {
|
||||
use Progress::*;
|
||||
|
||||
let mut map = HashMap::new();
|
||||
map.insert(String::from("variables1"), Complete);
|
||||
map.insert(String::from("functions1"), Complete);
|
||||
@@ -70,8 +86,6 @@ mod tests {
|
||||
}
|
||||
|
||||
fn get_vec_map() -> Vec<HashMap<String, Progress>> {
|
||||
use Progress::*;
|
||||
|
||||
let map = get_map();
|
||||
|
||||
let mut other = HashMap::new();
|
||||
@@ -87,25 +101,25 @@ mod tests {
|
||||
#[test]
|
||||
fn count_complete() {
|
||||
let map = get_map();
|
||||
assert_eq!(count_iterator(&map, Progress::Complete), 3);
|
||||
assert_eq!(count_iterator(&map, Complete), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_some() {
|
||||
let map = get_map();
|
||||
assert_eq!(count_iterator(&map, Progress::Some), 1);
|
||||
assert_eq!(count_iterator(&map, Some), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_none() {
|
||||
let map = get_map();
|
||||
assert_eq!(count_iterator(&map, Progress::None), 2);
|
||||
assert_eq!(count_iterator(&map, None), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_complete_equals_for() {
|
||||
let map = get_map();
|
||||
let progress_states = [Progress::Complete, Progress::Some, Progress::None];
|
||||
let progress_states = [Complete, Some, None];
|
||||
for progress_state in progress_states {
|
||||
assert_eq!(
|
||||
count_for(&map, progress_state),
|
||||
@@ -117,34 +131,38 @@ mod tests {
|
||||
#[test]
|
||||
fn count_collection_complete() {
|
||||
let collection = get_vec_map();
|
||||
assert_eq!(
|
||||
count_collection_iterator(&collection, Progress::Complete),
|
||||
6,
|
||||
);
|
||||
assert_eq!(count_collection_iterator(&collection, Complete), 6);
|
||||
assert_eq!(count_collection_iterator_flat(&collection, Complete), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_collection_some() {
|
||||
let collection = get_vec_map();
|
||||
assert_eq!(count_collection_iterator(&collection, Progress::Some), 1);
|
||||
assert_eq!(count_collection_iterator(&collection, Some), 1);
|
||||
assert_eq!(count_collection_iterator_flat(&collection, Some), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_collection_none() {
|
||||
let collection = get_vec_map();
|
||||
assert_eq!(count_collection_iterator(&collection, Progress::None), 4);
|
||||
assert_eq!(count_collection_iterator(&collection, None), 4);
|
||||
assert_eq!(count_collection_iterator_flat(&collection, None), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_collection_equals_for() {
|
||||
let collection = get_vec_map();
|
||||
let progress_states = [Progress::Complete, Progress::Some, Progress::None];
|
||||
let progress_states = [Complete, Some, None];
|
||||
|
||||
for progress_state in progress_states {
|
||||
assert_eq!(
|
||||
count_collection_for(&collection, progress_state),
|
||||
count_collection_iterator(&collection, progress_state),
|
||||
);
|
||||
assert_eq!(
|
||||
count_collection_for(&collection, progress_state),
|
||||
count_collection_iterator_flat(&collection, progress_state),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,8 +45,9 @@ mod tests {
|
||||
#[test]
|
||||
fn owned_no_mutation() {
|
||||
// We can also pass `vec` without `&` so `Cow` owns it directly. In this
|
||||
// case, no mutation occurs and thus also no clone. But the result is
|
||||
// still owned because it was never borrowed or mutated.
|
||||
// case, no mutation occurs (all numbers are already absolute) and thus
|
||||
// also no clone. But the result is still owned because it was never
|
||||
// borrowed or mutated.
|
||||
let vec = vec![0, 1, 2];
|
||||
let mut input = Cow::from(vec);
|
||||
abs_all(&mut input);
|
||||
@@ -56,9 +57,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn owned_mutation() {
|
||||
// Of course this is also the case if a mutation does occur. In this
|
||||
// case, the call to `to_mut()` in the `abs_all` function returns a
|
||||
// reference to the same data as before.
|
||||
// Of course this is also the case if a mutation does occur (not all
|
||||
// numbers are absolute). In this case, the call to `to_mut()` in the
|
||||
// `abs_all` function returns a reference to the same data as before.
|
||||
let vec = vec![-1, 0, 1];
|
||||
let mut input = Cow::from(vec);
|
||||
abs_all(&mut input);
|
||||
|
||||
@@ -15,7 +15,7 @@ fn char_counter<T: AsRef<str>>(arg: T) -> usize {
|
||||
// Squares a number using `as_mut()`.
|
||||
fn num_sq<T: AsMut<u32>>(arg: &mut T) {
|
||||
let arg = arg.as_mut();
|
||||
*arg = *arg * *arg;
|
||||
*arg *= *arg;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
|
||||
6
solutions/README.md
Normal file
6
solutions/README.md
Normal file
@@ -0,0 +1,6 @@
|
||||
# Official Rustlings solutions
|
||||
|
||||
Before you finish an exercise, its solution file will only contain an empty `main` function.
|
||||
The content of this file will be automatically replaced by the actual solution once you finish the exercise.
|
||||
|
||||
Note that these solution are often only _one possibility_ to solve an exercise.
|
||||
@@ -1,8 +1,7 @@
|
||||
// Mary is buying apples. The price of an apple is calculated as follows:
|
||||
// - An apple costs 2 rustbucks.
|
||||
// - If Mary buys more than 40 apples, each apple only costs 1 rustbuck!
|
||||
// Write a function that calculates the price of an order of apples given the
|
||||
// quantity bought.
|
||||
// - However, if Mary buys more than 40 apples, the price of each apple in the
|
||||
// entire order is reduced to only 1 rustbuck!
|
||||
|
||||
fn calculate_price_of_apples(n_apples: u64) -> u64 {
|
||||
if n_apples > 40 {
|
||||
|
||||
@@ -1,10 +1,3 @@
|
||||
// This is a quiz for the following sections:
|
||||
// - Strings
|
||||
// - Vecs
|
||||
// - Move semantics
|
||||
// - Modules
|
||||
// - Enums
|
||||
//
|
||||
// Let's build a little machine in the form of a function. As input, we're going
|
||||
// to give a list of strings and commands. These commands determine what action
|
||||
// is going to be applied to the string. It can either be:
|
||||
@@ -13,7 +6,7 @@
|
||||
// - Append "bar" to the string a specified amount of times
|
||||
//
|
||||
// The exact form of this will be:
|
||||
// - The input is going to be a vector of a 2-length tuple,
|
||||
// - The input is going to be a vector of 2-length tuples,
|
||||
// the first element is the string, the second one is the command.
|
||||
// - The output element is going to be a vector of strings.
|
||||
|
||||
@@ -31,17 +24,12 @@ mod my_module {
|
||||
pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {
|
||||
let mut output = Vec::new();
|
||||
|
||||
for (mut string, command) in input {
|
||||
for (string, command) in input {
|
||||
// Create the new string.
|
||||
let new_string = match command {
|
||||
Command::Uppercase => string.to_uppercase(),
|
||||
Command::Trim => string.trim().to_string(),
|
||||
Command::Append(n) => {
|
||||
for _ in 0..n {
|
||||
string += "bar";
|
||||
}
|
||||
string
|
||||
}
|
||||
Command::Append(n) => string + &"bar".repeat(n),
|
||||
};
|
||||
|
||||
// Push the new string to the output vector.
|
||||
@@ -56,15 +44,10 @@ mod my_module {
|
||||
pub fn transformer_iter(input: Vec<(String, Command)>) -> Vec<String> {
|
||||
input
|
||||
.into_iter()
|
||||
.map(|(mut string, command)| match command {
|
||||
.map(|(string, command)| match command {
|
||||
Command::Uppercase => string.to_uppercase(),
|
||||
Command::Trim => string.trim().to_string(),
|
||||
Command::Append(n) => {
|
||||
for _ in 0..n {
|
||||
string += "bar";
|
||||
}
|
||||
string
|
||||
}
|
||||
Command::Append(n) => string + &"bar".repeat(n),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
// This quiz tests:
|
||||
// - Generics
|
||||
// - Traits
|
||||
//
|
||||
// An imaginary magical school has a new report card generation system written
|
||||
// in Rust! Currently, the system only supports creating report cards where the
|
||||
// student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the
|
||||
|
||||
120
src/app_state.rs
120
src/app_state.rs
@@ -1,19 +1,19 @@
|
||||
use anyhow::{bail, Context, Result};
|
||||
use crossterm::style::Stylize;
|
||||
use serde::Deserialize;
|
||||
use anyhow::{bail, Context, Error, Result};
|
||||
use std::{
|
||||
fs::{self, File},
|
||||
io::{Read, StdoutLock, Write},
|
||||
path::{Path, PathBuf},
|
||||
path::Path,
|
||||
process::{Command, Stdio},
|
||||
thread,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
clear_terminal,
|
||||
cmd::CmdRunner,
|
||||
collections::hash_set_with_capacity,
|
||||
embedded::EMBEDDED_FILES,
|
||||
exercise::{Exercise, RunnableExercise, OUTPUT_CAPACITY},
|
||||
exercise::{Exercise, RunnableExercise},
|
||||
info_file::ExerciseInfo,
|
||||
DEBUG_PROFILE,
|
||||
};
|
||||
|
||||
const STATE_FILE_NAME: &str = ".rustlings-state.txt";
|
||||
@@ -34,31 +34,6 @@ pub enum StateFileStatus {
|
||||
NotRead,
|
||||
}
|
||||
|
||||
// Parses parts of the output of `cargo metadata`.
|
||||
#[derive(Deserialize)]
|
||||
struct CargoMetadata {
|
||||
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 {
|
||||
current_exercise_ind: usize,
|
||||
exercises: Vec<Exercise>,
|
||||
@@ -68,8 +43,7 @@ pub struct AppState {
|
||||
// Preallocated buffer for reading and writing the state file.
|
||||
file_buf: Vec<u8>,
|
||||
official_exercises: bool,
|
||||
// Cargo's target directory.
|
||||
target_dir: PathBuf,
|
||||
cmd_runner: CmdRunner,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -96,7 +70,7 @@ impl AppState {
|
||||
return StateFileStatus::NotRead;
|
||||
}
|
||||
|
||||
let mut done_exercises = hashbrown::HashSet::with_capacity(self.exercises.len());
|
||||
let mut done_exercises = hash_set_with_capacity(self.exercises.len());
|
||||
|
||||
for done_exerise_name in lines {
|
||||
if done_exerise_name.is_empty() {
|
||||
@@ -123,7 +97,7 @@ impl AppState {
|
||||
exercise_infos: Vec<ExerciseInfo>,
|
||||
final_message: String,
|
||||
) -> Result<(Self, StateFileStatus)> {
|
||||
let target_dir = parse_target_dir()?;
|
||||
let cmd_runner = CmdRunner::build()?;
|
||||
|
||||
let exercises = exercise_infos
|
||||
.into_iter()
|
||||
@@ -134,8 +108,7 @@ impl AppState {
|
||||
let path = exercise_info.path().leak();
|
||||
let name = exercise_info.name.leak();
|
||||
let dir = exercise_info.dir.map(|dir| &*dir.leak());
|
||||
|
||||
let hint = exercise_info.hint.trim().to_owned();
|
||||
let hint = exercise_info.hint.leak().trim_ascii();
|
||||
|
||||
Exercise {
|
||||
dir,
|
||||
@@ -157,7 +130,7 @@ impl AppState {
|
||||
final_message,
|
||||
file_buf: Vec::with_capacity(2048),
|
||||
official_exercises: !Path::new("info.toml").exists(),
|
||||
target_dir,
|
||||
cmd_runner,
|
||||
};
|
||||
|
||||
let state_file_status = slf.update_from_file();
|
||||
@@ -186,8 +159,8 @@ impl AppState {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn target_dir(&self) -> &Path {
|
||||
&self.target_dir
|
||||
pub fn cmd_runner(&self) -> &CmdRunner {
|
||||
&self.cmd_runner
|
||||
}
|
||||
|
||||
// Write the state file.
|
||||
@@ -336,7 +309,7 @@ impl AppState {
|
||||
/// Official exercises: Dump the solution file form the binary and return its path.
|
||||
/// Third-party exercises: Check if a solution file exists and return its path in that case.
|
||||
pub fn current_solution_path(&self) -> Result<Option<String>> {
|
||||
if DEBUG_PROFILE {
|
||||
if cfg!(debug_assertions) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
@@ -373,40 +346,58 @@ impl AppState {
|
||||
|
||||
if let Some(ind) = self.next_pending_exercise_ind() {
|
||||
self.set_current_exercise_ind(ind)?;
|
||||
|
||||
return Ok(ExercisesProgress::NewPending);
|
||||
}
|
||||
|
||||
writer.write_all(RERUNNING_ALL_EXERCISES_MSG)?;
|
||||
|
||||
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
|
||||
for (exercise_ind, exercise) in self.exercises().iter().enumerate() {
|
||||
write!(writer, "Running {exercise} ... ")?;
|
||||
writer.flush()?;
|
||||
let n_exercises = self.exercises.len();
|
||||
|
||||
let success = exercise.run_exercise(&mut output, &self.target_dir)?;
|
||||
if !success {
|
||||
writeln!(writer, "{}\n", "FAILED".red())?;
|
||||
let pending_exercise_ind = thread::scope(|s| {
|
||||
let handles = self
|
||||
.exercises
|
||||
.iter_mut()
|
||||
.map(|exercise| {
|
||||
s.spawn(|| {
|
||||
let success = exercise.run_exercise(None, &self.cmd_runner)?;
|
||||
exercise.done = success;
|
||||
Ok::<_, Error>(success)
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
self.current_exercise_ind = exercise_ind;
|
||||
for (exercise_ind, handle) in handles.into_iter().enumerate() {
|
||||
write!(writer, "\rProgress: {exercise_ind}/{n_exercises}")?;
|
||||
writer.flush()?;
|
||||
|
||||
// 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.n_done -= 1;
|
||||
|
||||
self.write()?;
|
||||
|
||||
return Ok(ExercisesProgress::NewPending);
|
||||
let success = handle.join().unwrap()?;
|
||||
if !success {
|
||||
writer.write_all(b"\n\n")?;
|
||||
return Ok(Some(exercise_ind));
|
||||
}
|
||||
}
|
||||
|
||||
writeln!(writer, "{}", "ok".green())?;
|
||||
Ok::<_, Error>(None)
|
||||
})?;
|
||||
|
||||
if let Some(pending_exercise_ind) = pending_exercise_ind {
|
||||
self.current_exercise_ind = pending_exercise_ind;
|
||||
self.n_done = self
|
||||
.exercises
|
||||
.iter()
|
||||
.filter(|exercise| exercise.done)
|
||||
.count() as u16;
|
||||
self.write()?;
|
||||
return Ok(ExercisesProgress::NewPending);
|
||||
}
|
||||
|
||||
// Write that the last exercise is done.
|
||||
self.write()?;
|
||||
|
||||
clear_terminal(writer)?;
|
||||
writer.write_all(FENISH_LINE.as_bytes())?;
|
||||
|
||||
let final_message = self.final_message.trim();
|
||||
let final_message = self.final_message.trim_ascii();
|
||||
if !final_message.is_empty() {
|
||||
writer.write_all(final_message.as_bytes())?;
|
||||
writer.write_all(b"\n")?;
|
||||
@@ -416,14 +407,9 @@ impl AppState {
|
||||
}
|
||||
}
|
||||
|
||||
const CARGO_METADATA_ERR: &str = "Failed to run the command `cargo metadata …`
|
||||
Did you already install Rust?
|
||||
Try running `cargo --version` to diagnose the problem.";
|
||||
|
||||
const RERUNNING_ALL_EXERCISES_MSG: &[u8] = b"
|
||||
All exercises seem to be done.
|
||||
Recompiling and running all exercises to make sure that all of them are actually done.
|
||||
|
||||
";
|
||||
|
||||
const FENISH_LINE: &str = "+----------------------------------------------------+
|
||||
@@ -459,7 +445,7 @@ mod tests {
|
||||
path: "exercises/0.rs",
|
||||
test: false,
|
||||
strict_clippy: false,
|
||||
hint: String::new(),
|
||||
hint: "",
|
||||
done: false,
|
||||
}
|
||||
}
|
||||
@@ -473,7 +459,7 @@ mod tests {
|
||||
final_message: String::new(),
|
||||
file_buf: Vec::new(),
|
||||
official_exercises: true,
|
||||
target_dir: PathBuf::new(),
|
||||
cmd_runner: CmdRunner::build().unwrap(),
|
||||
};
|
||||
|
||||
let mut assert = |done: [bool; 3], expected: [Option<usize>; 3]| {
|
||||
|
||||
@@ -111,6 +111,7 @@ mod tests {
|
||||
test: true,
|
||||
strict_clippy: true,
|
||||
hint: String::new(),
|
||||
skip_check_unsolved: false,
|
||||
},
|
||||
ExerciseInfo {
|
||||
name: String::from("2"),
|
||||
@@ -118,6 +119,7 @@ mod tests {
|
||||
test: false,
|
||||
strict_clippy: false,
|
||||
hint: String::new(),
|
||||
skip_check_unsolved: false,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
172
src/cmd.rs
172
src/cmd.rs
@@ -1,30 +1,44 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::{io::Read, path::Path, process::Command};
|
||||
use anyhow::{bail, Context, Result};
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
io::Read,
|
||||
path::PathBuf,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
/// Run a command with a description for a possible error and append the merged stdout and stderr.
|
||||
/// The boolean in the returned `Result` is true if the command's exit status is success.
|
||||
pub fn run_cmd(mut cmd: Command, description: &str, output: &mut Vec<u8>) -> Result<bool> {
|
||||
let (mut reader, writer) = os_pipe::pipe()
|
||||
.with_context(|| format!("Failed to create a pipe to run the command `{description}``"))?;
|
||||
fn run_cmd(mut cmd: Command, description: &str, output: Option<&mut Vec<u8>>) -> Result<bool> {
|
||||
let spawn = |mut cmd: Command| {
|
||||
// NOTE: The closure drops `cmd` which prevents a pipe deadlock.
|
||||
cmd.stdin(Stdio::null())
|
||||
.spawn()
|
||||
.with_context(|| format!("Failed to run the command `{description}`"))
|
||||
};
|
||||
|
||||
let writer_clone = writer.try_clone().with_context(|| {
|
||||
format!("Failed to clone the pipe writer for the command `{description}`")
|
||||
})?;
|
||||
let mut handle = if let Some(output) = output {
|
||||
let (mut reader, writer) = os_pipe::pipe().with_context(|| {
|
||||
format!("Failed to create a pipe to run the command `{description}``")
|
||||
})?;
|
||||
|
||||
let mut handle = cmd
|
||||
.stdout(writer_clone)
|
||||
.stderr(writer)
|
||||
.spawn()
|
||||
.with_context(|| format!("Failed to run the command `{description}`"))?;
|
||||
let writer_clone = writer.try_clone().with_context(|| {
|
||||
format!("Failed to clone the pipe writer for the command `{description}`")
|
||||
})?;
|
||||
|
||||
// Prevent pipe deadlock.
|
||||
drop(cmd);
|
||||
cmd.stdout(writer_clone).stderr(writer);
|
||||
let handle = spawn(cmd)?;
|
||||
|
||||
reader
|
||||
.read_to_end(output)
|
||||
.with_context(|| format!("Failed to read the output of the command `{description}`"))?;
|
||||
reader
|
||||
.read_to_end(output)
|
||||
.with_context(|| format!("Failed to read the output of the command `{description}`"))?;
|
||||
|
||||
output.push(b'\n');
|
||||
output.push(b'\n');
|
||||
|
||||
handle
|
||||
} else {
|
||||
cmd.stdout(Stdio::null()).stderr(Stdio::null());
|
||||
spawn(cmd)?
|
||||
};
|
||||
|
||||
handle
|
||||
.wait()
|
||||
@@ -32,50 +46,104 @@ pub fn run_cmd(mut cmd: Command, description: &str, output: &mut Vec<u8>) -> Res
|
||||
.map(|status| status.success())
|
||||
}
|
||||
|
||||
pub struct CargoCmd<'a> {
|
||||
pub subcommand: &'a str,
|
||||
pub args: &'a [&'a str],
|
||||
pub bin_name: &'a str,
|
||||
pub description: &'a str,
|
||||
/// RUSTFLAGS="-A warnings"
|
||||
pub hide_warnings: bool,
|
||||
/// Added as `--target-dir` if `Self::dev` is true.
|
||||
pub target_dir: &'a Path,
|
||||
/// The output buffer to append the merged stdout and stderr.
|
||||
pub output: &'a mut Vec<u8>,
|
||||
/// true while developing Rustlings.
|
||||
pub dev: bool,
|
||||
// Parses parts of the output of `cargo metadata`.
|
||||
#[derive(Deserialize)]
|
||||
struct CargoMetadata {
|
||||
target_directory: PathBuf,
|
||||
}
|
||||
|
||||
impl<'a> CargoCmd<'a> {
|
||||
/// Run `cargo SUBCOMMAND --bin EXERCISE_NAME … ARGS`.
|
||||
pub fn run(&mut self) -> Result<bool> {
|
||||
pub struct CmdRunner {
|
||||
target_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl CmdRunner {
|
||||
pub fn build() -> Result<Self> {
|
||||
// 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)?;
|
||||
|
||||
if !metadata_output.status.success() {
|
||||
bail!("The command `cargo metadata …` failed. Are you in the `rustlings/` directory?");
|
||||
}
|
||||
|
||||
let target_dir = serde_json::de::from_slice::<CargoMetadata>(&metadata_output.stdout)
|
||||
.context(
|
||||
"Failed to read the field `target_directory` from the output of the command `cargo metadata …`",
|
||||
)?.target_directory;
|
||||
|
||||
Ok(Self { target_dir })
|
||||
}
|
||||
|
||||
pub fn cargo<'out>(
|
||||
&self,
|
||||
subcommand: &str,
|
||||
bin_name: &str,
|
||||
output: Option<&'out mut Vec<u8>>,
|
||||
) -> CargoSubcommand<'out> {
|
||||
let mut cmd = Command::new("cargo");
|
||||
cmd.arg(self.subcommand);
|
||||
cmd.arg(subcommand).arg("-q").arg("--bin").arg(bin_name);
|
||||
|
||||
// A hack to make `cargo run` work when developing Rustlings.
|
||||
if self.dev {
|
||||
cmd.arg("--manifest-path")
|
||||
.arg("dev/Cargo.toml")
|
||||
.arg("--target-dir")
|
||||
.arg(self.target_dir);
|
||||
#[cfg(debug_assertions)]
|
||||
cmd.arg("--manifest-path")
|
||||
.arg("dev/Cargo.toml")
|
||||
.arg("--target-dir")
|
||||
.arg(&self.target_dir);
|
||||
|
||||
if output.is_some() {
|
||||
cmd.arg("--color").arg("always");
|
||||
}
|
||||
|
||||
cmd.arg("--color")
|
||||
.arg("always")
|
||||
.arg("-q")
|
||||
.arg("--bin")
|
||||
.arg(self.bin_name)
|
||||
.args(self.args);
|
||||
CargoSubcommand { cmd, output }
|
||||
}
|
||||
|
||||
if self.hide_warnings {
|
||||
cmd.env("RUSTFLAGS", "-A warnings");
|
||||
}
|
||||
/// The boolean in the returned `Result` is true if the command's exit status is success.
|
||||
pub fn run_debug_bin(&self, bin_name: &str, output: Option<&mut Vec<u8>>) -> Result<bool> {
|
||||
// 7 = "/debug/".len()
|
||||
let mut bin_path =
|
||||
PathBuf::with_capacity(self.target_dir.as_os_str().len() + 7 + bin_name.len());
|
||||
bin_path.push(&self.target_dir);
|
||||
bin_path.push("debug");
|
||||
bin_path.push(bin_name);
|
||||
|
||||
run_cmd(cmd, self.description, self.output)
|
||||
run_cmd(Command::new(&bin_path), &bin_path.to_string_lossy(), output)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CargoSubcommand<'out> {
|
||||
cmd: Command,
|
||||
output: Option<&'out mut Vec<u8>>,
|
||||
}
|
||||
|
||||
impl<'out> CargoSubcommand<'out> {
|
||||
#[inline]
|
||||
pub fn args<'arg, I>(&mut self, args: I) -> &mut Self
|
||||
where
|
||||
I: IntoIterator<Item = &'arg str>,
|
||||
{
|
||||
self.cmd.args(args);
|
||||
self
|
||||
}
|
||||
|
||||
/// The boolean in the returned `Result` is true if the command's exit status is success.
|
||||
#[inline]
|
||||
pub fn run(self, description: &str) -> Result<bool> {
|
||||
run_cmd(self.cmd, description, self.output)
|
||||
}
|
||||
}
|
||||
|
||||
const CARGO_METADATA_ERR: &str = "Failed to run the command `cargo metadata …`
|
||||
Did you already install Rust?
|
||||
Try running `cargo --version` to diagnose the problem.";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -86,7 +154,7 @@ mod tests {
|
||||
cmd.arg("Hello");
|
||||
|
||||
let mut output = Vec::with_capacity(8);
|
||||
run_cmd(cmd, "echo …", &mut output).unwrap();
|
||||
run_cmd(cmd, "echo …", Some(&mut output)).unwrap();
|
||||
|
||||
assert_eq!(output, b"Hello\n\n");
|
||||
}
|
||||
|
||||
10
src/collections.rs
Normal file
10
src/collections.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
use ahash::AHasher;
|
||||
use std::hash::BuildHasherDefault;
|
||||
|
||||
/// DOS attacks aren't a concern for Rustlings. Therefore, we use `ahash` with fixed seeds.
|
||||
pub type HashSet<T> = std::collections::HashSet<T, BuildHasherDefault<AHasher>>;
|
||||
|
||||
#[inline]
|
||||
pub fn hash_set_with_capacity<T>(capacity: usize) -> HashSet<T> {
|
||||
HashSet::with_capacity_and_hasher(capacity, BuildHasherDefault::<AHasher>::default())
|
||||
}
|
||||
@@ -2,8 +2,6 @@ use anyhow::{bail, Context, Result};
|
||||
use clap::Subcommand;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::DEBUG_PROFILE;
|
||||
|
||||
mod check;
|
||||
mod new;
|
||||
mod update;
|
||||
@@ -32,7 +30,7 @@ impl DevCommands {
|
||||
pub fn run(self) -> Result<()> {
|
||||
match self {
|
||||
Self::New { path, no_git } => {
|
||||
if DEBUG_PROFILE {
|
||||
if cfg!(debug_assertions) {
|
||||
bail!("Disabled in the debug build");
|
||||
}
|
||||
|
||||
|
||||
232
src/dev/check.rs
232
src/dev/check.rs
@@ -1,22 +1,20 @@
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use anyhow::{anyhow, bail, Context, Error, Result};
|
||||
use std::{
|
||||
cmp::Ordering,
|
||||
fs::{self, read_dir, OpenOptions},
|
||||
io::{self, Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
sync::{
|
||||
atomic::{self, AtomicBool},
|
||||
Mutex,
|
||||
},
|
||||
process::{Command, Stdio},
|
||||
thread,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
app_state::parse_target_dir,
|
||||
cargo_toml::{append_bins, bins_start_end_ind, BINS_BUFFER_CAPACITY},
|
||||
cmd::CmdRunner,
|
||||
collections::{hash_set_with_capacity, HashSet},
|
||||
exercise::{RunnableExercise, OUTPUT_CAPACITY},
|
||||
info_file::{ExerciseInfo, InfoFile},
|
||||
CURRENT_FORMAT_VERSION, DEBUG_PROFILE,
|
||||
CURRENT_FORMAT_VERSION,
|
||||
};
|
||||
|
||||
// Find a char that isn't allowed in the exercise's `name` or `dir`.
|
||||
@@ -24,33 +22,36 @@ fn forbidden_char(input: &str) -> Option<char> {
|
||||
input.chars().find(|c| !c.is_alphanumeric() && *c != '_')
|
||||
}
|
||||
|
||||
// Check that the Cargo.toml file is up-to-date.
|
||||
// Check that the `Cargo.toml` file is up-to-date.
|
||||
fn check_cargo_toml(
|
||||
exercise_infos: &[ExerciseInfo],
|
||||
current_cargo_toml: &str,
|
||||
cargo_toml_path: &str,
|
||||
exercise_path_prefix: &[u8],
|
||||
) -> Result<()> {
|
||||
let (bins_start_ind, bins_end_ind) = bins_start_end_ind(current_cargo_toml)?;
|
||||
let current_cargo_toml = fs::read_to_string(cargo_toml_path)
|
||||
.with_context(|| format!("Failed to read the file `{cargo_toml_path}`"))?;
|
||||
|
||||
let (bins_start_ind, bins_end_ind) = bins_start_end_ind(¤t_cargo_toml)?;
|
||||
|
||||
let old_bins = ¤t_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");
|
||||
if cfg!(debug_assertions) {
|
||||
bail!("The file `dev/Cargo.toml` is outdated. Please run `cargo run -- dev update` to update it. Then run `cargo run -- dev check` again");
|
||||
}
|
||||
|
||||
bail!("The file `Cargo.toml` is outdated. Please run `rustlings dev update` to update it");
|
||||
bail!("The file `Cargo.toml` is outdated. Please run `rustlings dev update` to update it. Then run `rustlings dev check` again");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Check the info of all exercises and return their paths in a set.
|
||||
fn check_info_file_exercises(info_file: &InfoFile) -> Result<hashbrown::HashSet<PathBuf>> {
|
||||
let mut names = hashbrown::HashSet::with_capacity(info_file.exercises.len());
|
||||
let mut paths = hashbrown::HashSet::with_capacity(info_file.exercises.len());
|
||||
fn check_info_file_exercises(info_file: &InfoFile) -> Result<HashSet<PathBuf>> {
|
||||
let mut names = hash_set_with_capacity(info_file.exercises.len());
|
||||
let mut paths = hash_set_with_capacity(info_file.exercises.len());
|
||||
|
||||
let mut file_buf = String::with_capacity(1 << 14);
|
||||
for exercise_info in &info_file.exercises {
|
||||
@@ -71,7 +72,7 @@ fn check_info_file_exercises(info_file: &InfoFile) -> Result<hashbrown::HashSet<
|
||||
}
|
||||
}
|
||||
|
||||
if exercise_info.hint.trim().is_empty() {
|
||||
if exercise_info.hint.trim_ascii().is_empty() {
|
||||
bail!("The exercise `{name}` has an empty hint. Please provide a hint or at least tell the user why a hint isn't needed for this exercise");
|
||||
}
|
||||
|
||||
@@ -92,6 +93,10 @@ fn check_info_file_exercises(info_file: &InfoFile) -> Result<hashbrown::HashSet<
|
||||
bail!("The `main` function is missing in the file `{path}`.\nCreate at least an empty `main` function to avoid language server errors");
|
||||
}
|
||||
|
||||
if !file_buf.contains("// TODO") {
|
||||
bail!("Didn't find any `// TODO` comment in the file `{path}`.\nYou need to have at least one such comment to guide the user.");
|
||||
}
|
||||
|
||||
if !exercise_info.test && file_buf.contains("#[test]") {
|
||||
bail!("The file `{path}` contains tests annotated with `#[test]` but the exercise `{name}` has `test = false` in the `info.toml` file");
|
||||
}
|
||||
@@ -107,10 +112,7 @@ fn check_info_file_exercises(info_file: &InfoFile) -> Result<hashbrown::HashSet<
|
||||
// Check `dir` for unexpected files.
|
||||
// Only Rust files in `allowed_rust_files` and `README.md` files are allowed.
|
||||
// Only one level of directory nesting is allowed.
|
||||
fn check_unexpected_files(
|
||||
dir: &str,
|
||||
allowed_rust_files: &hashbrown::HashSet<PathBuf>,
|
||||
) -> Result<()> {
|
||||
fn check_unexpected_files(dir: &str, allowed_rust_files: &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())
|
||||
};
|
||||
@@ -158,7 +160,45 @@ fn check_unexpected_files(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_exercises(info_file: &InfoFile) -> Result<()> {
|
||||
fn check_exercises_unsolved(info_file: &InfoFile, cmd_runner: &CmdRunner) -> Result<()> {
|
||||
println!(
|
||||
"Running all exercises to check that they aren't already solved. This may take a while…\n",
|
||||
);
|
||||
thread::scope(|s| {
|
||||
let handles = info_file
|
||||
.exercises
|
||||
.iter()
|
||||
.filter_map(|exercise_info| {
|
||||
if exercise_info.skip_check_unsolved {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some((
|
||||
exercise_info.name.as_str(),
|
||||
s.spawn(|| exercise_info.run_exercise(None, cmd_runner)),
|
||||
))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for (exercise_name, handle) in handles {
|
||||
let Ok(result) = handle.join() else {
|
||||
bail!("Panic while trying to run the exericse {exercise_name}");
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(true) => bail!(
|
||||
"The exercise {exercise_name} is already solved.\n{SKIP_CHECK_UNSOLVED_HINT}",
|
||||
),
|
||||
Ok(false) => (),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn check_exercises(info_file: &InfoFile, cmd_runner: &CmdRunner) -> Result<()> {
|
||||
match info_file.format_version.cmp(&CURRENT_FORMAT_VERSION) {
|
||||
Ordering::Less => bail!("`format_version` < {CURRENT_FORMAT_VERSION} (supported version)\nPlease migrate to the latest format version"),
|
||||
Ordering::Greater => bail!("`format_version` > {CURRENT_FORMAT_VERSION} (supported version)\nTry updating the Rustlings program"),
|
||||
@@ -166,85 +206,123 @@ fn check_exercises(info_file: &InfoFile) -> Result<()> {
|
||||
}
|
||||
|
||||
let info_file_paths = check_info_file_exercises(info_file)?;
|
||||
check_unexpected_files("exercises", &info_file_paths)?;
|
||||
let handle = thread::spawn(move || check_unexpected_files("exercises", &info_file_paths));
|
||||
|
||||
Ok(())
|
||||
check_exercises_unsolved(info_file, cmd_runner)?;
|
||||
handle.join().unwrap()
|
||||
}
|
||||
|
||||
fn check_solutions(require_solutions: bool, info_file: &InfoFile) -> Result<()> {
|
||||
let target_dir = parse_target_dir()?;
|
||||
let paths = Mutex::new(hashbrown::HashSet::with_capacity(info_file.exercises.len()));
|
||||
let error_occurred = AtomicBool::new(false);
|
||||
enum SolutionCheck {
|
||||
Success { sol_path: String },
|
||||
MissingRequired,
|
||||
MissingOptional,
|
||||
RunFailure { output: Vec<u8> },
|
||||
Err(Error),
|
||||
}
|
||||
|
||||
println!("Running all solutions. This may take a while...\n");
|
||||
fn check_solutions(
|
||||
require_solutions: bool,
|
||||
info_file: &InfoFile,
|
||||
cmd_runner: &CmdRunner,
|
||||
) -> Result<()> {
|
||||
println!("Running all solutions. This may take a while…\n");
|
||||
thread::scope(|s| {
|
||||
for exercise_info in &info_file.exercises {
|
||||
s.spawn(|| {
|
||||
let error = |e| {
|
||||
let mut stderr = io::stderr().lock();
|
||||
stderr.write_all(e).unwrap();
|
||||
stderr
|
||||
.write_all(b"\nFailed to run the solution of the exercise ")
|
||||
.unwrap();
|
||||
stderr.write_all(exercise_info.name.as_bytes()).unwrap();
|
||||
stderr.write_all(SEPARATOR).unwrap();
|
||||
error_occurred.store(true, atomic::Ordering::Relaxed);
|
||||
};
|
||||
let handles = info_file
|
||||
.exercises
|
||||
.iter()
|
||||
.map(|exercise_info| {
|
||||
s.spawn(|| {
|
||||
let sol_path = exercise_info.sol_path();
|
||||
if !Path::new(&sol_path).exists() {
|
||||
if require_solutions {
|
||||
return SolutionCheck::MissingRequired;
|
||||
}
|
||||
|
||||
let path = exercise_info.sol_path();
|
||||
if !Path::new(&path).exists() {
|
||||
if require_solutions {
|
||||
error(b"Solution missing");
|
||||
return SolutionCheck::MissingOptional;
|
||||
}
|
||||
|
||||
// No solution to check.
|
||||
return;
|
||||
}
|
||||
|
||||
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
|
||||
match exercise_info.run_solution(&mut output, &target_dir) {
|
||||
Ok(true) => {
|
||||
paths.lock().unwrap().insert(PathBuf::from(path));
|
||||
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
|
||||
match exercise_info.run_solution(Some(&mut output), cmd_runner) {
|
||||
Ok(true) => SolutionCheck::Success { sol_path },
|
||||
Ok(false) => SolutionCheck::RunFailure { output },
|
||||
Err(e) => SolutionCheck::Err(e),
|
||||
}
|
||||
Ok(false) => error(&output),
|
||||
Err(e) => error(e.to_string().as_bytes()),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut sol_paths = hash_set_with_capacity(info_file.exercises.len());
|
||||
let mut fmt_cmd = Command::new("rustfmt");
|
||||
fmt_cmd
|
||||
.arg("--check")
|
||||
.arg("--edition")
|
||||
.arg("2021")
|
||||
.arg("--color")
|
||||
.arg("always")
|
||||
.stdin(Stdio::null());
|
||||
|
||||
for (exercise_info, handle) in info_file.exercises.iter().zip(handles) {
|
||||
let Ok(check_result) = handle.join() else {
|
||||
bail!(
|
||||
"Panic while trying to run the solution of the exericse {}",
|
||||
exercise_info.name,
|
||||
);
|
||||
};
|
||||
|
||||
match check_result {
|
||||
SolutionCheck::Success { sol_path } => {
|
||||
fmt_cmd.arg(&sol_path);
|
||||
sol_paths.insert(PathBuf::from(sol_path));
|
||||
}
|
||||
});
|
||||
SolutionCheck::MissingRequired => {
|
||||
bail!(
|
||||
"The solution of the exercise {} is missing",
|
||||
exercise_info.name,
|
||||
);
|
||||
}
|
||||
SolutionCheck::MissingOptional => (),
|
||||
SolutionCheck::RunFailure { output } => {
|
||||
io::stderr().lock().write_all(&output)?;
|
||||
bail!(
|
||||
"Running the solution of the exercise {} failed with the error above",
|
||||
exercise_info.name,
|
||||
);
|
||||
}
|
||||
SolutionCheck::Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if error_occurred.load(atomic::Ordering::Relaxed) {
|
||||
bail!("At least one solution failed. See the output above.");
|
||||
}
|
||||
let handle = s.spawn(move || check_unexpected_files("solutions", &sol_paths));
|
||||
|
||||
check_unexpected_files("solutions", &paths.into_inner().unwrap())?;
|
||||
if !fmt_cmd
|
||||
.status()
|
||||
.context("Failed to run `rustfmt` on all solution files")?
|
||||
.success()
|
||||
{
|
||||
bail!("Some solutions aren't formatted. Run `rustfmt` on them");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
handle.join().unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn check(require_solutions: bool) -> Result<()> {
|
||||
let info_file = InfoFile::parse()?;
|
||||
|
||||
// A hack to make `cargo run -- dev check` work when developing Rustlings.
|
||||
if DEBUG_PROFILE {
|
||||
check_cargo_toml(
|
||||
&info_file.exercises,
|
||||
include_str!("../../dev-Cargo.toml"),
|
||||
b"../",
|
||||
)?;
|
||||
if cfg!(debug_assertions) {
|
||||
// A hack to make `cargo run -- dev check` work when developing Rustlings.
|
||||
check_cargo_toml(&info_file.exercises, "dev/Cargo.toml", b"../")?;
|
||||
} else {
|
||||
let current_cargo_toml =
|
||||
fs::read_to_string("Cargo.toml").context("Failed to read the file `Cargo.toml`")?;
|
||||
check_cargo_toml(&info_file.exercises, ¤t_cargo_toml, b"")?;
|
||||
check_cargo_toml(&info_file.exercises, "Cargo.toml", b"")?;
|
||||
}
|
||||
|
||||
check_exercises(&info_file)?;
|
||||
check_solutions(require_solutions, &info_file)?;
|
||||
let cmd_runner = CmdRunner::build()?;
|
||||
check_exercises(&info_file, &cmd_runner)?;
|
||||
check_solutions(require_solutions, &info_file, &cmd_runner)?;
|
||||
|
||||
println!("\nEverything looks fine!");
|
||||
println!("Everything looks fine!");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const SEPARATOR: &[u8] =
|
||||
b"\n========================================================================================\n";
|
||||
const SKIP_CHECK_UNSOLVED_HINT: &str = "If this is an introduction exercise that is intended to be already solved, add `skip_check_unsolved = true` to the exercise's metadata in the `info.toml` file";
|
||||
|
||||
@@ -76,8 +76,8 @@ pub fn new(path: &Path, no_git: bool) -> Result<()> {
|
||||
|
||||
pub const GITIGNORE: &[u8] = b".rustlings-state.txt
|
||||
Cargo.lock
|
||||
target
|
||||
.vscode
|
||||
target/
|
||||
.vscode/
|
||||
!.vscode/extensions.json
|
||||
";
|
||||
|
||||
@@ -139,7 +139,7 @@ const README: &str = "# Rustlings 🦀
|
||||
|
||||
Welcome to these third-party Rustlings exercises 😃
|
||||
|
||||
First, [install Rustlings using the official instructions in the README of the Rustlings project](https://github.com/rust-lang/rustlings) ✅
|
||||
First, [install Rustlings using the official instructions](https://github.com/rust-lang/rustlings) ✅
|
||||
|
||||
Then, open your terminal in this directory and run `rustlings` to get started with the exercises 🚀
|
||||
Then, clone this repository, open a terminal in this directory and run `rustlings` to get started with the exercises 🚀
|
||||
";
|
||||
|
||||
@@ -4,18 +4,19 @@ use std::fs;
|
||||
use crate::{
|
||||
cargo_toml::updated_cargo_toml,
|
||||
info_file::{ExerciseInfo, InfoFile},
|
||||
DEBUG_PROFILE,
|
||||
};
|
||||
|
||||
// Update the `Cargo.toml` file.
|
||||
fn update_cargo_toml(
|
||||
exercise_infos: &[ExerciseInfo],
|
||||
current_cargo_toml: &str,
|
||||
exercise_path_prefix: &[u8],
|
||||
cargo_toml_path: &str,
|
||||
exercise_path_prefix: &[u8],
|
||||
) -> Result<()> {
|
||||
let current_cargo_toml = fs::read_to_string(cargo_toml_path)
|
||||
.with_context(|| format!("Failed to read the file `{cargo_toml_path}`"))?;
|
||||
|
||||
let updated_cargo_toml =
|
||||
updated_cargo_toml(exercise_infos, current_cargo_toml, exercise_path_prefix)?;
|
||||
updated_cargo_toml(exercise_infos, ¤t_cargo_toml, exercise_path_prefix)?;
|
||||
|
||||
fs::write(cargo_toml_path, updated_cargo_toml)
|
||||
.context("Failed to write the `Cargo.toml` file")?;
|
||||
@@ -26,21 +27,14 @@ fn update_cargo_toml(
|
||||
pub fn update() -> Result<()> {
|
||||
let info_file = InfoFile::parse()?;
|
||||
|
||||
// A hack to make `cargo run -- dev update` work when developing Rustlings.
|
||||
if DEBUG_PROFILE {
|
||||
update_cargo_toml(
|
||||
&info_file.exercises,
|
||||
include_str!("../../dev-Cargo.toml"),
|
||||
b"../",
|
||||
"dev/Cargo.toml",
|
||||
)
|
||||
.context("Failed to update the file `dev/Cargo.toml`")?;
|
||||
if cfg!(debug_assertions) {
|
||||
// A hack to make `cargo run -- dev update` work when developing Rustlings.
|
||||
update_cargo_toml(&info_file.exercises, "dev/Cargo.toml", b"../")
|
||||
.context("Failed to update the file `dev/Cargo.toml`")?;
|
||||
|
||||
println!("Updated `dev/Cargo.toml`");
|
||||
} else {
|
||||
let current_cargo_toml =
|
||||
fs::read_to_string("Cargo.toml").context("Failed to read the file `Cargo.toml`")?;
|
||||
update_cargo_toml(&info_file.exercises, ¤t_cargo_toml, b"", "Cargo.toml")
|
||||
update_cargo_toml(&info_file.exercises, "Cargo.toml", &[])
|
||||
.context("Failed to update the file `Cargo.toml`")?;
|
||||
|
||||
println!("Updated `Cargo.toml`");
|
||||
|
||||
161
src/exercise.rs
161
src/exercise.rs
@@ -1,46 +1,41 @@
|
||||
use anyhow::Result;
|
||||
use crossterm::style::{style, StyledContent, Stylize};
|
||||
use ratatui::crossterm::style::{style, StyledContent, Stylize};
|
||||
use std::{
|
||||
fmt::{self, Display, Formatter},
|
||||
io::Write,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
cmd::{run_cmd, CargoCmd},
|
||||
in_official_repo,
|
||||
terminal_link::TerminalFileLink,
|
||||
DEBUG_PROFILE,
|
||||
};
|
||||
use crate::{cmd::CmdRunner, terminal_link::TerminalFileLink};
|
||||
|
||||
/// The initial capacity of the output buffer.
|
||||
pub const OUTPUT_CAPACITY: usize = 1 << 14;
|
||||
|
||||
// Run an exercise binary and append its output to the `output` buffer.
|
||||
// Compilation must be done before calling this method.
|
||||
fn run_bin(bin_name: &str, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
|
||||
writeln!(output, "{}", "Output".underlined())?;
|
||||
fn run_bin(
|
||||
bin_name: &str,
|
||||
mut output: Option<&mut Vec<u8>>,
|
||||
cmd_runner: &CmdRunner,
|
||||
) -> Result<bool> {
|
||||
if let Some(output) = output.as_deref_mut() {
|
||||
writeln!(output, "{}", "Output".underlined())?;
|
||||
}
|
||||
|
||||
// 7 = "/debug/".len()
|
||||
let mut bin_path = PathBuf::with_capacity(target_dir.as_os_str().len() + 7 + bin_name.len());
|
||||
bin_path.push(target_dir);
|
||||
bin_path.push("debug");
|
||||
bin_path.push(bin_name);
|
||||
let success = cmd_runner.run_debug_bin(bin_name, output.as_deref_mut())?;
|
||||
|
||||
let success = run_cmd(Command::new(&bin_path), &bin_path.to_string_lossy(), output)?;
|
||||
|
||||
if !success {
|
||||
// This output is important to show the user that something went wrong.
|
||||
// Otherwise, calling something like `exit(1)` in an exercise without further output
|
||||
// leaves the user confused about why the exercise isn't done yet.
|
||||
writeln!(
|
||||
output,
|
||||
"{}",
|
||||
"The exercise didn't run successfully (nonzero exit code)"
|
||||
.bold()
|
||||
.red(),
|
||||
)?;
|
||||
if let Some(output) = output {
|
||||
if !success {
|
||||
// This output is important to show the user that something went wrong.
|
||||
// Otherwise, calling something like `exit(1)` in an exercise without further output
|
||||
// leaves the user confused about why the exercise isn't done yet.
|
||||
writeln!(
|
||||
output,
|
||||
"{}",
|
||||
"The exercise didn't run successfully (nonzero exit code)"
|
||||
.bold()
|
||||
.red(),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(success)
|
||||
@@ -54,7 +49,7 @@ pub struct Exercise {
|
||||
pub path: &'static str,
|
||||
pub test: bool,
|
||||
pub strict_clippy: bool,
|
||||
pub hint: String,
|
||||
pub hint: &'static str,
|
||||
pub done: bool,
|
||||
}
|
||||
|
||||
@@ -77,89 +72,77 @@ pub trait RunnableExercise {
|
||||
|
||||
// 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();
|
||||
|
||||
// Developing the official Rustlings.
|
||||
let dev = DEBUG_PROFILE && in_official_repo();
|
||||
|
||||
let build_success = CargoCmd {
|
||||
subcommand: "build",
|
||||
args: &[],
|
||||
bin_name,
|
||||
description: "cargo build …",
|
||||
hide_warnings: false,
|
||||
target_dir,
|
||||
output,
|
||||
dev,
|
||||
fn run(
|
||||
&self,
|
||||
bin_name: &str,
|
||||
mut output: Option<&mut Vec<u8>>,
|
||||
cmd_runner: &CmdRunner,
|
||||
) -> Result<bool> {
|
||||
if let Some(output) = output.as_deref_mut() {
|
||||
output.clear();
|
||||
}
|
||||
.run()?;
|
||||
|
||||
let build_success = cmd_runner
|
||||
.cargo("build", bin_name, output.as_deref_mut())
|
||||
.run("cargo build …")?;
|
||||
if !build_success {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// Discard the output of `cargo build` because it will be shown again by Clippy.
|
||||
output.clear();
|
||||
// Discard the compiler output because it will be shown again by `cargo test` or Clippy.
|
||||
if let Some(output) = output.as_deref_mut() {
|
||||
output.clear();
|
||||
}
|
||||
|
||||
if self.test() {
|
||||
let output_is_some = output.is_some();
|
||||
let mut test_cmd = cmd_runner.cargo("test", bin_name, output.as_deref_mut());
|
||||
if output_is_some {
|
||||
test_cmd.args(["--", "--color", "always", "--show-output"]);
|
||||
}
|
||||
let test_success = test_cmd.run("cargo test …")?;
|
||||
if !test_success {
|
||||
run_bin(bin_name, output, cmd_runner)?;
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// Discard the compiler output because it will be shown again by Clippy.
|
||||
if let Some(output) = output.as_deref_mut() {
|
||||
output.clear();
|
||||
}
|
||||
}
|
||||
|
||||
let mut clippy_cmd = cmd_runner.cargo("clippy", bin_name, output.as_deref_mut());
|
||||
|
||||
// `--profile test` is required to also check code with `[cfg(test)]`.
|
||||
let clippy_args: &[&str] = if self.strict_clippy() {
|
||||
&["--profile", "test", "--", "-D", "warnings"]
|
||||
if self.strict_clippy() {
|
||||
clippy_cmd.args(["--profile", "test", "--", "-D", "warnings"]);
|
||||
} else {
|
||||
&["--profile", "test"]
|
||||
};
|
||||
let clippy_success = CargoCmd {
|
||||
subcommand: "clippy",
|
||||
args: clippy_args,
|
||||
bin_name,
|
||||
description: "cargo clippy …",
|
||||
hide_warnings: false,
|
||||
target_dir,
|
||||
output,
|
||||
dev,
|
||||
}
|
||||
.run()?;
|
||||
if !clippy_success {
|
||||
return Ok(false);
|
||||
clippy_cmd.args(["--profile", "test"]);
|
||||
}
|
||||
|
||||
if !self.test() {
|
||||
return run_bin(bin_name, output, target_dir);
|
||||
}
|
||||
let clippy_success = clippy_cmd.run("cargo clippy …")?;
|
||||
let run_success = run_bin(bin_name, output, cmd_runner)?;
|
||||
|
||||
let test_success = CargoCmd {
|
||||
subcommand: "test",
|
||||
args: &["--", "--color", "always", "--show-output"],
|
||||
bin_name,
|
||||
description: "cargo test …",
|
||||
// Hide warnings because they are shown by Clippy.
|
||||
hide_warnings: true,
|
||||
target_dir,
|
||||
output,
|
||||
dev,
|
||||
}
|
||||
.run()?;
|
||||
|
||||
let run_success = run_bin(bin_name, output, target_dir)?;
|
||||
|
||||
Ok(test_success && run_success)
|
||||
Ok(clippy_success && run_success)
|
||||
}
|
||||
|
||||
/// Compile, check and run the exercise.
|
||||
/// 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)
|
||||
fn run_exercise(&self, output: Option<&mut Vec<u8>>, cmd_runner: &CmdRunner) -> Result<bool> {
|
||||
self.run(self.name(), output, cmd_runner)
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
fn run_solution(&self, output: Option<&mut Vec<u8>>, cmd_runner: &CmdRunner) -> Result<bool> {
|
||||
let name = self.name();
|
||||
let mut bin_name = String::with_capacity(name.len());
|
||||
let mut bin_name = String::with_capacity(name.len() + 4);
|
||||
bin_name.push_str(name);
|
||||
bin_name.push_str("_sol");
|
||||
|
||||
self.run(&bin_name, output, target_dir)
|
||||
self.run(&bin_name, output, cmd_runner)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,14 +11,17 @@ pub struct ExerciseInfo {
|
||||
pub name: String,
|
||||
/// Exercise's directory name inside the `exercises/` directory.
|
||||
pub dir: Option<String>,
|
||||
#[serde(default = "default_true")]
|
||||
/// Run `cargo test` on the exercise.
|
||||
#[serde(default = "default_true")]
|
||||
pub test: bool,
|
||||
/// Deny all Clippy warnings.
|
||||
#[serde(default)]
|
||||
pub strict_clippy: bool,
|
||||
/// The exercise's hint to be shown to the user on request.
|
||||
pub hint: String,
|
||||
/// The exercise is already solved. Ignore it when checking that all exercises are unsolved.
|
||||
#[serde(default)]
|
||||
pub skip_check_unsolved: bool,
|
||||
}
|
||||
#[inline(always)]
|
||||
const fn default_true() -> bool {
|
||||
|
||||
129
src/init.rs
129
src/init.rs
@@ -1,32 +1,91 @@
|
||||
use anyhow::{bail, Context, Result};
|
||||
use crossterm::style::Stylize;
|
||||
use ratatui::crossterm::style::Stylize;
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
env::set_current_dir,
|
||||
fs::{self, create_dir},
|
||||
io::ErrorKind,
|
||||
path::Path,
|
||||
io::{self, Write},
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
use crate::{cargo_toml::updated_cargo_toml, embedded::EMBEDDED_FILES, info_file::InfoFile};
|
||||
use crate::{
|
||||
cargo_toml::updated_cargo_toml, embedded::EMBEDDED_FILES, info_file::InfoFile,
|
||||
term::press_enter_prompt,
|
||||
};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CargoLocateProject {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
pub fn init() -> Result<()> {
|
||||
// Prevent initialization in a directory that contains the file `Cargo.toml`.
|
||||
// This can mean that Rustlings was already initialized in this directory.
|
||||
// Otherwise, this can cause problems with Cargo workspaces.
|
||||
if Path::new("Cargo.toml").exists() {
|
||||
bail!(CARGO_TOML_EXISTS_ERR);
|
||||
let rustlings_dir = Path::new("rustlings");
|
||||
if rustlings_dir.exists() {
|
||||
bail!(RUSTLINGS_DIR_ALREADY_EXISTS_ERR);
|
||||
}
|
||||
|
||||
let rustlings_path = Path::new("rustlings");
|
||||
if let Err(e) = create_dir(rustlings_path) {
|
||||
if e.kind() == ErrorKind::AlreadyExists {
|
||||
bail!(RUSTLINGS_DIR_ALREADY_EXISTS_ERR);
|
||||
let locate_project_output = Command::new("cargo")
|
||||
.arg("locate-project")
|
||||
.arg("-q")
|
||||
.arg("--workspace")
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.context(CARGO_LOCATE_PROJECT_ERR)?;
|
||||
|
||||
let mut stdout = io::stdout().lock();
|
||||
let mut init_git = true;
|
||||
|
||||
if locate_project_output.status.success() {
|
||||
if Path::new("exercises").exists() && Path::new("solutions").exists() {
|
||||
bail!(IN_INITIALIZED_DIR_ERR);
|
||||
}
|
||||
return Err(e.into());
|
||||
|
||||
let workspace_manifest =
|
||||
serde_json::de::from_slice::<CargoLocateProject>(&locate_project_output.stdout)
|
||||
.context(
|
||||
"Failed to read the field `root` from the output of `cargo locate-project …`",
|
||||
)?
|
||||
.root;
|
||||
|
||||
let workspace_manifest_content = fs::read_to_string(&workspace_manifest)
|
||||
.with_context(|| format!("Failed to read the file {}", workspace_manifest.display()))?;
|
||||
if !workspace_manifest_content.contains("[workspace]\n")
|
||||
&& !workspace_manifest_content.contains("workspace.")
|
||||
{
|
||||
bail!("The current directory is already part of a Cargo project.\nPlease initialize Rustlings in a different directory");
|
||||
}
|
||||
|
||||
stdout.write_all(b"This command will create the directory `rustlings/` as a member of this Cargo workspace.\nPress ENTER to continue ")?;
|
||||
press_enter_prompt(&mut stdout)?;
|
||||
|
||||
// Make sure "rustlings" is added to `workspace.members` by making
|
||||
// Cargo initialize a new project.
|
||||
let status = Command::new("cargo")
|
||||
.arg("new")
|
||||
.arg("-q")
|
||||
.arg("--vcs")
|
||||
.arg("none")
|
||||
.arg("rustlings")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.status()?;
|
||||
if !status.success() {
|
||||
bail!("Failed to initialize a new Cargo workspace member.\nPlease initialize Rustlings in a different directory");
|
||||
}
|
||||
|
||||
stdout.write_all(b"The directory `rustlings` has been added to `workspace.members` in the `Cargo.toml` file of this Cargo workspace.\n")?;
|
||||
fs::remove_dir_all("rustlings")
|
||||
.context("Failed to remove the temporary directory `rustlings/`")?;
|
||||
init_git = false;
|
||||
} else {
|
||||
stdout.write_all(b"This command will create the directory `rustlings/` which will contain the exercises.\nPress ENTER to continue ")?;
|
||||
press_enter_prompt(&mut stdout)?;
|
||||
}
|
||||
|
||||
set_current_dir("rustlings")
|
||||
create_dir(rustlings_dir).context("Failed to create the `rustlings/` directory")?;
|
||||
set_current_dir(rustlings_dir)
|
||||
.context("Failed to change the current directory to `rustlings/`")?;
|
||||
|
||||
let info_file = InfoFile::parse()?;
|
||||
@@ -35,6 +94,11 @@ pub fn init() -> Result<()> {
|
||||
.context("Failed to initialize the `rustlings/exercises` directory")?;
|
||||
|
||||
create_dir("solutions").context("Failed to create the `solutions/` directory")?;
|
||||
fs::write(
|
||||
"solutions/README.md",
|
||||
include_bytes!("../solutions/README.md"),
|
||||
)
|
||||
.context("Failed to create the file rustlings/solutions/README.md")?;
|
||||
for dir in EMBEDDED_FILES.exercise_dirs {
|
||||
let mut dir_path = String::with_capacity(10 + dir.name.len());
|
||||
dir_path.push_str("solutions/");
|
||||
@@ -70,41 +134,46 @@ pub fn init() -> Result<()> {
|
||||
fs::write(".vscode/extensions.json", VS_CODE_EXTENSIONS_JSON)
|
||||
.context("Failed to create the file `rustlings/.vscode/extensions.json`")?;
|
||||
|
||||
// Ignore any Git error because Git initialization is not required.
|
||||
let _ = Command::new("git")
|
||||
.arg("init")
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status();
|
||||
if init_git {
|
||||
// Ignore any Git error because Git initialization is not required.
|
||||
let _ = Command::new("git")
|
||||
.arg("init")
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status();
|
||||
}
|
||||
|
||||
println!(
|
||||
writeln!(
|
||||
stdout,
|
||||
"\n{}\n\n{}",
|
||||
"Initialization done ✓".green(),
|
||||
POST_INIT_MSG.bold(),
|
||||
);
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const CARGO_LOCATE_PROJECT_ERR: &str = "Failed to run the command `cargo locate-project …`
|
||||
Did you already install Rust?
|
||||
Try running `cargo --version` to diagnose the problem.";
|
||||
|
||||
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
|
||||
solutions
|
||||
Cargo.lock
|
||||
target
|
||||
.vscode
|
||||
const GITIGNORE: &[u8] = b"Cargo.lock
|
||||
target/
|
||||
.vscode/
|
||||
";
|
||||
|
||||
pub const VS_CODE_EXTENSIONS_JSON: &[u8] = br#"{"recommendations":["rust-lang.rust-analyzer"]}"#;
|
||||
|
||||
const CARGO_TOML_EXISTS_ERR: &str = "The current directory contains the file `Cargo.toml`.
|
||||
const IN_INITIALIZED_DIR_ERR: &str = "It looks like Rustlings is already initialized in this directory.
|
||||
|
||||
If you already initialized Rustlings, run the command `rustlings` for instructions on getting started with the exercises.
|
||||
Otherwise, please run `rustlings init` again in another directory.";
|
||||
Otherwise, please run `rustlings init` again in a different directory.";
|
||||
|
||||
const RUSTLINGS_DIR_ALREADY_EXISTS_ERR: &str =
|
||||
"A directory with the name `rustlings` already exists in the current directory.
|
||||
|
||||
15
src/list.rs
15
src/list.rs
@@ -1,10 +1,13 @@
|
||||
use anyhow::Result;
|
||||
use crossterm::{
|
||||
event::{self, Event, KeyCode, KeyEventKind},
|
||||
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
||||
ExecutableCommand,
|
||||
use ratatui::{
|
||||
backend::CrosstermBackend,
|
||||
crossterm::{
|
||||
event::{self, Event, KeyCode, KeyEventKind},
|
||||
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
||||
ExecutableCommand,
|
||||
},
|
||||
Terminal,
|
||||
};
|
||||
use ratatui::{backend::CrosstermBackend, Terminal};
|
||||
use std::io;
|
||||
|
||||
use crate::app_state::AppState;
|
||||
@@ -24,7 +27,7 @@ pub fn list(app_state: &mut AppState) -> Result<()> {
|
||||
let mut ui_state = UiState::new(app_state);
|
||||
|
||||
'outer: loop {
|
||||
terminal.draw(|frame| ui_state.draw(frame).unwrap())?;
|
||||
terminal.try_draw(|frame| ui_state.draw(frame).map_err(io::Error::other))?;
|
||||
|
||||
let key = loop {
|
||||
match event::read()? {
|
||||
|
||||
@@ -161,7 +161,7 @@ impl<'a> UiState<'a> {
|
||||
}
|
||||
|
||||
pub fn draw(&mut self, frame: &mut Frame) -> Result<()> {
|
||||
let area = frame.size();
|
||||
let area = frame.area();
|
||||
|
||||
frame.render_stateful_widget(
|
||||
&self.table,
|
||||
|
||||
62
src/main.rs
62
src/main.rs
@@ -2,16 +2,18 @@ use anyhow::{bail, Context, Result};
|
||||
use app_state::StateFileStatus;
|
||||
use clap::{Parser, Subcommand};
|
||||
use std::{
|
||||
io::{self, BufRead, StdoutLock, Write},
|
||||
io::{self, IsTerminal, Write},
|
||||
path::Path,
|
||||
process::exit,
|
||||
};
|
||||
use term::{clear_terminal, press_enter_prompt};
|
||||
|
||||
use self::{app_state::AppState, dev::DevCommands, info_file::InfoFile, watch::WatchExit};
|
||||
|
||||
mod app_state;
|
||||
mod cargo_toml;
|
||||
mod cmd;
|
||||
mod collections;
|
||||
mod dev;
|
||||
mod embedded;
|
||||
mod exercise;
|
||||
@@ -20,35 +22,11 @@ mod init;
|
||||
mod list;
|
||||
mod progress_bar;
|
||||
mod run;
|
||||
mod term;
|
||||
mod terminal_link;
|
||||
mod watch;
|
||||
|
||||
const CURRENT_FORMAT_VERSION: u8 = 1;
|
||||
const DEBUG_PROFILE: bool = {
|
||||
#[allow(unused_assignments, unused_mut)]
|
||||
let mut debug_profile = false;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
debug_profile = true;
|
||||
}
|
||||
|
||||
debug_profile
|
||||
};
|
||||
|
||||
// The current directory is the official Rustligns repository.
|
||||
fn in_official_repo() -> bool {
|
||||
Path::new("dev/rustlings-repo.txt").exists()
|
||||
}
|
||||
|
||||
fn clear_terminal(stdout: &mut StdoutLock) -> io::Result<()> {
|
||||
stdout.write_all(b"\x1b[H\x1b[2J\x1b[3J")
|
||||
}
|
||||
|
||||
fn press_enter_prompt() -> io::Result<()> {
|
||||
io::stdin().lock().read_until(b'\n', &mut Vec::new())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rustlings is a collection of small exercises to get you used to writing and reading Rust code
|
||||
#[derive(Parser)]
|
||||
@@ -89,24 +67,12 @@ enum Subcommands {
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
if !DEBUG_PROFILE && in_official_repo() {
|
||||
if cfg!(not(debug_assertions)) && Path::new("dev/rustlings-repo.txt").exists() {
|
||||
bail!("{OLD_METHOD_ERR}");
|
||||
}
|
||||
|
||||
match args.command {
|
||||
Some(Subcommands::Init) => {
|
||||
if DEBUG_PROFILE {
|
||||
bail!("Disabled in the debug build");
|
||||
}
|
||||
|
||||
{
|
||||
let mut stdout = io::stdout().lock();
|
||||
stdout.write_all(b"This command will create the directory `rustlings/` which will contain the exercises.\nPress ENTER to continue ")?;
|
||||
stdout.flush()?;
|
||||
press_enter_prompt()?;
|
||||
stdout.write_all(b"\n")?;
|
||||
}
|
||||
|
||||
return init::init().context("Initialization failed");
|
||||
}
|
||||
Some(Subcommands::Dev(dev_command)) => return dev_command.run(),
|
||||
@@ -136,11 +102,12 @@ fn main() -> Result<()> {
|
||||
let mut stdout = io::stdout().lock();
|
||||
clear_terminal(&mut stdout)?;
|
||||
|
||||
let welcome_message = welcome_message.trim();
|
||||
let welcome_message = welcome_message.trim_ascii();
|
||||
write!(stdout, "{welcome_message}\n\nPress ENTER to continue ")?;
|
||||
stdout.flush()?;
|
||||
press_enter_prompt()?;
|
||||
press_enter_prompt(&mut stdout)?;
|
||||
clear_terminal(&mut stdout)?;
|
||||
// Flush to be able to show errors occurring before printing a newline to stdout.
|
||||
stdout.flush()?;
|
||||
}
|
||||
StateFileStatus::Read => (),
|
||||
}
|
||||
@@ -148,6 +115,10 @@ fn main() -> Result<()> {
|
||||
|
||||
match args.command {
|
||||
None => {
|
||||
if !io::stdout().is_terminal() {
|
||||
bail!("Unsupported or missing terminal/TTY");
|
||||
}
|
||||
|
||||
let notify_exercise_names = if args.manual_run {
|
||||
None
|
||||
} else {
|
||||
@@ -197,9 +168,10 @@ fn main() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const OLD_METHOD_ERR: &str = "You are trying to run Rustlings using the old method before v6.
|
||||
const OLD_METHOD_ERR: &str =
|
||||
"You are trying to run Rustlings using the old method before version 6.
|
||||
The new method doesn't include cloning the Rustlings' repository.
|
||||
Please follow the instructions in the README:
|
||||
Please follow the instructions in `README.md`:
|
||||
https://github.com/rust-lang/rustlings#getting-started";
|
||||
|
||||
const FORMAT_VERSION_HIGHER_ERR: &str =
|
||||
@@ -216,5 +188,5 @@ const PRE_INIT_MSG: &str = r"
|
||||
|_| \__,_|___/\__|_|_|_| |_|\__, |___/
|
||||
|___/
|
||||
|
||||
The `exercises` directory wasn't found in the current directory.
|
||||
The `exercises/` directory couldn't be found in the current directory.
|
||||
If you are just starting with Rustlings, run the command `rustlings init` to initialize it.";
|
||||
|
||||
@@ -14,7 +14,7 @@ const PROGRESS_EXCEEDS_MAX_ERR: &str =
|
||||
|
||||
/// Terminal progress bar to be used when not using Ratataui.
|
||||
pub fn progress_bar(progress: u16, total: u16, line_width: u16) -> Result<String> {
|
||||
use crossterm::style::Stylize;
|
||||
use ratatui::crossterm::style::Stylize;
|
||||
|
||||
if progress > total {
|
||||
bail!(PROGRESS_EXCEEDS_MAX_ERR);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use anyhow::{bail, Result};
|
||||
use crossterm::style::{style, Stylize};
|
||||
use ratatui::crossterm::style::{style, Stylize};
|
||||
use std::io::{self, Write};
|
||||
|
||||
use crate::{
|
||||
@@ -11,7 +11,7 @@ use crate::{
|
||||
pub fn run(app_state: &mut AppState) -> Result<()> {
|
||||
let exercise = app_state.current_exercise();
|
||||
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
|
||||
let success = exercise.run_exercise(&mut output, app_state.target_dir())?;
|
||||
let success = exercise.run_exercise(Some(&mut output), app_state.cmd_runner())?;
|
||||
|
||||
let mut stdout = io::stdout().lock();
|
||||
stdout.write_all(&output)?;
|
||||
|
||||
12
src/term.rs
Normal file
12
src/term.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
use std::io::{self, BufRead, StdoutLock, Write};
|
||||
|
||||
pub fn clear_terminal(stdout: &mut StdoutLock) -> io::Result<()> {
|
||||
stdout.write_all(b"\x1b[H\x1b[2J\x1b[3J")
|
||||
}
|
||||
|
||||
pub fn press_enter_prompt(stdout: &mut StdoutLock) -> io::Result<()> {
|
||||
stdout.flush()?;
|
||||
io::stdin().lock().read_until(b'\n', &mut Vec::new())?;
|
||||
stdout.write_all(b"\n")?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -102,8 +102,7 @@ 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(NOTIFY_ERR));
|
||||
}
|
||||
WatchEvent::TerminalEventErr(e) => {
|
||||
return Err(Error::from(e).context("Terminal event listener failed"));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use anyhow::Result;
|
||||
use crossterm::{
|
||||
use ratatui::crossterm::{
|
||||
style::{style, Stylize},
|
||||
terminal,
|
||||
};
|
||||
@@ -51,10 +51,15 @@ impl<'a> WatchState<'a> {
|
||||
pub fn run_current_exercise(&mut self) -> Result<()> {
|
||||
self.show_hint = false;
|
||||
|
||||
writeln!(
|
||||
self.writer,
|
||||
"\nChecking the exercise `{}`. Please wait…",
|
||||
self.app_state.current_exercise().name,
|
||||
)?;
|
||||
let success = self
|
||||
.app_state
|
||||
.current_exercise()
|
||||
.run_exercise(&mut self.output, self.app_state.target_dir())?;
|
||||
.run_exercise(Some(&mut self.output), self.app_state.cmd_runner())?;
|
||||
if success {
|
||||
self.done_status =
|
||||
if let Some(solution_path) = self.app_state.current_solution_path()? {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
|
||||
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
|
||||
use std::sync::mpsc::Sender;
|
||||
|
||||
use super::WatchEvent;
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
[package]
|
||||
name = "failure"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[[bin]]
|
||||
name = "compFailure"
|
||||
path = "exercises/compFailure.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "compNoExercise"
|
||||
path = "exercises/compNoExercise.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "testFailure"
|
||||
path = "exercises/testFailure.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "testNotPassed"
|
||||
path = "exercises/testNotPassed.rs"
|
||||
@@ -1,6 +0,0 @@
|
||||
fn main() {}
|
||||
|
||||
#[test]
|
||||
fn passing() {
|
||||
asset!(true);
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
fn main() {}
|
||||
|
||||
#[test]
|
||||
fn not_passing() {
|
||||
assert!(false);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
format_version = 1
|
||||
|
||||
[[exercises]]
|
||||
name = "compFailure"
|
||||
test = false
|
||||
hint = ""
|
||||
|
||||
[[exercises]]
|
||||
name = "testFailure"
|
||||
hint = "Hello!"
|
||||
@@ -1,16 +0,0 @@
|
||||
[package]
|
||||
name = "state"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[[bin]]
|
||||
name = "pending_exercise"
|
||||
path = "exercises/pending_exercise.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "pending_test_exercise"
|
||||
path = "exercises/pending_test_exercise.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "finished_exercise"
|
||||
path = "exercises/finished_exercise.rs"
|
||||
@@ -1 +0,0 @@
|
||||
fn main() {}
|
||||
@@ -1,4 +0,0 @@
|
||||
fn main() {}
|
||||
|
||||
#[test]
|
||||
fn it_works() {}
|
||||
@@ -1,15 +0,0 @@
|
||||
format_version = 1
|
||||
|
||||
[[exercises]]
|
||||
name = "pending_exercise"
|
||||
test = false
|
||||
hint = """"""
|
||||
|
||||
[[exercises]]
|
||||
name = "pending_test_exercise"
|
||||
hint = """"""
|
||||
|
||||
[[exercises]]
|
||||
name = "finished_exercise"
|
||||
test = false
|
||||
hint = """"""
|
||||
@@ -1,12 +0,0 @@
|
||||
[package]
|
||||
name = "success"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[[bin]]
|
||||
name = "compSuccess"
|
||||
path = "exercises/compSuccess.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "testSuccess"
|
||||
path = "exercises/testSuccess.rs"
|
||||
@@ -1 +0,0 @@
|
||||
fn main() {}
|
||||
@@ -1,7 +0,0 @@
|
||||
fn main() {}
|
||||
|
||||
#[test]
|
||||
fn passing() {
|
||||
println!("THIS TEST TOO SHALL PASS");
|
||||
assert!(true);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
format_version = 1
|
||||
|
||||
[[exercises]]
|
||||
name = "compSuccess"
|
||||
test = false
|
||||
hint = """"""
|
||||
|
||||
[[exercises]]
|
||||
name = "testSuccess"
|
||||
hint = """"""
|
||||
@@ -1,134 +1,182 @@
|
||||
use assert_cmd::prelude::*;
|
||||
use std::process::Command;
|
||||
use std::{
|
||||
env::{self, consts::EXE_SUFFIX},
|
||||
process::{Command, Stdio},
|
||||
str::from_utf8,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn fails_when_in_wrong_dir() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.current_dir("tests/")
|
||||
.assert()
|
||||
.code(1);
|
||||
enum Output<'a> {
|
||||
FullStdout(&'a str),
|
||||
PartialStdout(&'a str),
|
||||
PartialStderr(&'a str),
|
||||
}
|
||||
|
||||
use Output::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Cmd<'a> {
|
||||
current_dir: Option<&'a str>,
|
||||
args: &'a [&'a str],
|
||||
output: Option<Output<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> Cmd<'a> {
|
||||
#[inline]
|
||||
fn current_dir(&mut self, current_dir: &'a str) -> &mut Self {
|
||||
self.current_dir = Some(current_dir);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn args(&mut self, args: &'a [&'a str]) -> &mut Self {
|
||||
self.args = args;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn output(&mut self, output: Output<'a>) -> &mut Self {
|
||||
self.output = Some(output);
|
||||
self
|
||||
}
|
||||
|
||||
fn assert(&self, success: bool) {
|
||||
let rustlings_bin = {
|
||||
let mut path = env::current_exe().unwrap();
|
||||
// Pop test binary name
|
||||
path.pop();
|
||||
// Pop `/deps`
|
||||
path.pop();
|
||||
|
||||
path.push("rustlings");
|
||||
let mut path = path.into_os_string();
|
||||
path.push(EXE_SUFFIX);
|
||||
path
|
||||
};
|
||||
|
||||
let mut cmd = Command::new(rustlings_bin);
|
||||
|
||||
if let Some(current_dir) = self.current_dir {
|
||||
cmd.current_dir(current_dir);
|
||||
}
|
||||
|
||||
cmd.args(self.args).stdin(Stdio::null());
|
||||
|
||||
let status = match self.output {
|
||||
None => cmd
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.unwrap(),
|
||||
Some(FullStdout(stdout)) => {
|
||||
let output = cmd.stderr(Stdio::null()).output().unwrap();
|
||||
assert_eq!(from_utf8(&output.stdout).unwrap(), stdout);
|
||||
output.status
|
||||
}
|
||||
Some(PartialStdout(stdout)) => {
|
||||
let output = cmd.stderr(Stdio::null()).output().unwrap();
|
||||
assert!(from_utf8(&output.stdout).unwrap().contains(stdout));
|
||||
output.status
|
||||
}
|
||||
Some(PartialStderr(stderr)) => {
|
||||
let output = cmd.stdout(Stdio::null()).output().unwrap();
|
||||
assert!(from_utf8(&output.stderr).unwrap().contains(stderr));
|
||||
output.status
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(status.success(), success, "{cmd:?}");
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn success(&self) {
|
||||
self.assert(true);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn fail(&self) {
|
||||
self.assert(false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_single_compile_success() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.args(["run", "compSuccess"])
|
||||
.current_dir("tests/fixture/success/")
|
||||
.assert()
|
||||
fn run_compilation_success() {
|
||||
Cmd::default()
|
||||
.current_dir("tests/test_exercises")
|
||||
.args(&["run", "compilation_success"])
|
||||
.success();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_single_compile_failure() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.args(["run", "compFailure"])
|
||||
.current_dir("tests/fixture/failure/")
|
||||
.assert()
|
||||
.code(1);
|
||||
fn run_compilation_failure() {
|
||||
Cmd::default()
|
||||
.current_dir("tests/test_exercises")
|
||||
.args(&["run", "compilation_failure"])
|
||||
.fail();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_single_test_success() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.args(["run", "testSuccess"])
|
||||
.current_dir("tests/fixture/success/")
|
||||
.assert()
|
||||
fn run_test_success() {
|
||||
Cmd::default()
|
||||
.current_dir("tests/test_exercises")
|
||||
.args(&["run", "test_success"])
|
||||
.output(PartialStdout("\nOutput from `main` function\n"))
|
||||
.success();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_single_test_failure() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.args(["run", "testFailure"])
|
||||
.current_dir("tests/fixture/failure/")
|
||||
.assert()
|
||||
.code(1);
|
||||
fn run_test_failure() {
|
||||
Cmd::default()
|
||||
.current_dir("tests/test_exercises")
|
||||
.args(&["run", "test_failure"])
|
||||
.fail();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_single_test_not_passed() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.args(["run", "testNotPassed.rs"])
|
||||
.current_dir("tests/fixture/failure/")
|
||||
.assert()
|
||||
.code(1);
|
||||
fn run_exercise_not_in_info() {
|
||||
Cmd::default()
|
||||
.current_dir("tests/test_exercises")
|
||||
.args(&["run", "not_in_info"])
|
||||
.fail();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_single_test_no_exercise() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.args(["run", "compNoExercise.rs"])
|
||||
.current_dir("tests/fixture/failure")
|
||||
.assert()
|
||||
.code(1);
|
||||
fn reset_without_exercise_name() {
|
||||
Cmd::default().args(&["reset"]).fail();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_single_exercise() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.args(["reset", "intro1"])
|
||||
.assert()
|
||||
.code(0);
|
||||
fn hint() {
|
||||
Cmd::default()
|
||||
.current_dir("tests/test_exercises")
|
||||
.args(&["hint", "test_failure"])
|
||||
.output(FullStdout("The answer to everything: 42\n"))
|
||||
.success();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_no_exercise() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.arg("reset")
|
||||
.assert()
|
||||
.code(2)
|
||||
.stderr(predicates::str::contains(
|
||||
"required arguments were not provided",
|
||||
));
|
||||
}
|
||||
fn init() {
|
||||
let test_dir = tempfile::TempDir::new().unwrap();
|
||||
let test_dir = test_dir.path().to_str().unwrap();
|
||||
|
||||
#[test]
|
||||
fn get_hint_for_single_test() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.args(["hint", "testFailure"])
|
||||
.current_dir("tests/fixture/failure")
|
||||
.assert()
|
||||
.code(0)
|
||||
.stdout("Hello!\n");
|
||||
}
|
||||
Cmd::default().current_dir(test_dir).fail();
|
||||
|
||||
#[test]
|
||||
fn run_compile_exercise_does_not_prompt() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.args(["run", "pending_exercise"])
|
||||
.current_dir("tests/fixture/state")
|
||||
.assert()
|
||||
.code(0);
|
||||
}
|
||||
Cmd::default()
|
||||
.current_dir(test_dir)
|
||||
.args(&["init"])
|
||||
.success();
|
||||
|
||||
#[test]
|
||||
fn run_test_exercise_does_not_prompt() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.args(["run", "pending_test_exercise"])
|
||||
.current_dir("tests/fixture/state")
|
||||
.assert()
|
||||
.code(0);
|
||||
}
|
||||
// Running `init` after a successful initialization.
|
||||
Cmd::default()
|
||||
.current_dir(test_dir)
|
||||
.args(&["init"])
|
||||
.output(PartialStderr("`cd rustlings`"))
|
||||
.fail();
|
||||
|
||||
#[test]
|
||||
fn run_single_test_success_with_output() {
|
||||
Command::cargo_bin("rustlings")
|
||||
.unwrap()
|
||||
.args(["run", "testSuccess"])
|
||||
.current_dir("tests/fixture/success/")
|
||||
.assert()
|
||||
.code(0)
|
||||
.stdout(predicates::str::contains("THIS TEST TOO SHALL PASS"));
|
||||
let initialized_dir = format!("{test_dir}/rustlings");
|
||||
|
||||
// Running `init` in the initialized directory.
|
||||
Cmd::default()
|
||||
.current_dir(&initialized_dir)
|
||||
.args(&["init"])
|
||||
.output(PartialStderr("already initialized"))
|
||||
.fail();
|
||||
}
|
||||
|
||||
11
tests/test_exercises/dev/Cargo.toml
Normal file
11
tests/test_exercises/dev/Cargo.toml
Normal file
@@ -0,0 +1,11 @@
|
||||
bin = [
|
||||
{ name = "compilation_success", path = "../exercises/compilation_success.rs" },
|
||||
{ name = "compilation_failure", path = "../exercises/compilation_failure.rs" },
|
||||
{ name = "test_success", path = "../exercises/test_success.rs" },
|
||||
{ name = "test_failure", path = "../exercises/test_failure.rs" },
|
||||
]
|
||||
|
||||
[package]
|
||||
name = "test_exercises"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
9
tests/test_exercises/exercises/test_failure.rs
Normal file
9
tests/test_exercises/exercises/test_failure.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
fn main() {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn fails() {
|
||||
assert!(false);
|
||||
}
|
||||
}
|
||||
9
tests/test_exercises/exercises/test_success.rs
Normal file
9
tests/test_exercises/exercises/test_success.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
fn main() {
|
||||
println!("Output from `main` function");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn passes() {}
|
||||
}
|
||||
19
tests/test_exercises/info.toml
Normal file
19
tests/test_exercises/info.toml
Normal file
@@ -0,0 +1,19 @@
|
||||
format_version = 1
|
||||
|
||||
[[exercises]]
|
||||
name = "compilation_success"
|
||||
test = false
|
||||
hint = ""
|
||||
|
||||
[[exercises]]
|
||||
name = "compilation_failure"
|
||||
test = false
|
||||
hint = ""
|
||||
|
||||
[[exercises]]
|
||||
name = "test_success"
|
||||
hint = ""
|
||||
|
||||
[[exercises]]
|
||||
name = "test_failure"
|
||||
hint = "The answer to everything: 42"
|
||||
Reference in New Issue
Block a user