summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormo8it <mo8it@proton.me>2024-08-25 23:53:50 +0200
committermo8it <mo8it@proton.me>2024-08-25 23:53:50 +0200
commitb1898f6d8b2c2ae45279ca4c67fa1b1a94acb936 (patch)
tree25022e8fc2bc6254fc819d98ea278f04dd5d6bab
parentd29e9e7e07a16adda35aea9ce9dd120b6ecc9dfc (diff)
Use queue instead of Stylize
-rw-r--r--src/app_state.rs18
-rw-r--r--src/exercise.rs49
-rw-r--r--src/init.rs23
-rw-r--r--src/main.rs1
-rw-r--r--src/run.rs54
-rw-r--r--src/term.rs49
-rw-r--r--src/terminal_link.rs26
-rw-r--r--src/watch/state.rs108
8 files changed, 189 insertions, 139 deletions
diff --git a/src/app_state.rs b/src/app_state.rs
index 8fd8f3b..d7de1fd 100644
--- a/src/app_state.rs
+++ b/src/app_state.rs
@@ -338,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;
@@ -350,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();
@@ -368,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));
}
}
@@ -395,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)
diff --git a/src/exercise.rs b/src/exercise.rs
index ac5c6e6..462287d 100644
--- a/src/exercise.rs
+++ b/src/exercise.rs
@@ -1,15 +1,27 @@
use anyhow::Result;
-use 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,9 @@ 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\n");
+ write_ansi(output, ResetColor);
}
let success = cmd_runner.run_debug_bin(bin_name, output.as_deref_mut())?;
@@ -28,13 +42,10 @@ 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)\n");
+ write_ansi(output, ResetColor);
}
}
@@ -53,18 +64,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;
diff --git a/src/init.rs b/src/init.rs
index 2c172dc..40d9910 100644
--- a/src/init.rs
+++ b/src/init.rs
@@ -1,5 +1,8 @@
use anyhow::{bail, Context, Result};
-use crossterm::style::Stylize;
+use crossterm::{
+ style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
+ QueueableCommand,
+};
use serde::Deserialize;
use std::{
env::set_current_dir,
@@ -144,12 +147,13 @@ 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 ✓\n\n".as_bytes())?;
+ stdout
+ .queue(ResetColor)?
+ .queue(SetAttribute(Attribute::Bold))?;
+ stdout.write_all(POST_INIT_MSG)?;
+ stdout.queue(ResetColor)?;
Ok(())
}
@@ -182,5 +186,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.
+";
diff --git a/src/main.rs b/src/main.rs
index 61dd8ea..998d3d1 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -22,7 +22,6 @@ mod init;
mod list;
mod run;
mod term;
-mod terminal_link;
mod watch;
const CURRENT_FORMAT_VERSION: u8 = 1;
diff --git a/src/run.rs b/src/run.rs
index 09e53ec..929b475 100644
--- a/src/run.rs
+++ b/src/run.rs
@@ -1,11 +1,17 @@
-use anyhow::{bail, Result};
-use 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(())
diff --git a/src/term.rs b/src/term.rs
index b993108..4c6ac90 100644
--- a/src/term.rs
+++ b/src/term.rs
@@ -1,10 +1,13 @@
-use std::io::{self, BufRead, StdoutLock, Write};
+use std::{
+ fmt, fs,
+ io::{self, BufRead, StdoutLock, Write},
+};
use crossterm::{
cursor::MoveTo,
- style::{Color, ResetColor, SetForegroundColor},
+ style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
terminal::{Clear, ClearType},
- QueueableCommand,
+ Command, QueueableCommand,
};
/// Terminal progress bar to be used when not using Ratataui.
@@ -68,3 +71,43 @@ pub fn press_enter_prompt(stdout: &mut StdoutLock) -> io::Result<()> {
stdout.write_all(b"\n")?;
Ok(())
}
+
+pub fn terminal_file_link(stdout: &mut StdoutLock, path: &str, color: Color) -> io::Result<()> {
+ let canonical_path = fs::canonicalize(path).ok();
+
+ let Some(canonical_path) = canonical_path.as_deref().and_then(|p| p.to_str()) else {
+ return stdout.write_all(path.as_bytes());
+ };
+
+ // 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
+ };
+
+ stdout
+ .queue(SetForegroundColor(color))?
+ .queue(SetAttribute(Attribute::Underlined))?;
+ write!(
+ stdout,
+ "\x1b]8;;file://{canonical_path}\x1b\\{path}\x1b]8;;\x1b\\",
+ )?;
+ stdout.queue(ResetColor)?;
+
+ 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));
+}
diff --git a/src/terminal_link.rs b/src/terminal_link.rs
deleted file mode 100644
index 9bea07d..0000000
--- a/src/terminal_link.rs
+++ /dev/null
@@ -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)
- }
- }
-}
diff --git a/src/watch/state.rs b/src/watch/state.rs
index 40e3d3e..f9fd138 100644
--- a/src/watch/state.rs
+++ b/src/watch/state.rs
@@ -1,16 +1,17 @@
use anyhow::Result;
use crossterm::{
- style::{style, Stylize},
- terminal,
+ 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},
- term::progress_bar,
- terminal_link::TerminalFileLink,
+ exercise::{solution_link_line, RunnableExercise, OUTPUT_CAPACITY},
+ term::{progress_bar, terminal_file_link},
};
#[derive(PartialEq, Eq)]
@@ -21,7 +22,7 @@ enum DoneStatus {
}
pub struct WatchState<'a> {
- writer: StdoutLock<'a>,
+ stdout: StdoutLock<'a>,
app_state: &'a mut AppState,
output: Vec<u8>,
show_hint: bool,
@@ -31,10 +32,11 @@ 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();
+ // TODO: Take stdout as arg.
+ let stdout = io::stdout().lock();
Self {
- writer,
+ stdout,
app_state,
output: Vec::with_capacity(OUTPUT_CAPACITY),
show_hint: false,
@@ -45,14 +47,14 @@ impl<'a> WatchState<'a> {
#[inline]
pub fn into_writer(self) -> StdoutLock<'a> {
- self.writer
+ self.stdout
}
pub fn run_current_exercise(&mut self) -> Result<()> {
self.show_hint = false;
writeln!(
- self.writer,
+ self.stdout,
"\nChecking the exercise `{}`. Please wait…",
self.app_state.current_exercise().name,
)?;
@@ -98,75 +100,101 @@ impl<'a> WatchState<'a> {
return Ok(ExercisesProgress::CurrentPending);
}
- self.app_state.done_current_exercise(&mut self.writer)
+ self.app_state.done_current_exercise(&mut self.stdout)
}
fn show_prompt(&mut self) -> io::Result<()> {
- self.writer.write_all(b"\n")?;
-
if self.manual_run {
- write!(self.writer, "{}:run / ", 'r'.bold())?;
+ self.stdout.queue(SetAttribute(Attribute::Bold))?;
+ self.stdout.write_all(b"r")?;
+ self.stdout.queue(ResetColor)?;
+ self.stdout.write_all(b":run / ")?;
}
if self.done_status != DoneStatus::Pending {
- write!(self.writer, "{}:{} / ", 'n'.bold(), "next".underlined())?;
+ self.stdout.queue(SetAttribute(Attribute::Bold))?;
+ self.stdout.write_all(b"n")?;
+ self.stdout.queue(ResetColor)?;
+ self.stdout.write_all(b":")?;
+ self.stdout.queue(SetAttribute(Attribute::Underlined))?;
+ self.stdout.write_all(b"next")?;
+ self.stdout.queue(ResetColor)?;
+ self.stdout.write_all(b" / ")?;
}
if !self.show_hint {
- write!(self.writer, "{}:hint / ", 'h'.bold())?;
+ self.stdout.queue(SetAttribute(Attribute::Bold))?;
+ self.stdout.write_all(b"h")?;
+ self.stdout.queue(ResetColor)?;
+ self.stdout.write_all(b":hint / ")?;
}
- write!(self.writer, "{}:list / {}:quit ? ", 'l'.bold(), 'q'.bold())?;
+ self.stdout.queue(SetAttribute(Attribute::Bold))?;
+ self.stdout.write_all(b"l")?;
+ self.stdout.queue(ResetColor)?;
+ self.stdout.write_all(b":list / ")?;
+
+ self.stdout.queue(SetAttribute(Attribute::Bold))?;
+ self.stdout.write_all(b"q")?;
+ self.stdout.queue(ResetColor)?;
+ self.stdout.write_all(b":quit ? ")?;
- self.writer.flush()
+ self.stdout.flush()
}
pub fn render(&mut self) -> io::Result<()> {
// Prevent having the first line shifted if clearing wasn't successful.
- self.writer.write_all(b"\n")?;
- clear_terminal(&mut self.writer)?;
+ self.stdout.write_all(b"\n")?;
+ clear_terminal(&mut self.stdout)?;
- self.writer.write_all(&self.output)?;
+ self.stdout.write_all(&self.output)?;
if self.show_hint {
- writeln!(
- self.writer,
- "{}\n{}\n",
- "Hint".bold().cyan().underlined(),
- self.app_state.current_exercise().hint,
- )?;
+ self.stdout
+ .queue(SetAttributes(
+ Attributes::from(Attribute::Bold).with(Attribute::Underlined),
+ ))?
+ .queue(SetForegroundColor(Color::Cyan))?;
+ self.stdout.write_all(b"Hint\n")?;
+ self.stdout.queue(ResetColor)?;
+
+ self.stdout
+ .write_all(self.app_state.current_exercise().hint.as_bytes())?;
+ self.stdout.write_all(b"\n\n")?;
}
if self.done_status != DoneStatus::Pending {
- writeln!(self.writer, "{}", "Exercise done ✓".bold().green())?;
+ self.stdout
+ .queue(SetAttribute(Attribute::Bold))?
+ .queue(SetForegroundColor(Color::Green))?;
+ self.stdout.write_all("Exercise done ✓\n".as_bytes())?;
+ self.stdout.queue(ResetColor)?;
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(&mut self.stdout, solution_path)?;
}
writeln!(
- self.writer,
+ self.stdout,
"When done experimenting, enter `n` to move on to the next exercise 🦀\n",
)?;
}
let line_width = terminal::size()?.0;
progress_bar(
- &mut self.writer,
+ &mut self.stdout,
self.app_state.n_done(),
self.app_state.exercises().len() as u16,
line_width,
)?;
- writeln!(
- self.writer,
- "\nCurrent exercise: {}",
- self.app_state.current_exercise().terminal_link(),
+
+ self.stdout.write_all(b"\nCurrent exercise: ")?;
+ terminal_file_link(
+ &mut self.stdout,
+ self.app_state.current_exercise().path,
+ Color::Blue,
)?;
+ self.stdout.write_all(b"\n\n")?;
self.show_prompt()?;