Compare commits

...

29 commits

Author SHA1 Message Date
Kacper Poneta 8d7f82296f
Merge 59e8f70e55 into 74388d4bf4 2024-08-26 12:45:57 -07:00
mo8it 74388d4bf4 Only trigger write when needed 2024-08-26 04:41:26 +02:00
mo8it e811dd15b5 Fix list on terminals that don't disable line wrapping 2024-08-26 04:29:58 +02:00
mo8it f22700a4ec Use the correct environment variable 2024-08-26 02:43:08 +02:00
mo8it ee25a7d458 Disable terminal links in VS-Code 2024-08-26 02:41:22 +02:00
mo8it 594e212b8a Darker highlighting in the list 2024-08-26 00:53:42 +02:00
mo8it 5c355468c1 File link in the list? No problem :D 2024-08-26 00:49:56 +02:00
mo8it d1571d18f9 Only reset color and underline after link 2024-08-26 00:48:12 +02:00
mo8it cb86b44dea LOL, swapped colors 2024-08-26 00:40:30 +02:00
mo8it 833e6e0c92 Newline after resetting attributes 2024-08-26 00:24:39 +02:00
mo8it 159273e532 Take stdout as argument in watch mode 2024-08-26 00:09:04 +02:00
mo8it 631f2db1a3 Lower the maximum scroll padding 2024-08-25 23:54:18 +02:00
mo8it a1f0eaab54 Add disallowed types and methods in Clippy 2024-08-25 23:54:04 +02:00
mo8it b1898f6d8b Use queue instead of Stylize 2024-08-25 23:53:50 +02:00
mo8it d29e9e7e07 Update deps 2024-08-25 20:42:13 +02:00
mo8it 360605e284 Merge branch 'rm-ratatui' 2024-08-25 20:31:08 +02:00
mo8it 64772544fa Final touches :D 2024-08-25 20:29:54 +02:00
mo8it 5f4875e2ba Almost done with list 2024-08-25 19:24:12 +02:00
mo8it fd2a8c01cb Separate drawing rows 2024-08-24 19:18:13 +02:00
mo8it b6129ad081 Use the full length for the wide footer 2024-08-24 17:45:38 +02:00
mo8it 28d0b0a21e Highlight selected row 2024-08-24 17:45:02 +02:00
mo8it b779c43126 Almost done with list display 2024-08-24 17:17:56 +02:00
mo8it 4e12725616 Don't exit the list on "to current" if nothing is selected 2024-08-24 00:23:45 +02:00
mo8it 570bc9f32d Start list without Ratatui 2024-08-24 00:14:12 +02:00
mo8it 59e8f70e55 Format code 2024-07-12 18:31:23 +02:00
mo8it 4c8365fe88 Update dev/Cargo.toml 2024-07-12 18:25:01 +02:00
Kacper Poneta 52af0674c1 changed the task to make it more appropriate 2024-07-12 18:14:40 +02:00
Kacper Poneta 938b90e5f2 very small solution update 2024-07-11 22:55:48 +02:00
Kacper Poneta 55cc8584bd added exercise 2024-07-11 22:53:38 +02:00
22 changed files with 966 additions and 750 deletions

View file

@ -2,6 +2,3 @@
extend-exclude = [
"CHANGELOG.md",
]
[default.extend-words]
"ratatui" = "ratatui"

183
Cargo.lock generated
View file

