Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace all ansi_term crates #2923

Merged
merged 19 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions prdoc/pr_2923.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
title: "Use `console` crate instead of `ansi_term`"

doc:
- audience: Node Dev
description: |
This PR replace obsoleted `ansi_term` to `console`.

crates:
- name: sc-informant
bump: patch
- name: sc-tracing
bump: patch
jasl marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 1 addition & 1 deletion substrate/client/informant/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ workspace = true
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
ansi_term = { workspace = true }
console = { workspace = true }
futures = { workspace = true }
futures-timer = { workspace = true }
log = { workspace = true, default-features = true }
Expand Down
14 changes: 7 additions & 7 deletions substrate/client/informant/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use crate::OutputFormat;
use ansi_term::Colour;
use console::{Attribute, Color};
use log::info;
use sc_client_api::ClientInfo;
use sc_network::NetworkStatus;
Expand Down Expand Up @@ -146,15 +146,15 @@ impl<B: BlockT> InformantDisplay<B> {
target: "substrate",
"{} {}{} ({} peers), best: #{} ({}), finalized #{} ({}), {} {}",
jasl marked this conversation as resolved.
Show resolved Hide resolved
level,
self.format.print_with_color(Colour::White.bold(), status),
self.format.print(Color::White, Some(Attribute::Bold), &status),
target,
self.format.print_with_color(Colour::White.bold(), num_connected_peers),
self.format.print_with_color(Colour::White.bold(), best_number),
self.format.print(Color::White, Some(Attribute::Bold), format!("{}", num_connected_peers)),
self.format.print(Color::White, Some(Attribute::Bold), format!("{}", best_number)),
best_hash,
self.format.print_with_color(Colour::White.bold(), finalized_number),
self.format.print(Color::White, Some(Attribute::Bold), format!("{}", finalized_number)),
info.chain.finalized_hash,
self.format.print_with_color(Colour::Green, format!("⬇ {}", TransferRateFormat(avg_bytes_per_sec_inbound))),
self.format.print_with_color(Colour::Red, format!("⬆ {}", TransferRateFormat(avg_bytes_per_sec_outbound))),
self.format.print(Color::Green, None, format!("⬇ {}", TransferRateFormat(avg_bytes_per_sec_inbound))),
self.format.print(Color::Red, None, format!("⬆ {}", TransferRateFormat(avg_bytes_per_sec_outbound))),
)
}
}
Expand Down
56 changes: 19 additions & 37 deletions substrate/client/informant/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

//! Console informant. Prints sync progress and block events. Runs on the calling thread.

use ansi_term::{Colour, Style};
use console::{style, Attribute, Color};
use futures::prelude::*;
use futures_timer::Delay;
use log::{debug, info, trace};
Expand Down Expand Up @@ -51,41 +51,15 @@ impl Default for OutputFormat {
}
}

enum ColorOrStyle {
Color(Colour),
Style(Style),
}

impl From<Colour> for ColorOrStyle {
fn from(value: Colour) -> Self {
Self::Color(value)
}
}

impl From<Style> for ColorOrStyle {
fn from(value: Style) -> Self {
Self::Style(value)
}
}

impl ColorOrStyle {
fn paint(&self, data: String) -> impl Display {
match self {
Self::Color(c) => c.paint(data),
Self::Style(s) => s.paint(data),
}
}
}

