Skip to main content

gadk_cli/util/
oscmd.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Console helpers: the colour constants, the step [`Printer`],
17//! [`log_start_stop`]'s banners, the [`ReprintableStream`] that prefixes child output, and
18//! [`log_command`]. Everything is written to the given
19//! [`SharedWriter`] (the command's `Env::out`), byte for byte as ADK's deploy tool writes it.
20
21use std::fmt::{self, Display};
22use std::io::{self, Write};
23
24use crate::SharedWriter;
25use crate::runner::{Cmd, CommandRunner};
26
27pub const RESET: &str = "\x1b[0m";
28pub const RED: &str = "\x1b[31m";
29pub const GREEN: &str = "\x1b[32m";
30pub const YELLOW: &str = "\x1b[33m";
31pub const BLUE: &str = "\x1b[34m";
32pub const MAGENTA: &str = "\x1b[35m";
33pub const CYAN: &str = "\x1b[36m";
34pub const GRAY: &str = "\x1b[37m";
35pub const WHITE: &str = "\x1b[97m";
36
37/// The step printer `log_start_stop` builds. The arguments of one call arrive as one list, so a
38/// line is `    `, a green `> ` and a reset, a space, then `[`, the arguments' text joined by
39/// single spaces, and `]`.
40#[derive(Clone, Debug)]
41pub struct Printer {
42    out: SharedWriter,
43}
44
45impl Printer {
46    /// A printer writing to `out`.
47    pub fn new(out: SharedWriter) -> Printer {
48        Printer { out }
49    }
50
51    /// Prints one line. Each argument's [`Display`] must be its plain text (a `Cmd` displays
52    /// as its command line, a `GoDuration` as its duration string such as `1m0s`).
53    pub fn print(&self, a: &[&dyn Display]) {
54        let args: Vec<String> = a.iter().map(|x| x.to_string()).collect();
55        self.out
56            .write_str(&format!("    {GREEN}> {RESET} [{}]\n", args.join(" ")));
57    }
58
59    /// The writer this printer prints to (the command's stdout).
60    pub fn out(&self) -> SharedWriter {
61        self.out.clone()
62    }
63}
64
65/// Prints `<msg> : Starting`, runs `command` with a [`Printer`], prints an
66/// empty line, then `<msg> : Finished successfully` or `<msg> : Finished with error` and
67/// `Error: <err>`, and returns `command`'s result.
68pub async fn log_start_stop<F>(out: &SharedWriter, msg: &str, command: F) -> Result<(), String>
69where
70    F: AsyncFnOnce(Printer) -> Result<(), String>,
71{
72    out.write_str(&format!("{msg} : {GREEN}Starting{RESET}\n"));
73    let result = command(Printer::new(out.clone())).await;
74    out.write_str("\n");
75    match &result {
76        Ok(()) => out.write_str(&format!("{msg} : {GREEN}Finished successfully{RESET}\n")),
77        Err(err) => {
78            out.write_str(&format!("{msg} : {RED}Finished with error{RESET}\n"));
79            out.write_str(&format!("Error: {err}\n"));
80        }
81    }
82    result
83}
84
85/// Forwards a child's output to `stream`, writing `prefix` first and
86/// in place of every newline, so each output line is indented under the step.
87pub struct ReprintableStream<W: Write> {
88    prefix: Vec<u8>,
89    clean: bool,
90    stream: W,
91}
92
93impl<W: Write> fmt::Debug for ReprintableStream<W> {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        f.debug_struct("ReprintableStream")
96            .field("prefix", &String::from_utf8_lossy(&self.prefix))
97            .field("clean", &self.clean)
98            .finish()
99    }
100}
101
102/// Builds a stream over `s`: the prefix is
103/// `"\n       " + color + prefix + " > " + Reset`.
104pub fn new_reprintable_stream<W: Write>(s: W, prefix: &str, color: &str) -> ReprintableStream<W> {
105    ReprintableStream {
106        prefix: format!("\n       {color}{prefix} > {RESET}").into_bytes(),
107        clean: true,
108        stream: s,
109    }
110}
111
112impl<W: Write> Write for ReprintableStream<W> {
113    /// Reports all of `p` written once the pieces are.
114    fn write(&mut self, p: &[u8]) -> io::Result<usize> {
115        if self.clean {
116            self.stream.write_all(&self.prefix)?;
117            self.clean = false;
118        }
119        let mut start = 0;
120        for (i, &c) in p.iter().enumerate() {
121            if c == b'\n' {
122                self.stream.write_all(&p[start..i])?;
123                self.stream.write_all(&self.prefix)?;
124                start = i + 1;
125            }
126        }
127        if start < p.len() {
128            self.stream.write_all(&p[start..])?;
129        }
130        Ok(p.len())
131    }
132
133    fn flush(&mut self) -> io::Result<()> {
134        self.stream.flush()
135    }
136}
137
138/// Prints `Running : <dir> <cmd>` (yellow `Running : `, the directory, a reset, a space and the
139/// command), then runs `cmd` with its stdout and stderr each through a
140/// [`ReprintableStream`] onto the printer's writer (both go to the command's stdout). A failed
141/// start is its error text; a non-zero exit is `exit status <n>`.
142pub async fn log_command(runner: &dyn CommandRunner, cmd: &Cmd, p: &Printer) -> Result<(), String> {
143    p.print(&[&"Running : ", &YELLOW, &cmd.dir, &RESET, &" ", cmd]);
144    let mut stdout = new_reprintable_stream(p.out(), "  ", YELLOW);
145    let mut stderr = new_reprintable_stream(p.out(), "  ", YELLOW);
146    let exit = runner.run(cmd, &mut stdout, &mut stderr).await?;
147    if exit.success() {
148        Ok(())
149    } else {
150        Err(exit.go_error())
151    }
152}
153
154/// `p` without its extension, which must be
155/// `expected`.
156pub fn strip_extension(p: &str, expected: &str) -> Result<String, String> {
157    let ex = path_ext(p);
158    if ex.is_empty() {
159        return Err(format!("Cannot find extension in '{p}'"));
160    }
161    if ex != expected {
162        return Err(format!(
163            "Unexpected extension. Found '{ex}' instead of '{expected}'"
164        ));
165    }
166    Ok(p[..p.len() - ex.len()].to_string())
167}
168
169/// The suffix from the final `.` of the last slash-separated element.
170fn path_ext(p: &str) -> &str {
171    for (i, c) in p.bytes().enumerate().rev() {
172        if c == b'/' {
173            break;
174        }
175        if c == b'.' {
176            return &p[i..];
177        }
178    }
179    ""
180}
181
182#[cfg(test)]
183mod tests {
184    use pretty_assertions::assert_eq;
185
186    use super::*;
187    use crate::runner::Exit;
188    use crate::testutil::{Canned, RecordingRunner, TestEnv};
189
190    #[test]
191    fn colour_constants_are_go_ansi_codes() {
192        assert_eq!(
193            [RESET, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, GRAY, WHITE],
194            [
195                "\x1b[0m", "\x1b[31m", "\x1b[32m", "\x1b[33m", "\x1b[34m", "\x1b[35m", "\x1b[36m",
196                "\x1b[37m", "\x1b[97m"
197            ]
198        );
199    }
200
201    /// Expected bytes are Go's `fmt.Println("    "+Green+"> "+Reset, a)` for the same
202    /// arguments (Go 1.27).
203    #[test]
204    fn printer_prints_the_argument_slice_like_go_println() {
205        let t = TestEnv::builder("/w").build();
206        let p = Printer::new(t.env.out.clone());
207        p.print(&[&"Using temp dir:", &"/tmp/x"]);
208        p.print(&[]);
209        p.print(&[&"a", &3, &gadk_platform::GoDuration(1_000_000_000)]);
210        assert_eq!(
211            t.out.text(),
212            "    \x1b[32m> \x1b[0m [Using temp dir: /tmp/x]\n\
213             \x20   \x1b[32m> \x1b[0m []\n\
214             \x20   \x1b[32m> \x1b[0m [a 3 1s]\n"
215        );
216    }
217
218    #[tokio::test]
219    async fn log_start_stop_prints_go_banners_on_success() {
220        let t = TestEnv::builder("/w").build();
221        let got = log_start_stop(&t.env.out, "Preparing Dockerfile", async |p: Printer| {
222            p.print(&[&"Writing:", &"/tmp/x/Dockerfile"]);
223            Ok(())
224        })
225        .await;
226        assert_eq!(got, Ok(()));
227        assert_eq!(
228            t.out.text(),
229            "Preparing Dockerfile : \x1b[32mStarting\x1b[0m\n\
230             \x20   \x1b[32m> \x1b[0m [Writing: /tmp/x/Dockerfile]\n\
231             \n\
232             Preparing Dockerfile : \x1b[32mFinished successfully\x1b[0m\n"
233        );
234        assert_eq!(t.err.text(), "");
235    }
236
237    #[tokio::test]
238    async fn log_start_stop_prints_go_banners_on_error() {
239        let t = TestEnv::builder("/w").build();
240        let got = log_start_stop(&t.env.out, "Cleaning temp", async |_p: Printer| {
241            Err("failed to clean temp directory /x: boom".to_string())
242        })
243        .await;
244        assert_eq!(
245            got,
246            Err("failed to clean temp directory /x: boom".to_string())
247        );
248        assert_eq!(
249            t.out.text(),
250            "Cleaning temp : \x1b[32mStarting\x1b[0m\n\
251             \n\
252             Cleaning temp : \x1b[31mFinished with error\x1b[0m\n\
253             Error: failed to clean temp directory /x: boom\n"
254        );
255    }
256
257    const PREFIX: &str = "\n       \x1b[33m   > \x1b[0m";
258
259    /// Go `reprintableStream.Write`: the prefix before the first byte and in place of each
260    /// newline, across several writes.
261    #[test]
262    fn reprintable_stream_prefixes_every_line() {
263        let mut buf = Vec::new();
264        {
265            let mut s = new_reprintable_stream(&mut buf, "  ", YELLOW);
266            assert_eq!(s.write(b"one\ntw").unwrap(), 6);
267            assert_eq!(s.write(b"o\n").unwrap(), 2);
268            assert_eq!(s.write(b"").unwrap(), 0);
269            assert_eq!(s.write(b"\nthree").unwrap(), 6);
270        }
271        assert_eq!(
272            String::from_utf8(buf).unwrap(),
273            format!("{PREFIX}one{PREFIX}two{PREFIX}{PREFIX}three")
274        );
275    }
276
277    #[test]
278    fn reprintable_stream_writes_the_prefix_even_for_an_empty_first_write() {
279        let mut buf = Vec::new();
280        {
281            let mut s = new_reprintable_stream(&mut buf, "  ", YELLOW);
282            s.write_all(b"").unwrap();
283        }
284        // `write_all` of nothing makes no `write` call, so nothing is written (as Go's
285        // `io.Copy`, which never writes an empty chunk).
286        assert_eq!(buf, b"");
287    }
288
289    #[tokio::test]
290    async fn log_command_prints_running_and_streams_child_output() {
291        let runner = RecordingRunner::with_responder(|_| Canned {
292            stdout: b"Deploying...\nDone.\n".to_vec(),
293            stderr: b"warning\n".to_vec(),
294            result: Ok(Exit::Code(0)),
295        });
296        let t = TestEnv::builder("/w").runner(runner).build();
297        let cmd = t
298            .env
299            .command("gcloud", &["run", "deploy", "svc"])
300            .with_dir("/tmp/t");
301        let p = Printer::new(t.env.out.clone());
302        let got = log_command(t.env.runner.as_ref(), &cmd, &p).await;
303        assert_eq!(got, Ok(()));
304        // PATH is unset, so the lookup fails and Go's `Cmd.String()` is the name and args.
305        assert_eq!(
306            t.out.text(),
307            format!(
308                "    \x1b[32m> \x1b[0m [Running :  \x1b[33m /tmp/t \x1b[0m   gcloud run deploy svc]\n\
309                 {PREFIX}Deploying...{PREFIX}Done.{PREFIX}{PREFIX}warning{PREFIX}"
310            )
311        );
312        assert_eq!(t.runner.calls(), vec![cmd]);
313    }
314
315    #[tokio::test]
316    async fn log_command_reports_go_errors() {
317        let runner = RecordingRunner::with_responder(|c| {
318            if c.args[1] == "exit" {
319                Canned::exit(2)
320            } else {
321                Canned::start_error(r#"exec: "gcloud": executable file not found in $PATH"#)
322            }
323        });
324        let t = TestEnv::builder("/w").runner(runner).build();
325        let p = Printer::new(t.env.out.clone());
326        let exit = t.env.command("gcloud", &["exit"]);
327        assert_eq!(
328            log_command(t.env.runner.as_ref(), &exit, &p).await,
329            Err("exit status 2".to_string())
330        );
331        let start = t.env.command("gcloud", &["start"]);
332        assert_eq!(
333            log_command(t.env.runner.as_ref(), &start, &p).await,
334            Err(r#"exec: "gcloud": executable file not found in $PATH"#.to_string())
335        );
336    }
337
338    #[test]
339    fn strip_extension_is_go_strip_extension() {
340        assert_eq!(strip_extension("main.go", ".go"), Ok("main".to_string()));
341        assert_eq!(
342            strip_extension("cmd/agent/main.go", ".go"),
343            Ok("cmd/agent/main".to_string())
344        );
345        assert_eq!(
346            strip_extension("a.b/main", ".go"),
347            Err("Cannot find extension in 'a.b/main'".to_string())
348        );
349        assert_eq!(
350            strip_extension("main.rs", ".go"),
351            Err("Unexpected extension. Found '.rs' instead of '.go'".to_string())
352        );
353        assert_eq!(
354            strip_extension("archive.tar.gz", ".gz"),
355            Ok("archive.tar".to_string())
356        );
357        assert_eq!(strip_extension(".go", ".go"), Ok(String::new()));
358    }
359}