@ -14,12 +14,6 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "allocator-api2"
version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f"
[[package]]
name = "anstream"
version = "0.6.15"
@ -93,21 +87,6 @@ version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
[[package]]
name = "cassowary"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
[[package]]
name = "castaway"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0abae9be0aaf9ea96a3b1b8b1b55c602ca751eba1b1500220cea4ecbafe7c0d5"
dependencies = [
"rustversion",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
@ -160,20 +139,6 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fd119d74b830634cea2a0f58bbd0d54540518a14397557951e79340abc28c0"
[[package]]
name = "compact_str"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6050c3a16ddab2e412160b31f2c871015704239bca62f72f6e5f0be631d3f644"
dependencies = [
"castaway",
"cfg-if",
"itoa",
"rustversion",
"ryu",
"static_assertions",
]
[[package]]
name = "crossbeam-channel"
version = "0.5.13"
@ -214,12 +179,6 @@ dependencies = [
"winapi",
]
[[package]]
name = "either"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
[[package]]
name = "equivalent"
version = "1.0.1"
@ -238,9 +197,9 @@ dependencies = [
[[package]]
name = "fastrand"
version = "2.1.0"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a"
checksum = "e8c02a5121d4ea3eb16a80748c74f5549a5665e4c21333c6098f283870fbdea6"
[[package]]
name = "filetime"
@ -268,10 +227,6 @@ name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
"allocator-api2",
]
[[package]]
name = "heck"
@ -315,31 +270,12 @@ dependencies = [
"libc",
]
[[package]]
name = "instability"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b23a0c8dfe501baac4adf6ebbfa6eddf8f0c07f56b058cc1288017e32397846c"
dependencies = [
"quote",
"syn",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.11"
@ -405,15 +341,6 @@ version = "0.4.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
[[package]]
name = "lru"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37ee39891760e7d94734f6f63fedc29a2e4a152f836120753a72503f09fcf904"
dependencies = [
"hashbrown",
]
[[package]]
name = "memchr"
version = "2.7.4"
@ -513,12 +440,6 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "proc-macro2"
version = "1.0.86"
@ -530,34 +451,13 @@ dependencies = [
[[package]]
name = "quote"
version = "1.0.36"
version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7"
checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af"
dependencies = [
"proc-macro2",
]
[[package]]
name = "ratatui"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ba6a365afbe5615999275bea2446b970b10a41102500e27ce7678d50d978303"
dependencies = [
"bitflags 2.6.0",
"cassowary",
"compact_str",
"crossterm",
"instability",
"itertools",
"lru",
"paste",
"strum",
"strum_macros",
"unicode-segmentation",
"unicode-truncate",
"unicode-width",
]
[[package]]
name = "redox_syscall"
version = "0.5.3"
@ -587,9 +487,9 @@ dependencies = [
"ahash",
"anyhow",
"clap",
"crossterm",
"notify-debouncer-mini",
"os_pipe",
"ratatui",
"rustlings-macros",
"serde",
"serde_json",
@ -606,12 +506,6 @@ dependencies = [
"toml_edit",
]
[[package]]
name = "rustversion"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6"
[[package]]
name = "ryu"
version = "1.0.18"
@ -635,18 +529,18 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.208"
version = "1.0.209"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cff085d2cb684faa248efb494c39b68e522822ac0de72ccf08109abde717cfb2"
checksum = "99fce0ffe7310761ca6bf9faf5115afbc19688edd00171d81b1bb1b116c63e09"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.208"
version = "1.0.209"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24008e81ff7613ed8e5ba0cfaf24e2c2f1e5b8a0495711e44fcd4882fca62bcf"
checksum = "a5831b979fd7b5439637af1752d535ff49f4860c0f341d1baeb6faf0f4242170"
dependencies = [
"proc-macro2",
"quote",
@ -655,9 +549,9 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.125"
version = "1.0.127"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83c8e735a073ccf5be70aa8066aa984eaf2fa000db6c8d0100ae605b366d31ed"
checksum = "8043c06d9f82bd7271361ed64f415fe5e12a77fdb52e573e7f06a516dea329ad"
dependencies = [
"itoa",
"memchr",
@ -710,45 +604,17 @@ version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "strum"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"
dependencies = [
"strum_macros",
]
[[package]]
name = "strum_macros"
version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"
dependencies = [
"heck",
"proc-macro2",
"quote",
"rustversion",
"syn",
]
[[package]]
name = "syn"
version = "2.0.75"
version = "2.0.76"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6af063034fc1935ede7be0122941bafa9bacb949334d090b77ca98b5817c7d9"
checksum = "578e081a14e0cefc3279b0472138c513f37b41a08d5a3cca9b6e4e8ceb6cd525"
dependencies = [
"proc-macro2",
"quote",
@ -796,29 +662,6 @@ version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "unicode-segmentation"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202"
[[package]]
name = "unicode-truncate"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf"
dependencies = [
"itertools",
"unicode-segmentation",
"unicode-width",
]
[[package]]
name = "unicode-width"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d"
[[package]]
name = "utf8parse"
version = "0.2.2"

View file

@ -19,7 +19,7 @@ edition = "2021" # On Update: Update the edition of the `rustfmt` command that c
rust-version = "1.80"
[workspace.dependencies]
serde = { version = "1.0.208", features = ["derive"] }
serde = { version = "1.0.209", features = ["derive"] }
toml_edit = { version = "0.22.20", default-features = false, features = ["parse", "serde"] }
[package]
@ -49,11 +49,11 @@ include = [
ahash = { version = "0.8.11", default-features = false }
anyhow = "1.0.86"
clap = { version = "4.5.16", features = ["derive"] }
crossterm = { version = "0.28.1", default-features = false, features = ["windows", "events"] }
notify-debouncer-mini = { version = "0.4.1", default-features = false }
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.125"
serde_json = "1.0.127"
serde.workspace = true
toml_edit.workspace = true
@ -75,6 +75,8 @@ unstable_features = "forbid"
[workspace.lints.clippy]
empty_loop = "forbid"
disallowed-types = "deny"
disallowed-methods = "deny"
infinite_loop = "deny"
mem_forget = "deny"
dbg_macro = "warn"

13
clippy.toml Normal file
View file

@ -0,0 +1,13 @@
disallowed-types = [
# Inefficient. Use `.queue(…)` instead.
"crossterm::style::Stylize",
"crossterm::style::styled_content::StyledContent",
]
disallowed-methods = [
# We use `ahash` instead of the default hasher.
"std::collections::HashSet::new",
"std::collections::HashSet::with_capacity",
# Inefficient. Use `.queue(…)` instead.
"crossterm::style::style",
]

View file

@ -116,6 +116,8 @@ bin = [
{ name = "generics1_sol", path = "../solutions/14_generics/generics1.rs" },
{ name = "generics2", path = "../exercises/14_generics/generics2.rs" },
{ name = "generics2_sol", path = "../solutions/14_generics/generics2.rs" },
{ name = "generics3", path = "../exercises/14_generics/generics3.rs" },
{ name = "generics3_sol", path = "../solutions/14_generics/generics3.rs" },
{ name = "traits1", path = "../exercises/15_traits/traits1.rs" },
{ name = "traits1_sol", path = "../solutions/15_traits/traits1.rs" },
{ name = "traits2", path = "../exercises/15_traits/traits2.rs" },

View file

@ -0,0 +1,54 @@
// generics3.rs
// Execute `rustlings hint generics3` or use the `hint` watch subcommand for a hint.
// This function should take an array of `Option` elements and returns array of not None elements
// TODO fix this function signature
fn into_dispose_nulls(list: Vec<Option<&str>>) -> Vec<&str> {
list.into_iter().flatten().collect()
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn store_str_on_list() {
let names_list = vec![Some("maria"), Some("jacob"), None, Some("kacper"), None];
let only_values = into_dispose_nulls(names_list);
assert_eq!(only_values.len(), 3);
}
#[test]
fn store_numbers_on_list() {
let numbers_list = vec![Some(1), Some(2), None, Some(3)];
let only_values = into_dispose_nulls(numbers_list);
assert_eq!(only_values.len(), 3);
}
#[test]
fn store_custom_type_on_list() {
#[allow(dead_code)]
struct Rectangle {
width: i32,
height: i32,
}
impl Rectangle {
fn new(width: i32, height: i32) -> Self {
Self { width, height }
}
}
let custom_list = vec![
Some(Rectangle::new(1, 2)),
None,
None,
Some(Rectangle::new(3, 4)),
];
let only_values = into_dispose_nulls(custom_list);
assert_eq!(only_values.len(), 2);
}
}

View file

@ -16,7 +16,7 @@ include = [
proc-macro = true
[dependencies]
quote = "1.0.36"
quote = "1.0.37"
serde.workspace = true
toml_edit.workspace = true

View file

@ -744,6 +744,17 @@ hint = """
Related section in The Book:
https://doc.rust-lang.org/book/ch10-01-syntax.html#in-method-definitions"""
[[exercises]]
name = "generics3"
dir = "14_generics"
hint = """
Vectors in Rust use generics to create dynamically-sized arrays of any type.
The `into_dispose_nulls` function takes a vector as an argument, but only accepts vectors that store the &str type.
To allow the function to accept vectors that store any type, you can leverage your knowledge about generics.
If you're unsure how to proceed, please refer to the Rust Book at:
https://doc.rust-lang.org/book/ch10-01-syntax.html#in-function-definitions.
"""
# TRAITS
[[exercises]]

View file

@ -0,0 +1,53 @@
// generics3.rs
// Execute `rustlings hint generics3` or use the `hint` watch subcommand for a hint.
// Here we added generic type `T` to function signature
// Now this function can be used with vector of any
fn into_dispose_nulls<T>(list: Vec<Option<T>>) -> Vec<T> {
list.into_iter().flatten().collect()
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn store_str_on_list() {
let names_list = vec![Some("maria"), Some("jacob"), None, Some("kacper"), None];
let only_values = into_dispose_nulls(names_list);
assert_eq!(only_values.len(), 3);
}
#[test]
fn store_numbers_on_list() {
let numbers_list = vec![Some(1), Some(2), None, Some(3)];
let only_values = into_dispose_nulls(numbers_list);
assert_eq!(only_values.len(), 3);
}
#[test]
fn store_custom_type_on_list() {
struct Rectangle {
width: i32,
height: i32,
}
impl Rectangle {
fn new(width: i32, height: i32) -> Self {
Self { width, height }
}
}
let custom_list = vec![
Some(Rectangle::new(1, 2)),
None,
None,
Some(Rectangle::new(3, 4)),
];
let only_values = into_dispose_nulls(custom_list);
assert_eq!(only_values.len(), 2);
}
}

View file

@ -271,6 +271,7 @@ impl AppState {
Ok(exercise.path)
}
// Reset the exercise by index and return its name.
pub fn reset_exercise_by_ind(&mut self, exercise_ind: usize) -> Result<&'static str> {
if exercise_ind >= self.exercises.len() {
bail!(BAD_INDEX_ERR);
@ -280,7 +281,7 @@ impl AppState {
let exercise = &self.exercises[exercise_ind];
self.reset(exercise_ind, exercise.path)?;
Ok(exercise.path)
Ok(exercise.name)
}
// Return the index of the next pending exercise or `None` if all exercises are done.
@ -337,7 +338,7 @@ impl AppState {
/// Mark the current exercise as done and move on to the next pending exercise if one exists.
/// If all exercises are marked as done, run all of them to make sure that they are actually
/// done. If an exercise which is marked as done fails, mark it as pending and continue on it.
pub fn done_current_exercise(&mut self, writer: &mut StdoutLock) -> Result<ExercisesProgress> {
pub fn done_current_exercise(&mut self, stdout: &mut StdoutLock) -> Result<ExercisesProgress> {
let exercise = &mut self.exercises[self.current_exercise_ind];
if !exercise.done {
exercise.done = true;
@ -349,7 +350,7 @@ impl AppState {
return Ok(ExercisesProgress::NewPending);
}
writer.write_all(RERUNNING_ALL_EXERCISES_MSG)?;
stdout.write_all(RERUNNING_ALL_EXERCISES_MSG)?;
let n_exercises = self.exercises.len();
@ -367,12 +368,12 @@ impl AppState {
.collect::<Vec<_>>();
for (exercise_ind, handle) in handles.into_iter().enumerate() {
write!(writer, "\rProgress: {exercise_ind}/{n_exercises}")?;
writer.flush()?;
write!(stdout, "\rProgress: {exercise_ind}/{n_exercises}")?;
stdout.flush()?;
let success = handle.join().unwrap()?;
if !success {
writer.write_all(b"\n\n")?;
stdout.write_all(b"\n\n")?;
return Ok(Some(exercise_ind));
}
}
@ -394,13 +395,13 @@ impl AppState {
// Write that the last exercise is done.
self.write()?;
clear_terminal(writer)?;
writer.write_all(FENISH_LINE.as_bytes())?;
clear_terminal(stdout)?;
stdout.write_all(FENISH_LINE.as_bytes())?;
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")?;
stdout.write_all(final_message.as_bytes())?;
stdout.write_all(b"\n")?;
}
Ok(ExercisesProgress::AllDone)

View file

@ -1,15 +1,27 @@
use anyhow::Result;
use ratatui::crossterm::style::{style, StyledContent, Stylize};
use std::{
fmt::{self, Display, Formatter},
io::Write,
use crossterm::{
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
QueueableCommand,
};
use std::io::{self, StdoutLock, Write};
use crate::{cmd::CmdRunner, terminal_link::TerminalFileLink};
use crate::{
cmd::CmdRunner,
term::{terminal_file_link, write_ansi},
};
/// The initial capacity of the output buffer.
pub const OUTPUT_CAPACITY: usize = 1 << 14;
pub fn solution_link_line(stdout: &mut StdoutLock, solution_path: &str) -> io::Result<()> {
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"Solution")?;
stdout.queue(ResetColor)?;
stdout.write_all(b" for comparison: ")?;
terminal_file_link(stdout, solution_path, Color::Cyan)?;
stdout.write_all(b"\n")
}
// Run an exercise binary and append its output to the `output` buffer.
// Compilation must be done before calling this method.
fn run_bin(
@ -18,7 +30,10 @@ fn run_bin(
cmd_runner: &CmdRunner,
) -> Result<bool> {
if let Some(output) = output.as_deref_mut() {
writeln!(output, "{}", "Output".underlined())?;
write_ansi(output, SetAttribute(Attribute::Underlined));
output.extend_from_slice(b"Output");
write_ansi(output, ResetColor);
output.push(b'\n');
}
let success = cmd_runner.run_debug_bin(bin_name, output.as_deref_mut())?;
@ -28,13 +43,11 @@ fn run_bin(
// 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(),
)?;
write_ansi(output, SetAttribute(Attribute::Bold));
write_ansi(output, SetForegroundColor(Color::Red));
output.extend_from_slice(b"The exercise didn't run successfully (nonzero exit code)");
write_ansi(output, ResetColor);
output.push(b'\n');
}
}
@ -53,18 +66,6 @@ pub struct Exercise {
pub done: bool,
}
impl Exercise {
pub fn terminal_link(&self) -> StyledContent<TerminalFileLink<'_>> {
style(TerminalFileLink(self.path)).underlined().blue()
}
}
impl Display for Exercise {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.path.fmt(f)
}
}
pub trait RunnableExercise {
fn name(&self) -> &str;
fn strict_clippy(&self) -> bool;

View file

@ -1,5 +1,8 @@
use anyhow::{bail, Context, Result};
use ratatui::crossterm::style::Stylize;
use crossterm::{
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
QueueableCommand,
};
use serde::Deserialize;
use std::{
env::set_current_dir,
@ -144,12 +147,14 @@ pub fn init() -> Result<()> {
.status();
}
writeln!(
stdout,
"{}\n\n{}",
"Initialization done ✓".green(),
POST_INIT_MSG.bold(),
)?;
stdout.queue(SetForegroundColor(Color::Green))?;
stdout.write_all("Initialization done ✓".as_bytes())?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n\n")?;
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(POST_INIT_MSG)?;
stdout.queue(ResetColor)?;
Ok(())
}
@ -182,5 +187,6 @@ You probably already initialized Rustlings.
Run `cd rustlings`
Then run `rustlings` again";
const POST_INIT_MSG: &str = "Run `cd rustlings` to go into the generated directory.
Then run `rustlings` to get started.";
const POST_INIT_MSG: &[u8] = b"Run `cd rustlings` to go into the generated directory.
Then run `rustlings` to get started.
";

View file

@ -1,95 +1,96 @@
use anyhow::{Context, Result};
use ratatui::{
backend::CrosstermBackend,
crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind},
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
QueueableCommand,
use crossterm::{
cursor,
event::{
self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, MouseEventKind,
},
Terminal,
terminal::{
disable_raw_mode, enable_raw_mode, DisableLineWrap, EnableLineWrap, EnterAlternateScreen,
LeaveAlternateScreen,
},
QueueableCommand,
};
use std::io::{self, StdoutLock, Write};
use crate::app_state::AppState;
use self::state::{Filter, UiState};
use self::state::{Filter, ListState};
mod state;
fn handle_list(app_state: &mut AppState, stdout: &mut StdoutLock) -> Result<()> {
let mut terminal = Terminal::new(CrosstermBackend::new(stdout))?;
terminal.clear()?;
let mut list_state = ListState::new(app_state, stdout)?;
let mut ui_state = UiState::new(app_state);
'outer: loop {
terminal.try_draw(|frame| ui_state.draw(frame).map_err(io::Error::other))?;
let key = loop {
loop {
match event::read().context("Failed to read terminal event")? {
Event::Key(key) => match key.kind {
KeyEventKind::Press | KeyEventKind::Repeat => break key,
KeyEventKind::Release => (),
},
// Redraw
Event::Resize(_, _) => continue 'outer,
// Ignore
Event::FocusGained | Event::FocusLost | Event::Mouse(_) | Event::Paste(_) => (),
Event::Key(key) => {
match key.kind {
KeyEventKind::Release => continue,
KeyEventKind::Press | KeyEventKind::Repeat => (),
}
};
ui_state.message.clear();
list_state.message.clear();
match key.code {
KeyCode::Char('q') => break,
KeyCode::Down | KeyCode::Char('j') => ui_state.select_next(),
KeyCode::Up | KeyCode::Char('k') => ui_state.select_previous(),
KeyCode::Home | KeyCode::Char('g') => ui_state.select_first(),
KeyCode::End | KeyCode::Char('G') => ui_state.select_last(),
KeyCode::Char('q') => return Ok(()),
KeyCode::Down | KeyCode::Char('j') => list_state.select_next(),
KeyCode::Up | KeyCode::Char('k') => list_state.select_previous(),
KeyCode::Home | KeyCode::Char('g') => list_state.select_first(),
KeyCode::End | KeyCode::Char('G') => list_state.select_last(),
KeyCode::Char('d') => {
let message = if ui_state.filter == Filter::Done {
ui_state.filter = Filter::None;
"Disabled filter DONE"
if list_state.filter() == Filter::Done {
list_state.set_filter(Filter::None);
list_state.message.push_str("Disabled filter DONE");
} else {
ui_state.filter = Filter::Done;
"Enabled filter DONE │ Press d again to disable the filter"
};
ui_state = ui_state.with_updated_rows();
ui_state.message.push_str(message);
list_state.set_filter(Filter::Done);
list_state.message.push_str(
"Enabled filter DONE │ Press d again to disable the filter",
);
}
}
KeyCode::Char('p') => {
let message = if ui_state.filter == Filter::Pending {
ui_state.filter = Filter::None;
let message = if list_state.filter() == Filter::Pending {
list_state.set_filter(Filter::None);
"Disabled filter PENDING"
} else {
ui_state.filter = Filter::Pending;
list_state.set_filter(Filter::Pending);
"Enabled filter PENDING │ Press p again to disable the filter"
};
ui_state = ui_state.with_updated_rows();
ui_state.message.push_str(message);
}
KeyCode::Char('r') => {
ui_state = ui_state.with_reset_selected()?;
list_state.message.push_str(message);
}
KeyCode::Char('r') => list_state.reset_selected()?,
KeyCode::Char('c') => {
ui_state.selected_to_current_exercise()?;
break;
if list_state.selected_to_current_exercise()? {
return Ok(());
}
_ => (),
}
// Redraw to remove the message.
KeyCode::Esc => (),
_ => continue,
}
}
Event::Mouse(event) => match event.kind {
MouseEventKind::ScrollDown => list_state.select_next(),
MouseEventKind::ScrollUp => list_state.select_previous(),
_ => continue,
},
Event::Resize(width, height) => list_state.set_term_size(width, height),
// Ignore
Event::FocusGained | Event::FocusLost => continue,
}
Ok(())
list_state.draw(stdout)?;
}
}
pub fn list(app_state: &mut AppState) -> Result<()> {
let mut stdout = io::stdout().lock();
stdout
.queue(EnterAlternateScreen)?
.queue(EnableMouseCapture)?
.flush()?;
.queue(cursor::Hide)?
.queue(DisableLineWrap)?
.queue(EnableMouseCapture)?;
enable_raw_mode()?;
let res = handle_list(app_state, &mut stdout);
@ -97,6 +98,8 @@ pub fn list(app_state: &mut AppState) -> Result<()> {
// Restore the terminal even if we got an error.
stdout
.queue(LeaveAlternateScreen)?
.queue(cursor::Show)?
.queue(EnableLineWrap)?
.queue(DisableMouseCapture)?
.flush()?;
disable_raw_mode()?;

View file

@ -1,14 +1,32 @@
use anyhow::{Context, Result};
use ratatui::{
layout::{Constraint, Rect},
style::{Style, Stylize},
text::{Span, Text},
widgets::{Block, Borders, HighlightSpacing, Paragraph, Row, Table, TableState},
Frame,
use crossterm::{
cursor::{MoveTo, MoveToNextLine},
style::{Attribute, Color, ResetColor, SetAttribute, SetBackgroundColor, SetForegroundColor},
terminal::{self, BeginSynchronizedUpdate, Clear, ClearType, EndSynchronizedUpdate},
QueueableCommand,
};
use std::{
fmt::Write as _,
io::{self, StdoutLock, Write},
};
use std::{fmt::Write, mem};
use crate::{app_state::AppState, progress_bar::progress_bar_ratatui};
use crate::{
app_state::AppState,
exercise::Exercise,
term::{progress_bar, terminal_file_link, CountedWrite, MaxLenWriter},
MAX_EXERCISE_NAME_LEN,
};
const MAX_SCROLL_PADDING: usize = 5;
// +1 for column padding.
const SPACE: &[u8] = &[b' '; MAX_EXERCISE_NAME_LEN + 1];
fn next_ln(stdout: &mut StdoutLock) -> io::Result<()> {
stdout
.queue(Clear(ClearType::UntilNewLine))?
.queue(MoveToNextLine(1))?;
Ok(())
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Filter {
@ -17,269 +35,387 @@ pub enum Filter {
None,
}
pub struct UiState<'a> {
pub table: Table<'static>,
pub struct ListState<'a> {
/// Footer message to be displayed if not empty.
pub message: String,
pub filter: Filter,
app_state: &'a mut AppState,
table_state: TableState,
n_rows: usize,
name_col_width: usize,
filter: Filter,
n_rows_with_filter: usize,
/// Selected row out of the filtered ones.
selected_row: Option<usize>,
row_offset: usize,
term_width: u16,
term_height: u16,
separator_line: Vec<u8>,
narrow_term: bool,
show_footer: bool,
max_n_rows_to_display: usize,
scroll_padding: usize,
}
impl<'a> UiState<'a> {
pub fn with_updated_rows(mut self) -> Self {
let current_exercise_ind = self.app_state.current_exercise_ind();
impl<'a> ListState<'a> {
pub fn new(app_state: &'a mut AppState, stdout: &mut StdoutLock) -> io::Result<Self> {
stdout.queue(Clear(ClearType::All))?;
self.n_rows = 0;
let rows = self
.app_state
.exercises()
.iter()
.enumerate()
.filter_map(|(ind, exercise)| {
let exercise_state = if exercise.done {
if self.filter == Filter::Pending {
return None;
}
"DONE".green()
} else {
if self.filter == Filter::Done {
return None;
}
"PENDING".yellow()
};
self.n_rows += 1;
let next = if ind == current_exercise_ind {
">>>>".bold().red()
} else {
Span::default()
};
Some(Row::new([
next,
exercise_state,
Span::raw(exercise.name),
Span::raw(exercise.path),
]))
});
self.table = self.table.rows(rows);
if self.n_rows == 0 {
self.table_state.select(None);
} else {
self.table_state.select(Some(
self.table_state
.selected()
.map_or(0, |selected| selected.min(self.n_rows - 1)),
));
}
self
}
pub fn new(app_state: &'a mut AppState) -> Self {
let header = Row::new(["Next", "State", "Name", "Path"]);
let max_name_len = app_state
let name_col_title_len = 4;
let name_col_width = app_state
.exercises()
.iter()
.map(|exercise| exercise.name.len())
.max()
.unwrap_or(4) as u16;
let widths = [
Constraint::Length(4),
Constraint::Length(7),
Constraint::Length(max_name_len),
Constraint::Fill(1),
];
let table = Table::default()
.widths(widths)
.header(header)
.column_spacing(2)
.highlight_spacing(HighlightSpacing::Always)
.highlight_style(Style::new().bg(ratatui::style::Color::Rgb(50, 50, 50)))
.highlight_symbol("🦀")
.block(Block::default().borders(Borders::BOTTOM));
let selected = app_state.current_exercise_ind();
let table_state = TableState::default()
.with_offset(selected.saturating_sub(10))
.with_selected(Some(selected));
.map_or(name_col_title_len, |max| max.max(name_col_title_len));
let filter = Filter::None;
let n_rows = app_state.exercises().len();
let n_rows_with_filter = app_state.exercises().len();
let selected = app_state.current_exercise_ind();
let slf = Self {
table,
let mut slf = Self {
message: String::with_capacity(128),
filter,
app_state,
table_state,
n_rows,
name_col_width,
filter,
n_rows_with_filter,
selected_row: Some(selected),
row_offset: selected.saturating_sub(MAX_SCROLL_PADDING),
// Set by `set_term_size`
term_width: 0,
term_height: 0,
separator_line: Vec::new(),
narrow_term: false,
show_footer: true,
max_n_rows_to_display: 0,
scroll_padding: 0,
};
slf.with_updated_rows()
let (width, height) = terminal::size()?;
slf.set_term_size(width, height);
slf.draw(stdout)?;
Ok(slf)
}
pub fn select_next(&mut self) {
if self.n_rows > 0 {
let next = self
.table_state
.selected()
.map_or(0, |selected| (selected + 1).min(self.n_rows - 1));
self.table_state.select(Some(next));
}
fn update_offset(&mut self) {
let Some(selected) = self.selected_row else {
return;
};
let min_offset = (selected + self.scroll_padding)
.saturating_sub(self.max_n_rows_to_display.saturating_sub(1));
let max_offset = selected.saturating_sub(self.scroll_padding);
let global_max_offset = self
.n_rows_with_filter
.saturating_sub(self.max_n_rows_to_display);
self.row_offset = self
.row_offset
.max(min_offset)
.min(max_offset)
.min(global_max_offset);
}
pub fn select_previous(&mut self) {
if self.n_rows > 0 {
let previous = self
.table_state
.selected()
.map_or(0, |selected| selected.saturating_sub(1));
self.table_state.select(Some(previous));
}
pub fn set_term_size(&mut self, width: u16, height: u16) {
self.term_width = width;
self.term_height = height;
if height == 0 {
return;
}
pub fn select_first(&mut self) {
if self.n_rows > 0 {
self.table_state.select(Some(0));
}
let wide_help_footer_width = 95;
// The help footer is shorter when nothing is selected.
self.narrow_term = width < wide_help_footer_width && self.selected_row.is_some();
let header_height = 1;
// 2 separator, 1 progress bar, 1-2 footer message.
let footer_height = 4 + u16::from(self.narrow_term);
self.show_footer = height > header_height + footer_height;
if self.show_footer {
self.separator_line = "".as_bytes().repeat(width as usize);
}
pub fn select_last(&mut self) {
if self.n_rows > 0 {
self.table_state.select(Some(self.n_rows - 1));
}
self.max_n_rows_to_display = height
.saturating_sub(header_height + u16::from(self.show_footer) * footer_height)
as usize;
self.scroll_padding = (self.max_n_rows_to_display / 4).min(MAX_SCROLL_PADDING);
self.update_offset();
}
pub fn draw(&mut self, frame: &mut Frame) -> Result<()> {
let area = frame.area();
let narrow = area.width < 95;
let narrow_u16 = u16::from(narrow);
let table_height = area.height - 3 - narrow_u16;
fn draw_rows(
&self,
stdout: &mut StdoutLock,
filtered_exercises: impl Iterator<Item = (usize, &'a Exercise)>,
) -> io::Result<usize> {
let current_exercise_ind = self.app_state.current_exercise_ind();
let mut n_displayed_rows = 0;
frame.render_stateful_widget(
&self.table,
Rect {
x: 0,
y: 0,
width: area.width,
height: table_height,
},
&mut self.table_state,
);
for (exercise_ind, exercise) in filtered_exercises
.skip(self.row_offset)
.take(self.max_n_rows_to_display)
{
let mut writer = MaxLenWriter::new(stdout, self.term_width as usize);
frame.render_widget(
Paragraph::new(progress_bar_ratatui(
if self.selected_row == Some(self.row_offset + n_displayed_rows) {
writer.stdout.queue(SetBackgroundColor(Color::Rgb {
r: 40,
g: 40,
b: 40,
}))?;
// The crab emoji has the width of two ascii chars.
writer.add_to_len(2);
writer.stdout.write_all("🦀".as_bytes())?;
} else {
writer.write_ascii(b" ")?;
}
if exercise_ind == current_exercise_ind {
writer.stdout.queue(SetForegroundColor(Color::Red))?;
writer.write_ascii(b">>>>>>> ")?;
} else {
writer.write_ascii(b" ")?;
}
if exercise.done {
writer.stdout.queue(SetForegroundColor(Color::Green))?;
writer.write_ascii(b"DONE ")?;
} else {
writer.stdout.queue(SetForegroundColor(Color::Yellow))?;
writer.write_ascii(b"PENDING ")?;
}
writer.stdout.queue(SetForegroundColor(Color::Reset))?;
writer.write_str(exercise.name)?;
writer.write_ascii(&SPACE[..self.name_col_width + 2 - exercise.name.len()])?;
terminal_file_link(&mut writer, exercise.path, Color::Blue)?;
next_ln(stdout)?;
stdout.queue(ResetColor)?;
n_displayed_rows += 1;
}
Ok(n_displayed_rows)
}
pub fn draw(&mut self, stdout: &mut StdoutLock) -> io::Result<()> {
if self.term_height == 0 {
return Ok(());
}
stdout.queue(BeginSynchronizedUpdate)?.queue(MoveTo(0, 0))?;
// Header
let mut writer = MaxLenWriter::new(stdout, self.term_width as usize);
writer.write_ascii(b" Current State Name")?;
writer.write_ascii(&SPACE[..self.name_col_width - 2])?;
writer.write_ascii(b"Path")?;
next_ln(stdout)?;
// Rows
let iter = self.app_state.exercises().iter().enumerate();
let n_displayed_rows = match self.filter {
Filter::Done => self.draw_rows(stdout, iter.filter(|(_, exercise)| exercise.done))?,
Filter::Pending => {
self.draw_rows(stdout, iter.filter(|(_, exercise)| !exercise.done))?
}
Filter::None => self.draw_rows(stdout, iter)?,
};
for _ in 0..self.max_n_rows_to_display - n_displayed_rows {
next_ln(stdout)?;
}
if self.show_footer {
stdout.write_all(&self.separator_line)?;
next_ln(stdout)?;
progress_bar(
&mut MaxLenWriter::new(stdout, self.term_width as usize),
self.app_state.n_done(),
self.app_state.exercises().len() as u16,
area.width,
)?)
.block(Block::default().borders(Borders::BOTTOM)),
Rect {
x: 0,
y: table_height,
width: area.width,
height: 2,
},
);
self.term_width,
)?;
next_ln(stdout)?;
let message = if self.message.is_empty() {
// Help footer.
let mut text = Text::default();
let mut spans = Vec::with_capacity(4);
spans.push(Span::raw(
"↓/j ↑/k home/g end/G │ <c>ontinue at │ <r>eset exercise │",
));
stdout.write_all(&self.separator_line)?;
next_ln(stdout)?;
if narrow {
text.push_line(mem::take(&mut spans));
spans.push(Span::raw("filter "));
let mut writer = MaxLenWriter::new(stdout, self.term_width as usize);
if self.message.is_empty() {
// Help footer message
if self.selected_row.is_some() {
writer.write_str("↓/j ↑/k home/g end/G | <c>ontinue at | <r>eset exercise")?;
if self.narrow_term {
next_ln(stdout)?;
writer = MaxLenWriter::new(stdout, self.term_width as usize);
writer.write_ascii(b"filter ")?;
} else {
spans.push(Span::raw(" filter "));
writer.write_ascii(b" | filter ")?;
}
} else {
// Nothing selected (and nothing shown), so only display filter and quit.
writer.write_ascii(b"filter ")?;
}
match self.filter {
Filter::Done => {
spans.push("<d>one".underlined().magenta());
spans.push(Span::raw("/<p>ending"));
writer
.stdout
.queue(SetForegroundColor(Color::Magenta))?
.queue(SetAttribute(Attribute::Underlined))?;
writer.write_ascii(b"<d>one")?;
writer.stdout.queue(ResetColor)?;
writer.write_ascii(b"/<p>ending")?;
}
Filter::Pending => {
spans.push(Span::raw("<d>one/"));
spans.push("<p>ending".underlined().magenta());
writer.write_ascii(b"<d>one/")?;
writer
.stdout
.queue(SetForegroundColor(Color::Magenta))?
.queue(SetAttribute(Attribute::Underlined))?;
writer.write_ascii(b"<p>ending")?;
writer.stdout.queue(ResetColor)?;
}
Filter::None => spans.push(Span::raw("<d>one/<p>ending")),
Filter::None => writer.write_ascii(b"<d>one/<p>ending")?,
}
spans.push(Span::raw(" │ <q>uit list"));
text.push_line(spans);
text
writer.write_ascii(b" | <q>uit list")?;
} else {
Text::from(self.message.as_str().light_blue())
writer.stdout.queue(SetForegroundColor(Color::Magenta))?;
writer.write_str(&self.message)?;
stdout.queue(ResetColor)?;
next_ln(stdout)?;
}
next_ln(stdout)?;
}
stdout.queue(EndSynchronizedUpdate)?.flush()
}
fn set_selected(&mut self, selected: usize) {
self.selected_row = Some(selected);
self.update_offset();
}
fn update_rows(&mut self) {
self.n_rows_with_filter = match self.filter {
Filter::Done => self
.app_state
.exercises()
.iter()
.filter(|exercise| exercise.done)
.count(),
Filter::Pending => self
.app_state
.exercises()
.iter()
.filter(|exercise| !exercise.done)
.count(),
Filter::None => self.app_state.exercises().len(),
};
frame.render_widget(
message,
Rect {
x: 0,
y: table_height + 2,
width: area.width,
height: 1 + narrow_u16,
},
if self.n_rows_with_filter == 0 {
self.selected_row = None;
return;
}
self.set_selected(
self.selected_row
.map_or(0, |selected| selected.min(self.n_rows_with_filter - 1)),
);
}
#[inline]
pub fn filter(&self) -> Filter {
self.filter
}
pub fn set_filter(&mut self, filter: Filter) {
self.filter = filter;
self.update_rows();
}
pub fn select_next(&mut self) {
if let Some(selected) = self.selected_row {
self.set_selected((selected + 1).min(self.n_rows_with_filter - 1));
}
}
pub fn select_previous(&mut self) {
if let Some(selected) = self.selected_row {
self.set_selected(selected.saturating_sub(1));
}
}
pub fn select_first(&mut self) {
if self.n_rows_with_filter > 0 {
self.set_selected(0);
}
}
pub fn select_last(&mut self) {
if self.n_rows_with_filter > 0 {
self.set_selected(self.n_rows_with_filter - 1);
}
}
fn selected_to_exercise_ind(&self, selected: usize) -> Result<usize> {
match self.filter {
Filter::Done => self
.app_state
.exercises()
.iter()
.enumerate()
.filter(|(_, exercise)| exercise.done)
.nth(selected)
.context("Invalid selection index")
.map(|(ind, _)| ind),
Filter::Pending => self
.app_state
.exercises()
.iter()
.enumerate()
.filter(|(_, exercise)| !exercise.done)
.nth(selected)
.context("Invalid selection index")
.map(|(ind, _)| ind),
Filter::None => Ok(selected),
}
}
pub fn reset_selected(&mut self) -> Result<()> {
let Some(selected) = self.selected_row else {
self.message.push_str("Nothing selected to reset!");
return Ok(());
};
let exercise_ind = self.selected_to_exercise_ind(selected)?;
let exercise_name = self.app_state.reset_exercise_by_ind(exercise_ind)?;
self.update_rows();
write!(
self.message,
"The exercise `{exercise_name}` has been reset",
)?;
Ok(())
}
pub fn with_reset_selected(mut self) -> Result<Self> {
let Some(selected) = self.table_state.selected() else {
return Ok(self);
// Return `true` if there was something to select.
pub fn selected_to_current_exercise(&mut self) -> Result<bool> {
let Some(selected) = self.selected_row else {
self.message.push_str("Nothing selected to continue at!");
return Ok(false);
};
let ind = self
.app_state
.exercises()
.iter()
.enumerate()
.filter_map(|(ind, exercise)| match self.filter {
Filter::Done => exercise.done.then_some(ind),
Filter::Pending => (!exercise.done).then_some(ind),
Filter::None => Some(ind),
})
.nth(selected)
.context("Invalid selection index")?;
let exercise_ind = self.selected_to_exercise_ind(selected)?;
self.app_state.set_current_exercise_ind(exercise_ind)?;
let exercise_path = self.app_state.reset_exercise_by_ind(ind)?;
write!(self.message, "The exercise {exercise_path} has been reset")?;
Ok(self.with_updated_rows())
}
pub fn selected_to_current_exercise(&mut self) -> Result<()> {
let Some(selected) = self.table_state.selected() else {
return Ok(());
};
let ind = self
.app_state
.exercises()
.iter()
.enumerate()
.filter_map(|(ind, exercise)| match self.filter {
Filter::Done => exercise.done.then_some(ind),
Filter::Pending => (!exercise.done).then_some(ind),
Filter::None => Some(ind),
})
.nth(selected)
.context("Invalid selection index")?;
self.app_state.set_current_exercise_ind(ind)
Ok(true)
}
}

View file

@ -20,13 +20,12 @@ mod exercise;
mod info_file;
mod init;
mod list;
mod progress_bar;
mod run;
mod term;
mod terminal_link;
mod watch;
const CURRENT_FORMAT_VERSION: u8 = 1;
const MAX_EXERCISE_NAME_LEN: usize = 32;
/// Rustlings is a collection of small exercises to get you used to writing and reading Rust code
#[derive(Parser)]

View file

@ -1,100 +0,0 @@
use anyhow::{bail, Result};
use ratatui::text::{Line, Span};
use std::fmt::Write;
const PREFIX: &str = "Progress: [";
const PREFIX_WIDTH: u16 = PREFIX.len() as u16;
// Leaving the last char empty (_) for `total` > 99.
const POSTFIX_WIDTH: u16 = "] xxx/xx exercises_".len() as u16;
const WRAPPER_WIDTH: u16 = PREFIX_WIDTH + POSTFIX_WIDTH;
const MIN_LINE_WIDTH: u16 = WRAPPER_WIDTH + 4;
const PROGRESS_EXCEEDS_MAX_ERR: &str =
"The progress of the progress bar is higher than the maximum";
/// Terminal progress bar to be used when not using Ratataui.
pub fn progress_bar(progress: u16, total: u16, line_width: u16) -> Result<String> {
use ratatui::crossterm::style::Stylize;
if progress > total {
bail!(PROGRESS_EXCEEDS_MAX_ERR);
}
if line_width < MIN_LINE_WIDTH {
return Ok(format!("Progress: {progress}/{total} exercises"));
}
let mut line = String::with_capacity(usize::from(line_width));
line.push_str(PREFIX);
let width = line_width - WRAPPER_WIDTH;
let filled = (width * progress) / total;
let mut green_part = String::with_capacity(usize::from(filled + 1));
for _ in 0..filled {
green_part.push('#');
}
if filled < width {
green_part.push('>');
}
write!(line, "{}", green_part.green()).unwrap();
let width_minus_filled = width - filled;
if width_minus_filled > 1 {
let red_part_width = width_minus_filled - 1;
let mut red_part = String::with_capacity(usize::from(red_part_width));
for _ in 0..red_part_width {
red_part.push('-');
}
write!(line, "{}", red_part.red()).unwrap();
}
writeln!(line, "] {progress:>3}/{total} exercises").unwrap();
Ok(line)
}
/// Progress bar to be used with Ratataui.
// Not using Ratatui's Gauge widget to keep the progress bar consistent.
pub fn progress_bar_ratatui(progress: u16, total: u16, line_width: u16) -> Result<Line<'static>> {
use ratatui::style::Stylize;
if progress > total {
bail!(PROGRESS_EXCEEDS_MAX_ERR);
}
if line_width < MIN_LINE_WIDTH {
return Ok(Line::raw(format!("Progress: {progress}/{total} exercises")));
}
let mut spans = Vec::with_capacity(4);
spans.push(Span::raw(PREFIX));
let width = line_width - WRAPPER_WIDTH;
let filled = (width * progress) / total;
let mut green_part = String::with_capacity(usize::from(filled + 1));
for _ in 0..filled {
green_part.push('#');
}
if filled < width {
green_part.push('>');
}
spans.push(green_part.green());
let width_minus_filled = width - filled;
if width_minus_filled > 1 {
let red_part_width = width_minus_filled - 1;
let mut red_part = String::with_capacity(usize::from(red_part_width));
for _ in 0..red_part_width {
red_part.push('-');
}
spans.push(red_part.red());
}
spans.push(Span::raw(format!("] {progress:>3}/{total} exercises")));
Ok(Line::from(spans))
}

View file

@ -1,11 +1,17 @@
use anyhow::{bail, Result};
use ratatui::crossterm::style::{style, Stylize};
use std::io::{self, Write};
use anyhow::Result;
use crossterm::{
style::{Color, ResetColor, SetForegroundColor},
QueueableCommand,
};
use std::{
io::{self, Write},
process::exit,
};
use crate::{
app_state::{AppState, ExercisesProgress},
exercise::{RunnableExercise, OUTPUT_CAPACITY},
terminal_link::TerminalFileLink,
exercise::{solution_link_line, RunnableExercise, OUTPUT_CAPACITY},
term::terminal_file_link,
};
pub fn run(app_state: &mut AppState) -> Result<()> {
@ -19,35 +25,31 @@ pub fn run(app_state: &mut AppState) -> Result<()> {
if !success {
app_state.set_pending(app_state.current_exercise_ind())?;
bail!(
"Ran {} with errors",
app_state.current_exercise().terminal_link(),
);
stdout.write_all(b"Ran ")?;
terminal_file_link(&mut stdout, app_state.current_exercise().path, Color::Blue)?;
stdout.write_all(b" with errors\n")?;
exit(1);
}
writeln!(
stdout,
"{}{}",
"✓ Successfully ran ".green(),
exercise.path.green(),
)?;
stdout.queue(SetForegroundColor(Color::Green))?;
stdout.write_all("✓ Successfully ran ".as_bytes())?;
stdout.write_all(exercise.path.as_bytes())?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n")?;
if let Some(solution_path) = app_state.current_solution_path()? {
writeln!(
stdout,
"\n{} for comparison: {}\n",
"Solution".bold(),
style(TerminalFileLink(&solution_path)).underlined().cyan(),
)?;
stdout.write_all(b"\n")?;
solution_link_line(&mut stdout, &solution_path)?;
stdout.write_all(b"\n")?;
}
match app_state.done_current_exercise(&mut stdout)? {
ExercisesProgress::CurrentPending | ExercisesProgress::NewPending => {
stdout.write_all(b"Next exercise: ")?;
terminal_file_link(&mut stdout, app_state.current_exercise().path, Color::Blue)?;
stdout.write_all(b"\n")?;
}
ExercisesProgress::AllDone => (),
ExercisesProgress::CurrentPending | ExercisesProgress::NewPending => writeln!(
stdout,
"Next exercise: {}",
app_state.current_exercise().terminal_link(),
)?,
}
Ok(())

View file

@ -1,7 +1,153 @@
use std::io::{self, BufRead, StdoutLock, Write};
use std::{
cell::Cell,
env, fmt, fs,
io::{self, BufRead, StdoutLock, Write},
};
use crossterm::{
cursor::MoveTo,
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
terminal::{Clear, ClearType},
Command, QueueableCommand,
};
thread_local! {
static VS_CODE: Cell<bool> = Cell::new(env::var_os("TERM_PROGRAM").is_some_and(|v| v == "vscode"));
}
pub struct MaxLenWriter<'a, 'b> {
pub stdout: &'a mut StdoutLock<'b>,
len: usize,
max_len: usize,
}
impl<'a, 'b> MaxLenWriter<'a, 'b> {
#[inline]
pub fn new(stdout: &'a mut StdoutLock<'b>, max_len: usize) -> Self {
Self {
stdout,
len: 0,
max_len,
}
}
// Additional is for emojis that take more space.
#[inline]
pub fn add_to_len(&mut self, additional: usize) {
self.len += additional;
}
}
pub trait CountedWrite<'a> {
fn write_ascii(&mut self, ascii: &[u8]) -> io::Result<()>;
fn write_str(&mut self, unicode: &str) -> io::Result<()>;
fn stdout(&mut self) -> &mut StdoutLock<'a>;
}
impl<'a, 'b> CountedWrite<'b> for MaxLenWriter<'a, 'b> {
fn write_ascii(&mut self, ascii: &[u8]) -> io::Result<()> {
let n = ascii.len().min(self.max_len.saturating_sub(self.len));
if n > 0 {
self.stdout.write_all(&ascii[..n])?;
self.len += n;
}
Ok(())
}
fn write_str(&mut self, unicode: &str) -> io::Result<()> {
if let Some((ind, c)) = unicode
.char_indices()
.take(self.max_len.saturating_sub(self.len))
.last()
{
self.stdout
.write_all(&unicode.as_bytes()[..ind + c.len_utf8()])?;
self.len += ind + 1;
}
Ok(())
}
#[inline]
fn stdout(&mut self) -> &mut StdoutLock<'b> {
self.stdout
}
}
impl<'a> CountedWrite<'a> for StdoutLock<'a> {
#[inline]
fn write_ascii(&mut self, ascii: &[u8]) -> io::Result<()> {
self.write_all(ascii)
}
#[inline]
fn write_str(&mut self, unicode: &str) -> io::Result<()> {
self.write_all(unicode.as_bytes())
}
#[inline]
fn stdout(&mut self) -> &mut StdoutLock<'a> {
self
}
}
/// Terminal progress bar to be used when not using Ratataui.
pub fn progress_bar<'a>(
writer: &mut impl CountedWrite<'a>,
progress: u16,
total: u16,
line_width: u16,
) -> io::Result<()> {
debug_assert!(progress <= total);
const PREFIX: &[u8] = b"Progress: [";
const PREFIX_WIDTH: u16 = PREFIX.len() as u16;
// Leaving the last char empty (_) for `total` > 99.
const POSTFIX_WIDTH: u16 = "] xxx/xx exercises_".len() as u16;
const WRAPPER_WIDTH: u16 = PREFIX_WIDTH + POSTFIX_WIDTH;
const MIN_LINE_WIDTH: u16 = WRAPPER_WIDTH + 4;
if line_width < MIN_LINE_WIDTH {
writer.write_ascii(b"Progress: ")?;
// Integers are in ASCII.
writer.write_ascii(format!("{progress}/{total}").as_bytes())?;
return writer.write_ascii(b" exercises");
}
let stdout = writer.stdout();
stdout.write_all(PREFIX)?;
let width = line_width - WRAPPER_WIDTH;
let filled = (width * progress) / total;
stdout.queue(SetForegroundColor(Color::Green))?;
for _ in 0..filled {
stdout.write_all(b"#")?;
}
if filled < width {
stdout.write_all(b">")?;
}
let width_minus_filled = width - filled;
if width_minus_filled > 1 {
let red_part_width = width_minus_filled - 1;
stdout.queue(SetForegroundColor(Color::Red))?;
for _ in 0..red_part_width {
stdout.write_all(b"-")?;
}
}
stdout.queue(ResetColor)?;
write!(stdout, "] {progress:>3}/{total} exercises")
}
pub fn clear_terminal(stdout: &mut StdoutLock) -> io::Result<()> {
stdout.write_all(b"\x1b[H\x1b[2J\x1b[3J")
stdout
.queue(MoveTo(0, 0))?
.queue(Clear(ClearType::All))?
.queue(Clear(ClearType::Purge))
.map(|_| ())
}
pub fn press_enter_prompt(stdout: &mut StdoutLock) -> io::Result<()> {
@ -10,3 +156,58 @@ pub fn press_enter_prompt(stdout: &mut StdoutLock) -> io::Result<()> {
stdout.write_all(b"\n")?;
Ok(())
}
pub fn terminal_file_link<'a>(
writer: &mut impl CountedWrite<'a>,
path: &str,
color: Color,
) -> io::Result<()> {
// VS Code shows its own links. This also avoids some issues, especially on Windows.
if VS_CODE.get() {
return writer.write_str(path);
}
let canonical_path = fs::canonicalize(path).ok();
let Some(canonical_path) = canonical_path.as_deref().and_then(|p| p.to_str()) else {
return writer.write_str(path);
};
// Windows itself can't handle its verbatim paths.
#[cfg(windows)]
let canonical_path = if canonical_path.len() > 5 && &canonical_path[0..4] == r"\\?\" {
&canonical_path[4..]
} else {
canonical_path
};
writer
.stdout()
.queue(SetForegroundColor(color))?
.queue(SetAttribute(Attribute::Underlined))?;
writer.stdout().write_all(b"\x1b]8;;file://")?;
writer.stdout().write_all(canonical_path.as_bytes())?;
writer.stdout().write_all(b"\x1b\\")?;
// Only this part is visible.
writer.write_str(path)?;
writer.stdout().write_all(b"\x1b]8;;\x1b\\")?;
writer
.stdout()
.queue(SetForegroundColor(Color::Reset))?
.queue(SetAttribute(Attribute::NoUnderline))?;
Ok(())
}
pub fn write_ansi(output: &mut Vec<u8>, command: impl Command) {
struct FmtWriter<'a>(&'a mut Vec<u8>);
impl fmt::Write for FmtWriter<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0.extend_from_slice(s.as_bytes());
Ok(())
}
}
let _ = command.write_ansi(&mut FmtWriter(output));
}

View file

@ -1,26 +0,0 @@
use std::{
fmt::{self, Display, Formatter},
fs,
};
pub struct TerminalFileLink<'a>(pub &'a str);
impl<'a> Display for TerminalFileLink<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let path = fs::canonicalize(self.0);
if let Some(path) = path.as_deref().ok().and_then(|path| path.to_str()) {
// Windows itself can't handle its verbatim paths.
#[cfg(windows)]
let path = if path.len() > 5 && &path[0..4] == r"\\?\" {
&path[4..]
} else {
path
};
write!(f, "\x1b]8;;file://{path}\x1b\\{}\x1b]8;;\x1b\\", self.0)
} else {
write!(f, "{}", self.0)
}
}
}

View file

@ -72,35 +72,32 @@ pub fn watch(
let mut watch_state = WatchState::new(app_state, manual_run);
watch_state.run_current_exercise()?;
let mut stdout = io::stdout().lock();
watch_state.run_current_exercise(&mut stdout)?;
thread::spawn(move || terminal_event_handler(tx, manual_run));
while let Ok(event) = rx.recv() {
match event {
WatchEvent::Input(InputEvent::Next) => match watch_state.next_exercise()? {
WatchEvent::Input(InputEvent::Next) => match watch_state.next_exercise(&mut stdout)? {
ExercisesProgress::AllDone => break,
ExercisesProgress::CurrentPending => watch_state.render()?,
ExercisesProgress::NewPending => watch_state.run_current_exercise()?,
ExercisesProgress::CurrentPending => watch_state.render(&mut stdout)?,
ExercisesProgress::NewPending => watch_state.run_current_exercise(&mut stdout)?,
},
WatchEvent::Input(InputEvent::Hint) => {
watch_state.show_hint()?;
}
WatchEvent::Input(InputEvent::Hint) => watch_state.show_hint(&mut stdout)?,
WatchEvent::Input(InputEvent::List) => {
return Ok(WatchExit::List);
}
WatchEvent::Input(InputEvent::Quit) => {
watch_state.into_writer().write_all(QUIT_MSG)?;
stdout.write_all(QUIT_MSG)?;
break;
}
WatchEvent::Input(InputEvent::Run) => watch_state.run_current_exercise()?,
WatchEvent::Input(InputEvent::Unrecognized) => watch_state.render()?,
WatchEvent::Input(InputEvent::Run) => watch_state.run_current_exercise(&mut stdout)?,
WatchEvent::Input(InputEvent::Unrecognized) => watch_state.render(&mut stdout)?,
WatchEvent::FileChange { exercise_ind } => {
watch_state.handle_file_change(exercise_ind)?;
}
WatchEvent::TerminalResize => {
watch_state.render()?;
watch_state.handle_file_change(exercise_ind, &mut stdout)?;
}
WatchEvent::TerminalResize => watch_state.render(&mut stdout)?,
WatchEvent::NotifyErr(e) => {
return Err(Error::from(e).context(NOTIFY_ERR));
}

View file

@ -1,16 +1,17 @@
use anyhow::Result;
use ratatui::crossterm::{
style::{style, Stylize},
terminal,
use crossterm::{
style::{
Attribute, Attributes, Color, ResetColor, SetAttribute, SetAttributes, SetForegroundColor,
},
terminal, QueueableCommand,
};
use std::io::{self, StdoutLock, Write};
use crate::{
app_state::{AppState, ExercisesProgress},
clear_terminal,
exercise::{RunnableExercise, OUTPUT_CAPACITY},
progress_bar::progress_bar,
terminal_link::TerminalFileLink,
exercise::{solution_link_line, RunnableExercise, OUTPUT_CAPACITY},
term::{progress_bar, terminal_file_link},
};
#[derive(PartialEq, Eq)]
@ -21,7 +22,6 @@ enum DoneStatus {
}
pub struct WatchState<'a> {
writer: StdoutLock<'a>,
app_state: &'a mut AppState,
output: Vec<u8>,
show_hint: bool,
@ -31,10 +31,7 @@ pub struct WatchState<'a> {
impl<'a> WatchState<'a> {
pub fn new(app_state: &'a mut AppState, manual_run: bool) -> Self {
let writer = io::stdout().lock();
Self {
writer,
app_state,
output: Vec::with_capacity(OUTPUT_CAPACITY),
show_hint: false,
@ -43,16 +40,11 @@ impl<'a> WatchState<'a> {
}
}
#[inline]
pub fn into_writer(self) -> StdoutLock<'a> {
self.writer
}
pub fn run_current_exercise(&mut self) -> Result<()> {
pub fn run_current_exercise(&mut self, stdout: &mut StdoutLock) -> Result<()> {
self.show_hint = false;
writeln!(
self.writer,
stdout,
"\nChecking the exercise `{}`. Please wait…",
self.app_state.current_exercise().name,
)?;
@ -76,10 +68,15 @@ impl<'a> WatchState<'a> {
self.done_status = DoneStatus::Pending;
}
self.render()
self.render(stdout)?;
Ok(())
}
pub fn handle_file_change(&mut self, exercise_ind: usize) -> Result<()> {
pub fn handle_file_change(
&mut self,
exercise_ind: usize,
stdout: &mut StdoutLock,
) -> Result<()> {
// Don't skip exercises on file changes to avoid confusion from missing exercises.
// Skipping exercises must be explicit in the interactive list.
// But going back to an earlier exercise on file change is fine.
@ -88,91 +85,115 @@ impl<'a> WatchState<'a> {
}
self.app_state.set_current_exercise_ind(exercise_ind)?;
self.run_current_exercise()
self.run_current_exercise(stdout)
}
/// Move on to the next exercise if the current one is done.
pub fn next_exercise(&mut self) -> Result<ExercisesProgress> {
pub fn next_exercise(&mut self, stdout: &mut StdoutLock) -> Result<ExercisesProgress> {
if self.done_status == DoneStatus::Pending {
return Ok(ExercisesProgress::CurrentPending);
}
self.app_state.done_current_exercise(&mut self.writer)
self.app_state.done_current_exercise(stdout)
}
fn show_prompt(&mut self) -> io::Result<()> {
self.writer.write_all(b"\n")?;
fn show_prompt(&self, stdout: &mut StdoutLock) -> io::Result<()> {
if self.manual_run {
write!(self.writer, "{}:run / ", 'r'.bold())?;
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"r")?;
stdout.queue(ResetColor)?;
stdout.write_all(b":run / ")?;
}
if self.done_status != DoneStatus::Pending {
write!(self.writer, "{}:{} / ", 'n'.bold(), "next".underlined())?;
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"n")?;
stdout.queue(ResetColor)?;
stdout.write_all(b":")?;
stdout.queue(SetAttribute(Attribute::Underlined))?;
stdout.write_all(b"next")?;
stdout.queue(ResetColor)?;
stdout.write_all(b" / ")?;
}
if !self.show_hint {
write!(self.writer, "{}:hint / ", 'h'.bold())?;
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"h")?;
stdout.queue(ResetColor)?;
stdout.write_all(b":hint / ")?;
}
write!(self.writer, "{}:list / {}:quit ? ", 'l'.bold(), 'q'.bold())?;
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"l")?;
stdout.queue(ResetColor)?;
stdout.write_all(b":list / ")?;
self.writer.flush()
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"q")?;
stdout.queue(ResetColor)?;
stdout.write_all(b":quit ? ")?;
stdout.flush()
}
pub fn render(&mut self) -> Result<()> {
pub fn render(&self, stdout: &mut StdoutLock) -> io::Result<()> {
// Prevent having the first line shifted if clearing wasn't successful.
self.writer.write_all(b"\n")?;
clear_terminal(&mut self.writer)?;
stdout.write_all(b"\n")?;
clear_terminal(stdout)?;
self.writer.write_all(&self.output)?;
stdout.write_all(&self.output)?;
if self.show_hint {
writeln!(
self.writer,
"{}\n{}\n",
"Hint".bold().cyan().underlined(),
self.app_state.current_exercise().hint,
)?;
stdout
.queue(SetAttributes(
Attributes::from(Attribute::Bold).with(Attribute::Underlined),
))?
.queue(SetForegroundColor(Color::Cyan))?;
stdout.write_all(b"Hint")?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n")?;
stdout.write_all(self.app_state.current_exercise().hint.as_bytes())?;
stdout.write_all(b"\n\n")?;
}
if self.done_status != DoneStatus::Pending {
writeln!(self.writer, "{}", "Exercise done ✓".bold().green())?;
stdout
.queue(SetAttribute(Attribute::Bold))?
.queue(SetForegroundColor(Color::Green))?;
stdout.write_all("Exercise done ✓".as_bytes())?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n")?;
if let DoneStatus::DoneWithSolution(solution_path) = &self.done_status {
writeln!(
self.writer,
"{} for comparison: {}",
"Solution".bold(),
style(TerminalFileLink(solution_path)).underlined().cyan(),
)?;
solution_link_line(stdout, solution_path)?;
}
writeln!(
self.writer,
"When done experimenting, enter `n` to move on to the next exercise 🦀\n",
stdout.write_all(
"When done experimenting, enter `n` to move on to the next exercise 🦀\n\n"
.as_bytes(),
)?;
}
let line_width = terminal::size()?.0;
let progress_bar = progress_bar(
progress_bar(
stdout,
self.app_state.n_done(),
self.app_state.exercises().len() as u16,
line_width,
)?;
writeln!(
self.writer,
"{progress_bar}Current exercise: {}",
self.app_state.current_exercise().terminal_link(),
)?;
self.show_prompt()?;
stdout.write_all(b"\nCurrent exercise: ")?;
terminal_file_link(stdout, self.app_state.current_exercise().path, Color::Blue)?;
stdout.write_all(b"\n\n")?;
self.show_prompt(stdout)?;
Ok(())
}
pub fn show_hint(&mut self) -> Result<()> {
pub fn show_hint(&mut self, stdout: &mut StdoutLock) -> io::Result<()> {
self.show_hint = true;
self.render()
self.render(stdout)
}
}

View file

@ -1,4 +1,4 @@
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use std::sync::mpsc::Sender;
use super::WatchEvent;
@ -78,7 +78,7 @@ pub fn terminal_event_handler(tx: Sender<WatchEvent>, manual_run: bool) {
return;
}
}
Event::FocusGained | Event::FocusLost | Event::Mouse(_) | Event::Paste(_) => continue,
Event::FocusGained | Event::FocusLost | Event::Mouse(_) => continue,
}
};