Skip to content

Commit 881f2ae

Browse files
committed
refactor: improve test logging structure
Signed-off-by: xizheyin <[email protected]>
1 parent c636d76 commit 881f2ae

File tree

7 files changed

+204
-228
lines changed

7 files changed

+204
-228
lines changed

bootstrap/src/clean.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,23 @@ use crate::Run;
55

66
/// Clean the build directory
77
#[derive(Args, Debug)]
8-
pub struct CleanCommand {}
8+
pub struct CleanCommand {
9+
#[arg(short, long)]
10+
pub verbose: bool,
11+
}
912

1013
impl Run for CleanCommand {
14+
const STEP_DISPLAY_NAME: &'static str = "clean";
15+
1116
fn run(&self, manifest: &Manifest) {
17+
self.log_action_start("cleaning", "build directory");
1218
let _ = std::fs::remove_dir_all("crates/target");
19+
self.log_action_context("rm", "crates/target");
1320
let _ = std::fs::remove_dir_all(&manifest.out_dir);
21+
self.log_action_context("rm", &manifest.out_dir.display());
22+
}
23+
24+
fn verbose(&self) -> bool {
25+
self.verbose
1426
}
1527
}

bootstrap/src/fmt.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,14 @@ use crate::Run;
1010
pub struct FmtCommand {
1111
#[arg(short, long)]
1212
pub check: bool,
13+
14+
#[arg(short, long)]
15+
pub verbose: bool,
1316
}
1417

1518
impl Run for FmtCommand {
19+
const STEP_DISPLAY_NAME: &'static str = "FMT";
20+
1621
fn run(&self, _manifest: &crate::manifest::Manifest) {
1722
self.perform(
1823
Command::new("cargo").arg("fmt").args(["--manifest-path", "bootstrap/Cargo.toml"]),
@@ -30,14 +35,18 @@ impl Run for FmtCommand {
3035
self.perform(Command::new("rustfmt").args(["--edition", "2021"]).arg(file.unwrap()));
3136
}
3237
}
38+
39+
fn verbose(&self) -> bool {
40+
self.verbose
41+
}
3342
}
3443

3544
impl FmtCommand {
3645
pub fn perform(&self, command: &mut Command) {
3746
if self.check {
3847
command.arg("--check");
3948
}
40-
log::debug!("running {:?}", command);
41-
assert!(command.status().unwrap().success(), "failed to run {:?}", command);
49+
50+
self.command_status("format code", command);
4251
}
4352
}

bootstrap/src/log.rs

Lines changed: 0 additions & 25 deletions
This file was deleted.

bootstrap/src/main.rs

Lines changed: 70 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
use std::fmt::Display;
2+
use std::process::{self, ExitStatus};
3+
14
use clap::{Parser, Subcommand};
5+
use color_print::cprintln;
26

37
use crate::manifest::Manifest;
48

59
mod clean;
610
mod fmt;
7-
mod log;
811
mod manifest;
912
mod rustc;
1013
mod test;
@@ -38,7 +41,65 @@ pub enum Command {
3841
}
3942

4043
trait Run {
44+
// The name like "BUILD" or "TEST" for logs.
45+
const STEP_DISPLAY_NAME: &'static str;
4146
fn run(&self, manifest: &Manifest);
47+
48+
/// True if verbose output should be enabled.
49+
fn verbose(&self) -> bool;
50+
51+
/// Record that the step has started a new action.
52+
fn log_action_start(&self, action: &str, item: impl Display) {
53+
let name = Self::STEP_DISPLAY_NAME;
54+
cprintln!("<b>[{name}]</b> {action} <cyan>{item}</cyan>");
55+
}
56+
57+
/// Record context associated with the current action. Only use if there has been a preceding
58+
/// call to `log_action_start`.
59+
fn log_action_context(&self, key: impl Display, value: impl Display) {
60+
if self.verbose() {
61+
cprintln!(" {key}: {value}");
62+
}
63+
}
64+
65+
/// Run a command and ensure it succeeds, capturing output.
66+
fn command_output(&self, action: &str, command: &mut process::Command) -> process::Output {
67+
if self.verbose() {
68+
cprintln!(" {action}: {command:?}");
69+
}
70+
71+
match command.output() {
72+
// Command ran and completed successfully
73+
Ok(output) if output.status.success() => {
74+
if self.verbose() {
75+
cprintln!(" <g>success</g>");
76+
}
77+
output
78+
}
79+
// Command ran but did not complete
80+
Ok(output) => panic!("command failed: {output:?}"),
81+
Err(e) => panic!("command failed: {e:?}"),
82+
}
83+
}
84+
85+
/// Run a command and ensure it succeeds.
86+
fn command_status(&self, action: &str, command: &mut process::Command) -> ExitStatus {
87+
if self.verbose() {
88+
cprintln!(" {}: {}", action, format!("{:?}", command).replace('"', ""));
89+
}
90+
match command.status() {
91+
// Command ran and completed successfully
92+
Ok(status) if status.success() => {
93+
if self.verbose() {
94+
cprintln!(" <g>success</g>");
95+
}
96+
status
97+
}
98+
// Command ran but did not complete
99+
Ok(status) => panic!("command failed: {status:?}"),
100+
Err(e) => panic!("command failed: {e:?}"),
101+
}
102+
}
42103
}
43104

44105
fn main() {
@@ -56,11 +117,17 @@ fn main() {
56117
test.verbose |= cli.verbose;
57118
test.run(&manifest)
58119
}
59-
Command::Clean(clean) => clean.run(&manifest),
120+
Command::Clean(mut clean) => {
121+
clean.verbose |= cli.verbose;
122+
clean.run(&manifest)
123+
}
60124
Command::Rustc(mut rustc) => {
61125
rustc.verbose |= cli.verbose;
62126
rustc.run(&manifest)
63127
}
64-
Command::Fmt(fmt) => fmt.run(&manifest),
128+
Command::Fmt(mut fmt) => {
129+
fmt.verbose |= cli.verbose;
130+
fmt.run(&manifest)
131+
}
65132
}
66133
}

