1
0
mirror of https://github.com/rust-lang/rustlings.git synced 2024-11-08 09:09:17 +01:00

Improve resetting

This commit is contained in:
mo8it 2024-04-18 12:41:17 +02:00
parent f04089b8bc
commit 01e6732e4d
4 changed files with 67 additions and 47 deletions

@ -7,9 +7,15 @@ use crossterm::{
use std::{ use std::{
fs::{self, File}, fs::{self, File},
io::{Read, StdoutLock, Write}, io::{Read, StdoutLock, Write},
path::Path,
process::{Command, Stdio},
}; };
use crate::{exercise::Exercise, info_file::ExerciseInfo}; use crate::{
embedded::{WriteStrategy, EMBEDDED_FILES},
exercise::Exercise,
info_file::ExerciseInfo,
};
const STATE_FILE_NAME: &str = ".rustlings-state.txt"; const STATE_FILE_NAME: &str = ".rustlings-state.txt";
const BAD_INDEX_ERR: &str = "The current exercise index is higher than the number of exercises"; const BAD_INDEX_ERR: &str = "The current exercise index is higher than the number of exercises";
@ -31,6 +37,7 @@ pub struct AppState {
n_done: u16, n_done: u16,
final_message: String, final_message: String,
file_buf: Vec<u8>, file_buf: Vec<u8>,
official_exercises: bool,
} }
impl AppState { impl AppState {
@ -111,6 +118,7 @@ impl AppState {
n_done: 0, n_done: 0,
final_message, final_message,
file_buf: Vec::with_capacity(2048), file_buf: Vec::with_capacity(2048),
official_exercises: !Path::new("info.toml").exists(),
}; };
let state_file_status = slf.update_from_file(); let state_file_status = slf.update_from_file();
@ -172,6 +180,53 @@ impl AppState {
Ok(()) Ok(())
} }
fn reset_path(&self, path: &str) -> Result<()> {
if self.official_exercises {
return EMBEDDED_FILES
.write_exercise_to_disk(path, WriteStrategy::Overwrite)
.with_context(|| format!("Failed to reset the exercise {path}"));
}
let output = Command::new("git")
.arg("stash")
.arg("push")
.arg("--")
.arg(path)
.stdin(Stdio::null())
.stdout(Stdio::null())
.output()
.with_context(|| format!("Failed to run `git stash push -- {path}`"))?;
if !output.status.success() {
bail!(
"`git stash push -- {path}` didn't run successfully: {}",
String::from_utf8_lossy(&output.stderr),
);
}
Ok(())
}
pub fn reset_current_exercise(&mut self) -> Result<&'static str> {
let path = self.current_exercise().path;
self.set_pending(self.current_exercise_ind)?;
self.reset_path(path)?;
Ok(path)
}
pub fn reset_exercise_by_ind(&mut self, exercise_ind: usize) -> Result<&'static str> {
if exercise_ind >= self.exercises.len() {
bail!(BAD_INDEX_ERR);
}
let path = self.exercises[exercise_ind].path;
self.set_pending(exercise_ind)?;
self.reset_path(path)?;
Ok(path)
}
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.

@ -1,17 +1,13 @@
use anyhow::{bail, Context, Result}; use anyhow::{Context, Result};
use crossterm::style::{style, StyledContent, Stylize}; use crossterm::style::{style, StyledContent, Stylize};
use std::{ use std::{
fmt::{self, Display, Formatter}, fmt::{self, Display, Formatter},
fs, fs,
path::Path, path::Path,
process::{Command, Output, Stdio}, process::{Command, Output},
}; };
use crate::{ use crate::{info_file::Mode, DEVELOPING_OFFICIAL_RUSTLINGS};
embedded::{WriteStrategy, EMBEDDED_FILES},
info_file::Mode,
DEVELOPING_OFFICIAL_RUSTLINGS,
};
pub struct TerminalFileLink<'a> { pub struct TerminalFileLink<'a> {
path: &'a str, path: &'a str,
@ -87,34 +83,6 @@ impl Exercise {
} }
} }
pub fn reset(&self) -> Result<()> {
if Path::new("info.toml").exists() {
let output = Command::new("git")
.arg("stash")
.arg("push")
.arg("--")
.arg(self.path)
.stdin(Stdio::null())
.stdout(Stdio::null())
.output()
.with_context(|| format!("Failed to run `git stash push -- {}`", self.path))?;
if !output.status.success() {
bail!(
"`git stash push -- {}` didn't run successfully: {}",
self.path,
String::from_utf8_lossy(&output.stderr),
);
}
} else {
EMBEDDED_FILES
.write_exercise_to_disk(self.path, WriteStrategy::Overwrite)
.with_context(|| format!("Failed to reset the exercise {self}"))?;
}
Ok(())
}
pub fn terminal_link(&self) -> StyledContent<TerminalFileLink<'_>> { pub fn terminal_link(&self) -> StyledContent<TerminalFileLink<'_>> {
style(TerminalFileLink { path: self.path }) style(TerminalFileLink { path: self.path })
.underlined() .underlined()

@ -217,23 +217,22 @@ impl<'a> UiState<'a> {
return Ok(self); return Ok(self);
}; };
let (ind, exercise) = self let ind = self
.app_state .app_state
.exercises() .exercises()
.iter() .iter()
.enumerate() .enumerate()
.filter_map(|(ind, exercise)| match self.filter { .filter_map(|(ind, exercise)| match self.filter {
Filter::Done => exercise.done.then_some((ind, exercise)), Filter::Done => exercise.done.then_some(ind),
Filter::Pending => (!exercise.done).then_some((ind, exercise)), Filter::Pending => (!exercise.done).then_some(ind),
Filter::None => Some((ind, exercise)), Filter::None => Some(ind),
}) })
.nth(selected) .nth(selected)
.context("Invalid selection index")?; .context("Invalid selection index")?;
exercise.reset()?; let exercise_path = self.app_state.reset_exercise_by_ind(ind)?;
self.message self.message
.write_fmt(format_args!("The exercise {exercise} has been reset!"))?; .write_fmt(format_args!("The exercise {exercise_path} has been reset"))?;
self.app_state.set_pending(ind)?;
Ok(self.with_updated_rows()) Ok(self.with_updated_rows())
} }

@ -158,10 +158,8 @@ fn main() -> Result<()> {
} }
Some(Subcommands::Reset { name }) => { Some(Subcommands::Reset { name }) => {
app_state.set_current_exercise_by_name(&name)?; app_state.set_current_exercise_by_name(&name)?;
let exercise = app_state.current_exercise(); let exercise_path = app_state.reset_current_exercise()?;
exercise.reset()?; println!("The exercise {exercise_path} has been reset");
println!("The exercise {exercise} has been reset!");
app_state.set_pending(app_state.current_exercise_ind())?;
} }
Some(Subcommands::Hint { name }) => { Some(Subcommands::Hint { name }) => {
app_state.set_current_exercise_by_name(&name)?; app_state.set_current_exercise_by_name(&name)?;