1- use anyhow:: Result ;
1+ use anyhow:: { Context , Result } ;
22use crossterm:: {
33 QueueableCommand ,
44 style:: { Attribute , Color , ResetColor , SetAttribute , SetForegroundColor } ,
@@ -7,6 +7,7 @@ use std::io::{self, StdoutLock, Write};
77
88use crate :: {
99 cmd:: CmdRunner ,
10+ embedded:: InputFile ,
1011 term:: { self , CountedWrite , file_path, terminal_file_link, write_ansi} ,
1112} ;
1213
@@ -69,6 +70,7 @@ fn run_bin(
6970pub struct Exercise {
7071 pub name : & ' static str ,
7172 pub dir : Option < & ' static str > ,
73+ pub embedded_input_files : & ' static [ InputFile ] ,
7274 /// Path of the exercise file starting with the `exercises/` directory.
7375 pub path : & ' static str ,
7476 pub canonical_path : Option < String > ,
@@ -99,6 +101,7 @@ pub trait RunnableExercise {
99101 fn dir ( & self ) -> Option < & str > ;
100102 fn strict_clippy ( & self ) -> bool ;
101103 fn test ( & self ) -> bool ;
104+ fn embedded_input_files ( & self ) -> & [ InputFile ] ;
102105
103106 // Compile, check and run the exercise or its solution (depending on `bin_name´).
104107 // The output is written to the `output` buffer after clearing it.
@@ -112,6 +115,19 @@ pub trait RunnableExercise {
112115 output. clear ( ) ;
113116 }
114117
118+ // Input files are already written to disk during `rustlings init`.
119+ // We repeat it here to ensure an exercise doesn't fail because the
120+ // input files were deleted or modified in the meantime. Note that
121+ // `self.embedded_input_files()` is empty for community exercises.
122+ for input_file in self . embedded_input_files ( ) {
123+ let name = input_file. name ;
124+ let path = match self . dir ( ) {
125+ Some ( dir) => format ! ( "exercises/{dir}/{name}" ) ,
126+ None => format ! ( "exercises/{name}" ) ,
127+ } ;
128+ std:: fs:: write ( path, input_file. content ) . context ( "failed to write input file" ) ?;
129+ }
130+
115131 let build_success = cmd_runner
116132 . cargo ( "build" , bin_name, output. as_deref_mut ( ) )
117133 . run ( "cargo build …" ) ?;
@@ -224,4 +240,8 @@ impl RunnableExercise for Exercise {
224240 fn test ( & self ) -> bool {
225241 self . test
226242 }
243+
244+ fn embedded_input_files ( & self ) -> & [ InputFile ] {
245+ self . embedded_input_files
246+ }
227247}
0 commit comments