mirror of
https://github.com/rust-lang/rustlings.git
synced 2025-01-09 20:03:24 +03:00
Compare commits
7 commits
7f73219041
...
8e178ac60d
Author | SHA1 | Date | |
---|---|---|---|
8e178ac60d | |||
3ae6c208b2 | |||
563727f47f | |||
2b7ac91505 | |||
52c0f5b39e | |||
fef66b80ad | |||
b6f40f2ec8 |
236
src/app_state.rs
236
src/app_state.rs
|
@ -1,9 +1,5 @@
|
||||||
use anyhow::{bail, Context, Result};
|
use anyhow::{bail, Context, Result};
|
||||||
use crossterm::{
|
use crossterm::style::Stylize;
|
||||||
style::Stylize,
|
|
||||||
terminal::{Clear, ClearType},
|
|
||||||
ExecutableCommand,
|
|
||||||
};
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::{
|
use std::{
|
||||||
fs::{self, File},
|
fs::{self, File},
|
||||||
|
@ -13,6 +9,7 @@ use std::{
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
clear_terminal,
|
||||||
embedded::EMBEDDED_FILES,
|
embedded::EMBEDDED_FILES,
|
||||||
exercise::{Exercise, OUTPUT_CAPACITY},
|
exercise::{Exercise, OUTPUT_CAPACITY},
|
||||||
info_file::ExerciseInfo,
|
info_file::ExerciseInfo,
|
||||||
|
@ -33,6 +30,7 @@ pub enum StateFileStatus {
|
||||||
NotRead,
|
NotRead,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Parses parts of the output of `cargo metadata`.
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CargoMetadata {
|
struct CargoMetadata {
|
||||||
target_directory: PathBuf,
|
target_directory: PathBuf,
|
||||||
|
@ -41,14 +39,18 @@ struct CargoMetadata {
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
current_exercise_ind: usize,
|
current_exercise_ind: usize,
|
||||||
exercises: Vec<Exercise>,
|
exercises: Vec<Exercise>,
|
||||||
|
// Caches the number of done exercises to avoid iterating over all exercises every time.
|
||||||
n_done: u16,
|
n_done: u16,
|
||||||
final_message: String,
|
final_message: String,
|
||||||
|
// Preallocated buffer for reading and writing the state file.
|
||||||
file_buf: Vec<u8>,
|
file_buf: Vec<u8>,
|
||||||
official_exercises: bool,
|
official_exercises: bool,
|
||||||
|
// Cargo's target directory.
|
||||||
target_dir: PathBuf,
|
target_dir: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
|
// Update the app state from the state file.
|
||||||
fn update_from_file(&mut self) -> StateFileStatus {
|
fn update_from_file(&mut self) -> StateFileStatus {
|
||||||
self.file_buf.clear();
|
self.file_buf.clear();
|
||||||
self.n_done = 0;
|
self.n_done = 0;
|
||||||
|
@ -98,6 +100,7 @@ impl AppState {
|
||||||
exercise_infos: Vec<ExerciseInfo>,
|
exercise_infos: Vec<ExerciseInfo>,
|
||||||
final_message: String,
|
final_message: String,
|
||||||
) -> Result<(Self, StateFileStatus)> {
|
) -> Result<(Self, StateFileStatus)> {
|
||||||
|
// Get the target directory from Cargo.
|
||||||
let metadata_output = Command::new("cargo")
|
let metadata_output = Command::new("cargo")
|
||||||
.arg("metadata")
|
.arg("metadata")
|
||||||
.arg("-q")
|
.arg("-q")
|
||||||
|
@ -117,31 +120,7 @@ impl AppState {
|
||||||
|
|
||||||
let exercises = exercise_infos
|
let exercises = exercise_infos
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|mut exercise_info| {
|
.map(Exercise::from)
|
||||||
// Leaking to be able to borrow in the watch mode `Table`.
|
|
||||||
// Leaking is not a problem because the `AppState` instance lives until
|
|
||||||
// the end of the program.
|
|
||||||
let path = exercise_info.path().leak();
|
|
||||||
|
|
||||||
exercise_info.name.shrink_to_fit();
|
|
||||||
let name = exercise_info.name.leak();
|
|
||||||
let dir = exercise_info.dir.map(|mut dir| {
|
|
||||||
dir.shrink_to_fit();
|
|
||||||
&*dir.leak()
|
|
||||||
});
|
|
||||||
|
|
||||||
let hint = exercise_info.hint.trim().to_owned();
|
|
||||||
|
|
||||||
Exercise {
|
|
||||||
dir,
|
|
||||||
name,
|
|
||||||
path,
|
|
||||||
test: exercise_info.test,
|
|
||||||
strict_clippy: exercise_info.strict_clippy,
|
|
||||||
hint,
|
|
||||||
done: false,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
let mut slf = Self {
|
let mut slf = Self {
|
||||||
|
@ -184,6 +163,36 @@ impl AppState {
|
||||||
&self.target_dir
|
&self.target_dir
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Write the state file.
|
||||||
|
// The file's format is very simple:
|
||||||
|
// - The first line is a comment.
|
||||||
|
// - The second line is an empty line.
|
||||||
|
// - The third line is the name of the current exercise. It must end with `\n` even if there
|
||||||
|
// are no done exercises.
|
||||||
|
// - The fourth line is an empty line.
|
||||||
|
// - All remaining lines are the names of done exercises.
|
||||||
|
fn write(&mut self) -> Result<()> {
|
||||||
|
self.file_buf.clear();
|
||||||
|
|
||||||
|
self.file_buf
|
||||||
|
.extend_from_slice(b"DON'T EDIT THIS FILE!\n\n");
|
||||||
|
self.file_buf
|
||||||
|
.extend_from_slice(self.current_exercise().name.as_bytes());
|
||||||
|
self.file_buf.push(b'\n');
|
||||||
|
|
||||||
|
for exercise in &self.exercises {
|
||||||
|
if exercise.done {
|
||||||
|
self.file_buf.push(b'\n');
|
||||||
|
self.file_buf.extend_from_slice(exercise.name.as_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fs::write(STATE_FILE_NAME, &self.file_buf)
|
||||||
|
.with_context(|| format!("Failed to write the state file {STATE_FILE_NAME}"))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn set_current_exercise_ind(&mut self, ind: usize) -> Result<()> {
|
pub fn set_current_exercise_ind(&mut self, ind: usize) -> Result<()> {
|
||||||
if ind >= self.exercises.len() {
|
if ind >= self.exercises.len() {
|
||||||
bail!(BAD_INDEX_ERR);
|
bail!(BAD_INDEX_ERR);
|
||||||
|
@ -218,6 +227,8 @@ impl AppState {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Official exercises: Dump the original file from the binary.
|
||||||
|
// Third-party exercises: Reset the exercise file with `git stash`.
|
||||||
fn reset(&self, ind: usize, dir_name: Option<&str>, path: &str) -> Result<()> {
|
fn reset(&self, ind: usize, dir_name: Option<&str>, path: &str) -> Result<()> {
|
||||||
if self.official_exercises {
|
if self.official_exercises {
|
||||||
return EMBEDDED_FILES
|
return EMBEDDED_FILES
|
||||||
|
@ -271,6 +282,7 @@ impl AppState {
|
||||||
Ok(exercise.path)
|
Ok(exercise.path)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Return the index of the next pending exercise or `None` if all exercises are done.
|
||||||
fn next_pending_exercise_ind(&self) -> Option<usize> {
|
fn next_pending_exercise_ind(&self) -> Option<usize> {
|
||||||
if self.current_exercise_ind == self.exercises.len() - 1 {
|
if self.current_exercise_ind == self.exercises.len() - 1 {
|
||||||
// The last exercise is done.
|
// The last exercise is done.
|
||||||
|
@ -293,6 +305,8 @@ 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>> {
|
pub fn current_solution_path(&self) -> Result<Option<String>> {
|
||||||
if DEBUG_PROFILE {
|
if DEBUG_PROFILE {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
|
@ -328,6 +342,9 @@ 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, writer: &mut StdoutLock) -> Result<ExercisesProgress> {
|
||||||
let exercise = &mut self.exercises[self.current_exercise_ind];
|
let exercise = &mut self.exercises[self.current_exercise_ind];
|
||||||
if !exercise.done {
|
if !exercise.done {
|
||||||
|
@ -335,78 +352,48 @@ impl AppState {
|
||||||
self.n_done += 1;
|
self.n_done += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
let Some(ind) = self.next_pending_exercise_ind() else {
|
if let Some(ind) = self.next_pending_exercise_ind() {
|
||||||
writer.write_all(RERUNNING_ALL_EXERCISES_MSG)?;
|
self.set_current_exercise_ind(ind)?;
|
||||||
|
|
||||||
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
|
return Ok(ExercisesProgress::Pending);
|
||||||
for (exercise_ind, exercise) in self.exercises().iter().enumerate() {
|
|
||||||
write!(writer, "Running {exercise} ... ")?;
|
|
||||||
writer.flush()?;
|
|
||||||
|
|
||||||
let success = exercise.run(&mut output, &self.target_dir)?;
|
|
||||||
if !success {
|
|
||||||
writeln!(writer, "{}\n", "FAILED".red())?;
|
|
||||||
|
|
||||||
self.current_exercise_ind = exercise_ind;
|
|
||||||
|
|
||||||
// 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::Pending);
|
|
||||||
}
|
|
||||||
|
|
||||||
writeln!(writer, "{}", "ok".green())?;
|
|
||||||
}
|
|
||||||
|
|
||||||
writer.execute(Clear(ClearType::All))?;
|
|
||||||
writer.write_all(FENISH_LINE.as_bytes())?;
|
|
||||||
|
|
||||||
let final_message = self.final_message.trim();
|
|
||||||
if !final_message.is_empty() {
|
|
||||||
writer.write_all(final_message.as_bytes())?;
|
|
||||||
writer.write_all(b"\n")?;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Ok(ExercisesProgress::AllDone);
|
|
||||||
};
|
|
||||||
|
|
||||||
self.set_current_exercise_ind(ind)?;
|
|
||||||
|
|
||||||
Ok(ExercisesProgress::Pending)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write the state file.
|
|
||||||
// The file's format is very simple:
|
|
||||||
// - The first line is a comment.
|
|
||||||
// - The second line is an empty line.
|
|
||||||
// - The third line is the name of the current exercise. It must end with `\n` even if there
|
|
||||||
// are no done exercises.
|
|
||||||
// - The fourth line is an empty line.
|
|
||||||
// - All remaining lines are the names of done exercises.
|
|
||||||
fn write(&mut self) -> Result<()> {
|
|
||||||
self.file_buf.clear();
|
|
||||||
|
|
||||||
self.file_buf
|
|
||||||
.extend_from_slice(b"DON'T EDIT THIS FILE!\n\n");
|
|
||||||
self.file_buf
|
|
||||||
.extend_from_slice(self.current_exercise().name.as_bytes());
|
|
||||||
self.file_buf.push(b'\n');
|
|
||||||
|
|
||||||
for exercise in &self.exercises {
|
|
||||||
if exercise.done {
|
|
||||||
self.file_buf.push(b'\n');
|
|
||||||
self.file_buf.extend_from_slice(exercise.name.as_bytes());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fs::write(STATE_FILE_NAME, &self.file_buf)
|
writer.write_all(RERUNNING_ALL_EXERCISES_MSG)?;
|
||||||
.with_context(|| format!("Failed to write the state file {STATE_FILE_NAME}"))?;
|
|
||||||
|
|
||||||
Ok(())
|
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
|
||||||
|
for (exercise_ind, exercise) in self.exercises().iter().enumerate() {
|
||||||
|
write!(writer, "Running {exercise} ... ")?;
|
||||||
|
writer.flush()?;
|
||||||
|
|
||||||
|
let success = exercise.run(&mut output, &self.target_dir)?;
|
||||||
|
if !success {
|
||||||
|
writeln!(writer, "{}\n", "FAILED".red())?;
|
||||||
|
|
||||||
|
self.current_exercise_ind = exercise_ind;
|
||||||
|
|
||||||
|
// 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::Pending);
|
||||||
|
}
|
||||||
|
|
||||||
|
writeln!(writer, "{}", "ok".green())?;
|
||||||
|
}
|
||||||
|
|
||||||
|
clear_terminal(writer)?;
|
||||||
|
writer.write_all(FENISH_LINE.as_bytes())?;
|
||||||
|
|
||||||
|
let final_message = self.final_message.trim();
|
||||||
|
if !final_message.is_empty() {
|
||||||
|
writer.write_all(final_message.as_bytes())?;
|
||||||
|
writer.write_all(b"\n")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ExercisesProgress::AllDone)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -441,3 +428,56 @@ const FENISH_LINE: &str = "+----------------------------------------------------
|
||||||
▒▒ ▒▒ ▒▒ ▒▒\x1b[0m
|
▒▒ ▒▒ ▒▒ ▒▒\x1b[0m
|
||||||
|
|
||||||
";
|
";
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn dummy_exercise() -> Exercise {
|
||||||
|
Exercise {
|
||||||
|
dir: None,
|
||||||
|
name: "0",
|
||||||
|
path: "exercises/0.rs",
|
||||||
|
test: false,
|
||||||
|
strict_clippy: false,
|
||||||
|
hint: String::new(),
|
||||||
|
done: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn next_pending_exercise() {
|
||||||
|
let mut app_state = AppState {
|
||||||
|
current_exercise_ind: 0,
|
||||||
|
exercises: vec![dummy_exercise(), dummy_exercise(), dummy_exercise()],
|
||||||
|
n_done: 0,
|
||||||
|
final_message: String::new(),
|
||||||
|
file_buf: Vec::new(),
|
||||||
|
official_exercises: true,
|
||||||
|
target_dir: PathBuf::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut assert = |done: [bool; 3], expected: [Option<usize>; 3]| {
|
||||||
|
for (exercise, done) in app_state.exercises.iter_mut().zip(done) {
|
||||||
|
exercise.done = done;
|
||||||
|
}
|
||||||
|
for (ind, expected) in expected.into_iter().enumerate() {
|
||||||
|
app_state.current_exercise_ind = ind;
|
||||||
|
assert_eq!(
|
||||||
|
app_state.next_pending_exercise_ind(),
|
||||||
|
expected,
|
||||||
|
"done={done:?}, ind={ind}",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
assert([true, true, true], [None, None, None]);
|
||||||
|
assert([false, false, false], [Some(1), Some(2), Some(0)]);
|
||||||
|
assert([false, true, true], [None, Some(0), Some(0)]);
|
||||||
|
assert([true, false, true], [Some(1), None, Some(1)]);
|
||||||
|
assert([true, true, false], [Some(2), Some(2), None]);
|
||||||
|
assert([true, false, false], [Some(1), Some(2), Some(1)]);
|
||||||
|
assert([false, true, false], [Some(2), Some(2), Some(0)]);
|
||||||
|
assert([false, false, true], [Some(1), Some(0), Some(0)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -2,6 +2,10 @@ use anyhow::{Context, Result};
|
||||||
|
|
||||||
use crate::info_file::ExerciseInfo;
|
use crate::info_file::ExerciseInfo;
|
||||||
|
|
||||||
|
// Return the start and end index of the content of the list `bin = […]`.
|
||||||
|
// bin = [xxxxxxxxxxxxxxxxx]
|
||||||
|
// |start_ind |
|
||||||
|
// |end_ind
|
||||||
pub fn bins_start_end_ind(cargo_toml: &str) -> Result<(usize, usize)> {
|
pub fn bins_start_end_ind(cargo_toml: &str) -> Result<(usize, usize)> {
|
||||||
let start_ind = cargo_toml
|
let start_ind = cargo_toml
|
||||||
.find("bin = [")
|
.find("bin = [")
|
||||||
|
@ -16,6 +20,8 @@ pub fn bins_start_end_ind(cargo_toml: &str) -> Result<(usize, usize)> {
|
||||||
Ok((start_ind, end_ind))
|
Ok((start_ind, end_ind))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Generate and append the content of the `bin` list in `Cargo.toml`.
|
||||||
|
// The `exercise_path_prefix` is the prefix of the `path` field of every list entry.
|
||||||
pub fn append_bins(
|
pub fn append_bins(
|
||||||
buf: &mut Vec<u8>,
|
buf: &mut Vec<u8>,
|
||||||
exercise_infos: &[ExerciseInfo],
|
exercise_infos: &[ExerciseInfo],
|
||||||
|
@ -37,6 +43,7 @@ pub fn append_bins(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update the `bin` list and leave everything else unchanged.
|
||||||
pub fn updated_cargo_toml(
|
pub fn updated_cargo_toml(
|
||||||
exercise_infos: &[ExerciseInfo],
|
exercise_infos: &[ExerciseInfo],
|
||||||
current_cargo_toml: &str,
|
current_cargo_toml: &str,
|
||||||
|
@ -55,3 +62,61 @@ pub fn updated_cargo_toml(
|
||||||
|
|
||||||
Ok(updated_cargo_toml)
|
Ok(updated_cargo_toml)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_bins_start_end_ind() {
|
||||||
|
assert_eq!(bins_start_end_ind("").ok(), None);
|
||||||
|
assert_eq!(bins_start_end_ind("[]").ok(), None);
|
||||||
|
assert_eq!(bins_start_end_ind("bin = [").ok(), None);
|
||||||
|
assert_eq!(bins_start_end_ind("bin = ]").ok(), None);
|
||||||
|
assert_eq!(bins_start_end_ind("bin = []").ok(), Some((7, 7)));
|
||||||
|
assert_eq!(bins_start_end_ind("bin= []").ok(), None);
|
||||||
|
assert_eq!(bins_start_end_ind("bin =[]").ok(), None);
|
||||||
|
assert_eq!(bins_start_end_ind("bin=[]").ok(), None);
|
||||||
|
assert_eq!(bins_start_end_ind("bin = [\nxxx\n]").ok(), Some((7, 12)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_bins() {
|
||||||
|
let exercise_infos = [
|
||||||
|
ExerciseInfo {
|
||||||
|
name: String::from("1"),
|
||||||
|
dir: None,
|
||||||
|
test: true,
|
||||||
|
strict_clippy: true,
|
||||||
|
hint: String::new(),
|
||||||
|
},
|
||||||
|
ExerciseInfo {
|
||||||
|
name: String::from("2"),
|
||||||
|
dir: Some(String::from("d")),
|
||||||
|
test: false,
|
||||||
|
strict_clippy: false,
|
||||||
|
hint: String::new(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
let mut buf = Vec::with_capacity(128);
|
||||||
|
append_bins(&mut buf, &exercise_infos, b"");
|
||||||
|
assert_eq!(
|
||||||
|
buf,
|
||||||
|
br#"
|
||||||
|
{ name = "1", path = "exercises/1.rs" },
|
||||||
|
{ name = "2", path = "exercises/d/2.rs" },
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
updated_cargo_toml(&exercise_infos, "abc\nbin = [xxx]\n123", b"../").unwrap(),
|
||||||
|
br#"abc
|
||||||
|
bin = [
|
||||||
|
{ name = "1", path = "../exercises/1.rs" },
|
||||||
|
{ name = "2", path = "../exercises/d/2.rs" },
|
||||||
|
]
|
||||||
|
123"#,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -15,7 +15,7 @@ pub enum DevCommands {
|
||||||
New {
|
New {
|
||||||
/// The path to create the project in
|
/// The path to create the project in
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
/// Don't initialize a Git repository in the project directory
|
/// Don't try to initialize a Git repository in the project directory
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
no_git: bool,
|
no_git: bool,
|
||||||
},
|
},
|
||||||
|
|
|
@ -10,6 +10,7 @@ use std::{
|
||||||
use crate::{
|
use crate::{
|
||||||
cmd::{run_cmd, CargoCmd},
|
cmd::{run_cmd, CargoCmd},
|
||||||
in_official_repo,
|
in_official_repo,
|
||||||
|
info_file::ExerciseInfo,
|
||||||
terminal_link::TerminalFileLink,
|
terminal_link::TerminalFileLink,
|
||||||
DEBUG_PROFILE,
|
DEBUG_PROFILE,
|
||||||
};
|
};
|
||||||
|
@ -104,14 +105,7 @@ impl Exercise {
|
||||||
|
|
||||||
let test_success = CargoCmd {
|
let test_success = CargoCmd {
|
||||||
subcommand: "test",
|
subcommand: "test",
|
||||||
args: &[
|
args: &["--", "--color", "always", "--show-output"],
|
||||||
"--",
|
|
||||||
"--color",
|
|
||||||
"always",
|
|
||||||
"--show-output",
|
|
||||||
"--format",
|
|
||||||
"pretty",
|
|
||||||
],
|
|
||||||
exercise_name: self.name,
|
exercise_name: self.name,
|
||||||
description: "cargo test …",
|
description: "cargo test …",
|
||||||
// Hide warnings because they are shown by Clippy.
|
// Hide warnings because they are shown by Clippy.
|
||||||
|
@ -132,6 +126,34 @@ impl Exercise {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<ExerciseInfo> for Exercise {
|
||||||
|
fn from(mut exercise_info: ExerciseInfo) -> Self {
|
||||||
|
// Leaking to be able to borrow in the watch mode `Table`.
|
||||||
|
// Leaking is not a problem because the `AppState` instance lives until
|
||||||
|
// the end of the program.
|
||||||
|
let path = exercise_info.path().leak();
|
||||||
|
|
||||||
|
exercise_info.name.shrink_to_fit();
|
||||||
|
let name = exercise_info.name.leak();
|
||||||
|
let dir = exercise_info.dir.map(|mut dir| {
|
||||||
|
dir.shrink_to_fit();
|
||||||
|
&*dir.leak()
|
||||||
|
});
|
||||||
|
|
||||||
|
let hint = exercise_info.hint.trim().to_owned();
|
||||||
|
|
||||||
|
Exercise {
|
||||||
|
dir,
|
||||||
|
name,
|
||||||
|
path,
|
||||||
|
test: exercise_info.test,
|
||||||
|
strict_clippy: exercise_info.strict_clippy,
|
||||||
|
hint,
|
||||||
|
done: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Display for Exercise {
|
impl Display for Exercise {
|
||||||
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||||
self.path.fmt(f)
|
self.path.fmt(f)
|
||||||
|
|
37
src/main.rs
37
src/main.rs
|
@ -1,12 +1,8 @@
|
||||||
use anyhow::{bail, Context, Result};
|
use anyhow::{bail, Context, Result};
|
||||||
use app_state::StateFileStatus;
|
use app_state::StateFileStatus;
|
||||||
use clap::{Parser, Subcommand};
|
use clap::{Parser, Subcommand};
|
||||||
use crossterm::{
|
|
||||||
terminal::{Clear, ClearType},
|
|
||||||
ExecutableCommand,
|
|
||||||
};
|
|
||||||
use std::{
|
use std::{
|
||||||
io::{self, BufRead, Write},
|
io::{self, BufRead, StdoutLock, Write},
|
||||||
path::Path,
|
path::Path,
|
||||||
process::exit,
|
process::exit,
|
||||||
};
|
};
|
||||||
|
@ -40,6 +36,20 @@ const DEBUG_PROFILE: bool = {
|
||||||
debug_profile
|
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
|
/// Rustlings is a collection of small exercises to get you used to writing and reading Rust code
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[command(version)]
|
#[command(version)]
|
||||||
|
@ -54,7 +64,7 @@ struct Args {
|
||||||
|
|
||||||
#[derive(Subcommand)]
|
#[derive(Subcommand)]
|
||||||
enum Subcommands {
|
enum Subcommands {
|
||||||
/// Initialize Rustlings
|
/// Initialize the official Rustlings exercises
|
||||||
Init,
|
Init,
|
||||||
/// Run a single exercise. Runs the next pending exercise if the exercise name is not specified
|
/// Run a single exercise. Runs the next pending exercise if the exercise name is not specified
|
||||||
Run {
|
Run {
|
||||||
|
@ -76,10 +86,6 @@ enum Subcommands {
|
||||||
Dev(DevCommands),
|
Dev(DevCommands),
|
||||||
}
|
}
|
||||||
|
|
||||||
fn in_official_repo() -> bool {
|
|
||||||
Path::new("dev/rustlings-repo.txt").exists()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
let args = Args::parse();
|
let args = Args::parse();
|
||||||
|
|
||||||
|
@ -97,7 +103,7 @@ fn main() -> Result<()> {
|
||||||
let mut stdout = io::stdout().lock();
|
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.write_all(b"This command will create the directory `rustlings/` which will contain the exercises.\nPress ENTER to continue ")?;
|
||||||
stdout.flush()?;
|
stdout.flush()?;
|
||||||
io::stdin().lock().read_until(b'\n', &mut Vec::new())?;
|
press_enter_prompt()?;
|
||||||
stdout.write_all(b"\n")?;
|
stdout.write_all(b"\n")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -123,19 +129,18 @@ fn main() -> Result<()> {
|
||||||
info_file.final_message.unwrap_or_default(),
|
info_file.final_message.unwrap_or_default(),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
|
// Show the welcome message if the state file doesn't exist yet.
|
||||||
if let Some(welcome_message) = info_file.welcome_message {
|
if let Some(welcome_message) = info_file.welcome_message {
|
||||||
match state_file_status {
|
match state_file_status {
|
||||||
StateFileStatus::NotRead => {
|
StateFileStatus::NotRead => {
|
||||||
let mut stdout = io::stdout().lock();
|
let mut stdout = io::stdout().lock();
|
||||||
stdout.execute(Clear(ClearType::All))?;
|
clear_terminal(&mut stdout)?;
|
||||||
|
|
||||||
let welcome_message = welcome_message.trim();
|
let welcome_message = welcome_message.trim();
|
||||||
write!(stdout, "{welcome_message}\n\nPress ENTER to continue ")?;
|
write!(stdout, "{welcome_message}\n\nPress ENTER to continue ")?;
|
||||||
stdout.flush()?;
|
stdout.flush()?;
|
||||||
|
press_enter_prompt()?;
|
||||||
io::stdin().lock().read_until(b'\n', &mut Vec::new())?;
|
clear_terminal(&mut stdout)?;
|
||||||
|
|
||||||
stdout.execute(Clear(ClearType::All))?;
|
|
||||||
}
|
}
|
||||||
StateFileStatus::Read => (),
|
StateFileStatus::Read => (),
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,13 +1,13 @@
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use crossterm::{
|
use crossterm::{
|
||||||
style::{style, Stylize},
|
style::{style, Stylize},
|
||||||
terminal::{size, Clear, ClearType},
|
terminal::size,
|
||||||
ExecutableCommand,
|
|
||||||
};
|
};
|
||||||
use std::io::{self, StdoutLock, Write};
|
use std::io::{self, StdoutLock, Write};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
app_state::{AppState, ExercisesProgress},
|
app_state::{AppState, ExercisesProgress},
|
||||||
|
clear_terminal,
|
||||||
exercise::OUTPUT_CAPACITY,
|
exercise::OUTPUT_CAPACITY,
|
||||||
progress_bar::progress_bar,
|
progress_bar::progress_bar,
|
||||||
terminal_link::TerminalFileLink,
|
terminal_link::TerminalFileLink,
|
||||||
|
@ -111,7 +111,7 @@ impl<'a> WatchState<'a> {
|
||||||
// Prevent having the first line shifted.
|
// Prevent having the first line shifted.
|
||||||
self.writer.write_all(b"\n")?;
|
self.writer.write_all(b"\n")?;
|
||||||
|
|
||||||
self.writer.execute(Clear(ClearType::All))?;
|
clear_terminal(&mut self.writer)?;
|
||||||
|
|
||||||
self.writer.write_all(&self.output)?;
|
self.writer.write_all(&self.output)?;
|
||||||
self.writer.write_all(b"\n")?;
|
self.writer.write_all(b"\n")?;
|
||||||
|
|
Loading…
Reference in a new issue