impl OutputFormat {
/// Print with color if `self.enable_color == true`.
fn print_with_color(
&self,
color: impl Into<ColorOrStyle>,
data: impl ToString,
) -> impl Display {
fn print(&self, color: Color, attr: Option<Attribute>, data: impl Display) -> impl Display {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bkchr console API design is not good here. Do you have any suggestions?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the problem here? I don't see it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In ansi_term, the function can just pass Colour::Red.bold() to get red and bold style, but console doesn't provide such fluent API, I separate color and attribute, and because there are usages do not have attribute, so I have to make it optional which feels not good than previous one

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is fine. This is some internal api any way.

if self.enable_color {
color.into().paint(data.to_string()).to_string()
let mut styled = style(data).fg(color);
if let Some(attr) = attr {
styled = styled.attr(attr);
}
styled.to_string()
} else {
data.to_string()
}
Expand Down Expand Up @@ -161,11 +135,19 @@ where
match maybe_ancestor {
Ok(ref ancestor) if ancestor.hash != *last_hash => info!(
"♻️ Reorg on #{},{} to #{},{}, common ancestor #{},{}",
format.print_with_color(Colour::Red.bold(), last_num),
format.print(Color::Red, Some(Attribute::Bold), last_num.to_string()),
jasl marked this conversation as resolved.
Show resolved Hide resolved
last_hash,
format.print_with_color(Colour::Green.bold(), n.header.number()),
format.print(
Color::Green,
Some(Attribute::Bold),
n.header.number().to_string(),
jasl marked this conversation as resolved.
Show resolved Hide resolved
),
n.hash,
format.print_with_color(Colour::White.bold(), ancestor.number),
format.print(
Color::White,
Some(Attribute::Bold),
ancestor.number.to_string(),
jasl marked this conversation as resolved.
Show resolved Hide resolved
),
ancestor.hash,
),
Ok(_) => {},
Expand All @@ -191,7 +173,7 @@ where
info!(
target: "substrate",
"{best_indicator} Imported #{} ({} → {})",
format.print_with_color(Colour::White.bold(), n.header.number()),
format.print(Color::White, Some(Attribute::Bold), n.header.number().to_string()),
jasl marked this conversation as resolved.
Show resolved Hide resolved
n.header.parent_hash(),
n.hash,
);
Expand Down
2 changes: 1 addition & 1 deletion substrate/client/tracing/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ workspace = true
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
ansi_term = { workspace = true }
console = { workspace = true }
is-terminal = { workspace = true }
chrono = { workspace = true }
codec = { workspace = true, default-features = true }
Expand Down
18 changes: 8 additions & 10 deletions substrate/client/tracing/src/logging/event_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use crate::logging::fast_local_time::FastLocalTime;
use ansi_term::Colour;
use console::style;
use regex::Regex;
use std::fmt::{self, Write};
use tracing::{Event, Level, Subscriber};
Expand Down Expand Up @@ -166,11 +166,11 @@ impl<'a> fmt::Display for FmtLevel<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.ansi {
match *self.level {
Level::TRACE => write!(f, "{}", Colour::Purple.paint(TRACE_STR)),
Level::DEBUG => write!(f, "{}", Colour::Blue.paint(DEBUG_STR)),
Level::INFO => write!(f, "{}", Colour::Green.paint(INFO_STR)),
Level::WARN => write!(f, "{}", Colour::Yellow.paint(WARN_STR)),
Level::ERROR => write!(f, "{}", Colour::Red.paint(ERROR_STR)),
Level::TRACE => write!(f, "{}", style(TRACE_STR).magenta().to_string()),
Level::DEBUG => write!(f, "{}", style(DEBUG_STR).blue().to_string()),
Level::INFO => write!(f, "{}", style(INFO_STR).green().to_string()),
Level::WARN => write!(f, "{}", style(WARN_STR).yellow().to_string()),
Level::ERROR => write!(f, "{}", style(ERROR_STR).red().to_string()),
}
} else {
match *self.level {
Expand Down Expand Up @@ -234,7 +234,6 @@ impl<'a> fmt::Display for FmtThreadName<'a> {
//
// https://github.com/tokio-rs/tracing/blob/2f59b32/tracing-subscriber/src/fmt/time/mod.rs#L252
mod time {
use ansi_term::Style;
use std::fmt;
use tracing_subscriber::fmt::{format, time::FormatTime};

Expand All @@ -247,10 +246,9 @@ mod time {
T: FormatTime,
{
if with_ansi {
let style = Style::new().dimmed();
write!(writer, "{}", style.prefix())?;
write!(writer, "\x1B[2m")?;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The newer tracing-subscriber has removed with_ansi format support.
to keep it simple, I copy the dimmed style and replace its usage in write!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't allow to get prefix and suffix.

timer.format_time(writer)?; will do write! so we can't wrap it with style here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I see what you mean now!

timer.format_time(writer)?;
write!(writer, "{}", style.suffix())?;
write!(writer, "\x1B[0m")?;
} else {
timer.format_time(writer)?;
}
Expand Down
2 changes: 1 addition & 1 deletion substrate/client/tracing/src/logging/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ mod tests {
fn do_not_write_with_colors_on_tty_entrypoint() {
if env::var("ENABLE_LOGGING").is_ok() {
let _guard = init_logger("");
log::info!("{}", ansi_term::Colour::Yellow.paint(EXPECTED_LOG_MESSAGE));
log::info!("{}", console::style(EXPECTED_LOG_MESSAGE).yellow().to_string());
jasl marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down