Skip to content
1        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::{12        Mutex, 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};2122const FRAMES: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];2324static EVENTS_JSON: AtomicBool = AtomicBool::new(false);25/// Keeps each JSON line whole when output from several threads is emitted.26static EVENT_WRITER: Mutex<()> = Mutex::new(());2728/// Selects JSON events on stdout instead of terminal messages.29pub fn set_events_json(enabled: bool) {30    EVENTS_JSON.store(enabled, Ordering::Relaxed);31}3233fn events_json() -> bool {34    EVENTS_JSON.load(Ordering::Relaxed)35}3637fn emit(event: &Value) {38    let _guard = EVENT_WRITER.lock().unwrap_or_else(PoisonError::into_inner);39    let mut stdout = io::stdout().lock();40    let _ = writeln!(stdout, "{event}");41    let _ = stdout.flush();42}4344/// Prints what is starting next, for stages whose own output may be quiet.45pub fn step(message: &str) {46    if events_json() {47        emit(&json!({ "type": "step", "message": message }));48    } else {49        println!("{message}...");50    }51}5253/// Reports something the user should know, without stopping the release.54pub fn notice(message: &str) {55    if events_json() {56        emit(&json!({ "type": "notice", "message": message }));57    } else {58        println!("{message}");59    }60}6162/// Reports the release outcome. `details` holds the structured fields that63/// go with the terminal sentence.64pub fn done(message: &str, details: Value) {65    if events_json() {66        let mut event = Map::new();67        event.insert("type".to_owned(), json!("done"));68        event.insert("message".to_owned(), json!(message));69        if let Value::Object(fields) = details {70            event.extend(fields);71        }72        emit(&Value::Object(event));73    } else {74        println!("{message}");75    }76}7778/// Reports a failure in JSON mode. Terminal mode prints the error itself.79pub fn error(message: &str) {80    if events_json() {81        emit(&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.88pub fn run_command(command: &mut Command) -> io::Result<ExitStatus> {89    if !events_json() {90        return command.status();91    }92    let mut child = command93        .stdin(Stdio::null())94        .stdout(Stdio::piped())95        .stderr(Stdio::piped())96        .spawn()?;97    let stdout = child.stdout.take();98    let stderr = child.stderr.take();99    thread::scope(|scope| {100        if let Some(stdout) = stdout {101            scope.spawn(move || relay(stdout, "stdout"));102        }103        if let Some(stderr) = stderr {104            scope.spawn(move || relay(stderr, "stderr"));105        }106    });107    child.wait()108}109110fn relay(source: impl Read, stream: &str) {111    for line in BufReader::new(source).lines() {112        let Ok(line) = line else { break };113        emit(&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.120pub struct Spinner {121    done: Option<Sender<()>>,122    handle: Option<JoinHandle<()>>,123}124125impl Spinner {126    pub fn start(message: impl Into<String>) -> Self {127        let message = message.into();128        if events_json() {129            step(&message);130            return Self {131                done: None,132                handle: None,133            };134        }135        if !io::stderr().is_terminal() {136            println!("{message}...");137            return Self {138                done: None,139                handle: None,140            };141        }142143        let (done, stopped) = mpsc::channel();144        let handle = thread::spawn(move || {145            for frame in FRAMES.iter().cycle() {146                eprint!("\r{frame} {message}...");147                let _ = io::stderr().flush();148                match stopped.recv_timeout(Duration::from_millis(80)) {149                    Err(RecvTimeoutError::Timeout) => {}150                    Ok(()) | Err(RecvTimeoutError::Disconnected) => break,151                }152            }153            eprint!("\r\x1b[2K");154            let _ = io::stderr().flush();155        });156        Self {157            done: Some(done),158            handle: Some(handle),159        }160    }161}162163impl Drop for Spinner {164    fn drop(&mut self) {165        self.done.take();166        if let Some(handle) = self.handle.take() {167            let _ = handle.join();168        }169    }170}