1use 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";
29pub const RED: &str = "\x1b[31m";
31pub const GREEN: &str = "\x1b[32m";
33pub const YELLOW: &str = "\x1b[33m";
35pub const BLUE: &str = "\x1b[34m";
37pub const MAGENTA: &str = "\x1b[35m";
39pub const CYAN: &str = "\x1b[36m";
41pub const GRAY: &str = "\x1b[37m";
43pub const WHITE: &str = "\x1b[97m";
45
46#[derive(Clone, Debug)]
50pub struct Printer {
51 out: SharedWriter,
52}
53
54impl Printer {
55 pub fn new(out: SharedWriter) -> Printer {
57 Printer { out }
58 }
59
60 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 pub fn out(&self) -> SharedWriter {
70 self.out.clone()
71 }
72}
73
74pub 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
94pub 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
111pub 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 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
147pub 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
163pub 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
178fn 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 #[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 #[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 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 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}