LINE1 10 20 30 40 50 60 701//! What the CLI tells the user while a release runs.2//!3//! In a terminal this prints the usual lines. With `--events json` every4//! message becomes one JSON object per line on stdout, so another program (the5//! Ino console) can show the same progress. The release logic itself is the6//! same in both modes.78use std::{9 io::{self, BufRead, BufReader, IsTerminal, Read, Write},10 process::{Command, ExitStatus, Stdio},11 sync::{12Mutex, PoisonError,13 atomic::{AtomicBool, Ordering},14 mpsc::{self, RecvTimeoutError, Sender},15 },16 thread::{self, JoinHandle},17 time::Duration,18};1920use serde_json::{Map, Value, json};2122constFRAMES: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];2324staticEVENTS_JSON: AtomicBool = AtomicBool::new(false);25/// Keeps each JSON line whole when output from several threads is emitted.26staticEVENT_WRITER: Mutex<()> = Mutex::new(());2728/// Selects JSON events on stdout instead of terminal messages.29pubfnset_events_json(enabled: bool) {30EVENTS_JSON.store(enabled, Ordering::Relaxed);31}3233fnevents_json() -> bool {34EVENTS_JSON.load(Ordering::Relaxed)35}3637fnemit(event: &Value) {38let _guard = EVENT_WRITER.lock().unwrap_or_else(PoisonError::into_inner);39letmut stdout = io::stdout().lock();40let _ = writeln!(stdout, "{event}");41let _ = stdout.flush();42}4344/// Prints what is starting next, for stages whose own output may be quiet.45pubfnstep(message: &str) {46ifevents_json() {47emit(&json!({ "type": "step", "message": message }));48 } else {49println!("{message}...");50 }51}5253/// Reports something the user should know, without stopping the release.54pubfnnotice(message: &str) {55ifevents_json() {56emit(&json!({ "type": "notice", "message": message }));57 } else {58println!("{message}");59 }60}6162/// Reports the release outcome. `details` holds the structured fields that63/// go with the terminal sentence.64pubfndone(message: &str, details: Value) {65ifevents_json() {66letmut event = Map::new();67 event.insert("type".to_owned(), json!("done"));68 event.insert("message".to_owned(), json!(message));69ifletValue::Object(fields) = details {70 event.extend(fields);71 }72emit(&Value::Object(event));73 } else {74println!("{message}");75 }76}7778/// Reports a failure in JSON mode. Terminal mode prints the error itself.79pubfnerror(message: &str) {80ifevents_json() {81emit(&json!({ "type": "error", "message": message }));82 }83}8485/// Runs one command of a release step. In a terminal its output goes straight86/// to the terminal. With events, each line of its output is sent as an87/// `output` event, so the JSON stream stays intact.88pubfnrun_command(command: &mutCommand) -> io::Result<ExitStatus> {89if !events_json() {90return command.status();91 }92letmut child = command93 .stdin(Stdio::null())94 .stdout(Stdio::piped())95 .stderr(Stdio::piped())96 .spawn()?;97let stdout = child.stdout.take();98let stderr = child.stderr.take();99 thread::scope(|scope| {100ifletSome(stdout) = stdout {101 scope.spawn(move || relay(stdout, "stdout"));102 }103ifletSome(stderr) = stderr {104 scope.spawn(move || relay(stderr, "stderr"));105 }106 });107 child.wait()108}109110fnrelay(source: implRead, stream: &str) {111for line inBufReader::new(source).lines() {112letOk(line) = line else { break };113emit(&json!({ "type": "output", "stream": stream, "line": line }));114 }115}116117/// Shows that a long wait is running until it is dropped. On a terminal the118/// message animates on stderr and is cleared when the wait ends. Otherwise the119/// message is printed once, so logs still show what started.120pubstructSpinner {121 done: Option<Sender<()>>,122 handle: Option<JoinHandle<()>>,123}124125implSpinner {126pubfnstart(message: implInto<String>) -> Self {127let message = message.into();128ifevents_json() {129step(&message);130returnSelf {131 done: None,132 handle: None,133 };134 }135if !io::stderr().is_terminal() {136println!("{message}...");137returnSelf {138 done: None,139 handle: None,140 };141 }142143let (done, stopped) = mpsc::channel();144let handle = thread::spawn(move || {145for frame inFRAMES.iter().cycle() {146eprint!("\r{frame} {message}...");147let _ = io::stderr().flush();148match stopped.recv_timeout(Duration::from_millis(80)) {149Err(RecvTimeoutError::Timeout) => {}150Ok(()) | Err(RecvTimeoutError::Disconnected) => break,151 }152 }153eprint!("\r\x1b[2K");154let _ = io::stderr().flush();155 });156Self {157 done: Some(done),158 handle: Some(handle),159 }160 }161}162163implDropforSpinner {164fndrop(&mutself) {165self.done.take();166ifletSome(handle) = self.handle.take() {167let _ = handle.join();168 }169 }170}