1use bynk_driver::emsg;
7use std::io::Read as _;
8use std::process::ExitCode;
9use std::time::Duration;
10
11use crate::cli::EvalCommand;
12use bynk_driver::eval::{DEFAULT_TIMEOUT, EvalReport, EvalRequest, evaluate};
13
14pub fn default_timeout_secs() -> u64 {
16 DEFAULT_TIMEOUT.as_secs()
17}
18
19fn print(report: &EvalReport) -> ExitCode {
22 match serde_json::to_string(report) {
23 Ok(text) => println!("{text}"),
24 Err(e) => {
25 emsg!("bynk eval: error: could not render the result: {e}");
26 return ExitCode::FAILURE;
27 }
28 }
29 if report.succeeded() {
30 ExitCode::SUCCESS
31 } else {
32 ExitCode::FAILURE
33 }
34}
35
36pub fn refuse(message: impl Into<String>) -> ExitCode {
38 print(&bynk_driver::eval::EvalOutcome::Error(message.into()).into())
39}
40
41pub fn run(args: EvalCommand) -> ExitCode {
43 let EvalCommand {
44 input,
45 unit,
46 expr,
47 sources_stdin,
48 suite,
49 timeout,
50 } = args;
51 if sources_stdin && expr.is_none() {
53 return refuse(
54 "`--sources-stdin` reads the unsaved buffers from stdin, so the snippet must come from `--expr`",
55 );
56 }
57 let mut stdin = String::new();
58 if (sources_stdin || expr.is_none())
59 && let Err(e) = std::io::stdin().read_to_string(&mut stdin)
60 {
61 return refuse(format!("could not read stdin: {e}"));
62 }
63 let (snippet, buffers) = if sources_stdin {
64 match bynk_driver::source_overlay::parse_overlay(&stdin) {
65 Ok(buffers) => (expr.unwrap_or_default(), buffers),
66 Err(e) => return refuse(e.to_string()),
67 }
68 } else {
69 (expr.unwrap_or(stdin), Default::default())
70 };
71 if snippet.trim().is_empty() {
72 return refuse("there is nothing to evaluate: give `--expr`, or a snippet on stdin");
73 }
74 let timeout = Duration::from_secs(timeout);
75 print(
76 &evaluate(&EvalRequest {
77 input,
78 unit,
79 snippet,
80 buffers,
81 suites: suite.into_iter().collect(),
82 timeout,
83 })
84 .into(),
85 )
86}