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