bootstrap/src/manifest.rs

Lines changed: 62 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
use anstream::eprintln as println;
2-
use color_print::cprintln;
31
use std::path::{Path, PathBuf};
42
use std::process::Command;
53

6-
use crate::log::Log;
4+
use anstream::eprintln as println;
5+
use color_print::cprintln;
6+
7+
use crate::Run;
78

89
#[derive(Debug)]
910
pub struct Manifest {
@@ -12,111 +13,95 @@ pub struct Manifest {
1213
pub out_dir: PathBuf,
1314
}
1415

15-
impl Log for Manifest {
16-
fn log_step(&self, step_type: &str, name: &str, details: Vec<(&str, &str)>) {
17-
if self.verbose {
18-
cprintln!("<b>[BUILD]</b> {} {}", step_type, name);
19-
for (label, value) in details {
20-
cprintln!(" {}: {}", label, value);
21-
}
16+
impl Manifest {
17+
/// Builds the rustc codegen c library
18+
pub fn prepare(&self) {
19+
let prepare = PrepareAction { verbose: self.verbose };
20+
prepare.run(&self);
21+
}
22+
23+
/// The path to the rustc codegen c library
24+
pub fn codegen_backend(&self) -> &'static Path {
25+
if self.release {
26+
Path::new("crates/target/release/librustc_codegen_c.so")
2227
} else {
23-
cprintln!("<b>[BUILD]</b> {} {}", step_type, name);
28+
Path::new("crates/target/debug/librustc_codegen_c.so")
2429
}
2530
}
2631

27-
fn is_verbose(&self) -> bool {
28-
self.verbose
32+
/// The command to run rustc with the codegen backend
33+
pub fn rustc(&self) -> Command {
34+
let mut command = Command::new("rustc");
35+
command
36+
.args(["--edition", "2021"])
37+
.arg("-Z")
38+
.arg(format!("codegen-backend={}", self.codegen_backend().display()))
39+
.args(["-C", "panic=abort"])
40+
.args(["-C", "lto=false"])
41+
.arg(format!("-Lall={}", self.out_dir.display()))
42+
.env("CFLAGS", "-Irust_runtime")
43+
.arg("-lc")
44+
.arg("-lrust_runtime");
45+
if self.verbose {
46+
command.env("RUST_BACKTRACE", "full");
47+
}
48+
command
2949
}
3050
}
3151

32-
impl Manifest {
33-
/// Builds the rustc codegen c library
34-
pub fn prepare(&self) {
35-
// New step
36-
// Build codegen backend
37-
self.log_step(
38-
"preparing",
39-
"codegen backend",
40-
vec![("target", &self.codegen_backend().display().to_string())],
41-
);
52+
struct PrepareAction {
53+
verbose: bool,
54+
}
55+
56+
impl Run for PrepareAction {
57+
const STEP_DISPLAY_NAME: &'static str = "prepare";
58+
59+
fn run(&self, manifest: &Manifest) {
60+
// action: Build codegen backend
61+
self.log_action_start("building", "codegen backend");
62+
self.log_action_context("target", manifest.codegen_backend().display());
4263

4364
let mut command = Command::new("cargo");
4465
command.arg("build").args(["--manifest-path", "crates/Cargo.toml"]);
45-
if self.verbose {
66+
if manifest.verbose {
4667
command.args(["-v"]);
4768
}
48-
if self.release {
69+
if manifest.release {
4970
command.arg("--release");
5071
}
51-
let status = command.status().unwrap();
52-
let status = if self.verbose { Some(status) } else { None };
53-
self.log_command("command", &command, &status);
54-
55-
// New step
56-
// Build runtime library
57-
self.log_step(
58-
"librust_runtime",
59-
"librust_runtime",
60-
vec![("output", &self.out_dir.display().to_string())],
61-
);
72+
self.command_status("build", &mut command);
73+
74+
// action: Build runtime library
75+
self.log_action_start("building", "librust_runtime");
76+
self.log_action_context("output dir", &manifest.out_dir.to_path_buf().display());
6277

6378
// cmd: Create output directory
64-
match std::fs::create_dir_all(&self.out_dir) {
65-
Ok(_) => (),
66-
Err(e) => {
67-
cprintln!(" <r>failed</r> to create output directory: {}", e);
68-
std::process::exit(1);
69-
}
79+
if let Err(e) = std::fs::create_dir_all(&manifest.out_dir) {
80+
cprintln!(" <r>failed</r> to create output directory: {}", e);
81+
std::process::exit(1);
7082
}
83+
7184
let cc = std::env::var("CC").unwrap_or("clang".to_string());
7285

7386
// cmd: Compile runtime.c
7487
let mut command = Command::new(&cc);
7588
command
7689
.arg("rust_runtime/rust_runtime.c")
7790
.arg("-o")
78-
.arg(self.out_dir.join("rust_runtime.o"))
91+
.arg(manifest.out_dir.join("rust_runtime.o"))
7992
.arg("-c");
80-
let status = command.status().unwrap();
81-
let status = if self.verbose { Some(status) } else { None };
82-
self.log_command("compile", &command, &status);
93+
self.command_status("build", &mut command);
8394

8495
// cmd: Create static library
8596
let mut command = Command::new("ar");
8697
command
8798
.arg("rcs")
88-
.arg(self.out_dir.join("librust_runtime.a"))
89-
.arg(self.out_dir.join("rust_runtime.o"));
90-
let status = command.status().unwrap();
91-
let status = if self.verbose { Some(status) } else { None };
92-
self.log_command("archive", &command, &status);
93-
}
94-
95-
/// The path to the rustc codegen c library
96-
pub fn codegen_backend(&self) -> &'static Path {
97-
if self.release {
98-
Path::new("crates/target/release/librustc_codegen_c.so")
99-
} else {
100-
Path::new("crates/target/debug/librustc_codegen_c.so")
101-
}
99+
.arg(manifest.out_dir.join("librust_runtime.a"))
100+
.arg(manifest.out_dir.join("rust_runtime.o"));
101+
self.command_status("archive", &mut command);
102102
}
103103

104-
/// The command to run rustc with the codegen backend
105-
pub fn rustc(&self) -> Command {
106-
let mut command = Command::new("rustc");
107-
command
108-
.args(["--edition", "2021"])
109-
.arg("-Z")
110-
.arg(format!("codegen-backend={}", self.codegen_backend().display()))
111-
.args(["-C", "panic=abort"])
112-
.args(["-C", "lto=false"])
113-
.arg(format!("-Lall={}", self.out_dir.display()))
114-
.env("CFLAGS", "-Irust_runtime")
115-
.arg("-lc")
116-
.arg("-lrust_runtime");
117-
if self.verbose {
118-
command.env("RUST_BACKTRACE", "full");
119-
}
120-
command
104+
fn verbose(&self) -> bool {
105+
self.verbose
121106
}
122107
}

0 commit comments

Comments
 (0)