@@ -193,26 +193,37 @@ async fn echo_text_handler(bot: Bot, msg: Message) -> ResponseResult<()> {
193193
194194async fn run_bc ( expr : & str ) -> Result < String , Box < dyn std:: error:: Error + Send + Sync > > {
195195 let mut child = TokioProcessCommand :: new ( "bc" )
196- . arg ( "-l" ) // enable math functions (sqrt, sin, etc.)
196+ . arg ( "-l" )
197197 . stdin ( Stdio :: piped ( ) )
198198 . stdout ( Stdio :: piped ( ) )
199199 . stderr ( Stdio :: piped ( ) )
200200 . spawn ( ) ?;
201201
202202 if let Some ( mut stdin) = child. stdin . take ( ) {
203203 stdin. write_all ( expr. as_bytes ( ) ) . await ?;
204- stdin. write_all ( b"\n " ) . await ?; // bc needs a newline
204+ stdin. write_all ( b"\n " ) . await ?;
205205 stdin. flush ( ) . await ?;
206+ // stdin is dropped here → EOF is sent to bc
206207 }
207208
208209 let output = child. wait_with_output ( ) . await ?;
209- if output. status . success ( ) {
210- Ok ( String :: from_utf8_lossy ( & output. stdout ) . into_owned ( ) )
210+
211+ let stdout = String :: from_utf8_lossy ( & output. stdout ) . into_owned ( ) ;
212+ let stderr = String :: from_utf8_lossy ( & output. stderr ) . trim ( ) . to_string ( ) ;
213+
214+ if output. status . success ( ) && stderr. is_empty ( ) {
215+ Ok ( stdout)
211216 } else {
217+ // Now catches both non-zero exit AND error messages on stderr (the common case)
212218 Err ( format ! (
213- "bc exited with code {}: {}" ,
214- output. status,
215- String :: from_utf8_lossy( & output. stderr)
219+ "bc error (exit {:?}): {}\n stdout was: {}" ,
220+ output. status. code( ) ,
221+ if stderr. is_empty( ) {
222+ "(no stderr)" . to_string( )
223+ } else {
224+ stderr
225+ } ,
226+ stdout. trim( )
216227 )
217228 . into ( ) )
218229 }
@@ -282,6 +293,9 @@ mod tests {
282293 #[ tokio:: test]
283294 async fn bc_error_handling ( ) {
284295 let res = run_bc ( "syntax error!" ) . await ;
285- assert ! ( res. is_err( ) ) ; // bc should return non-zero
296+ assert ! (
297+ res. is_err( ) ,
298+ "bc should return Err on invalid input (syntax error reported via stderr)"
299+ ) ;
286300 }
287301}
0 commit comments