Skip to content

Commit

Permalink
Replace all ansi_term crates (paritytech#2923)
Browse files Browse the repository at this point in the history
Now Polkadot-SDK is ansi_term free

---------

Co-authored-by: Bastian Köcher <git@kchr.de>
  • Loading branch information
2 people authored and TarekkMA committed Aug 2, 2024
1 parent a31ffcf commit ac945db
Show file tree
Hide file tree
Showing 20 changed files with 81 additions and 261 deletions.
6 changes: 3 additions & 3 deletions Cargo.lock

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

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,6 @@ ahash = { version = "0.8.2" }
alloy-primitives = { version = "0.4.2", default-features = false }
alloy-sol-types = { version = "0.4.2", default-features = false }
always-assert = { version = "0.1" }
ansi_term = { version = "0.12.1" }
anyhow = { version = "1.0.81" }
aquamarine = { version = "0.5.0" }
arbitrary = { version = "1.3.2" }
Expand Down
2 changes: 1 addition & 1 deletion bridges/relays/utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ publish = false
workspace = true

[dependencies]
ansi_term = { workspace = true }
anyhow = { workspace = true }
async-std = { workspace = true }
async-trait = { workspace = true }
backoff = { workspace = true }
console = { workspace = true }
isahc = { workspace = true }
env_logger = { workspace = true }
futures = { workspace = true }
Expand Down
16 changes: 8 additions & 8 deletions bridges/relays/utils/src/initialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

//! Relayer initialization functions.

use console::style;
use parking_lot::Mutex;
use std::{cell::RefCell, fmt::Display, io::Write};

Expand Down Expand Up @@ -55,7 +56,7 @@ pub fn initialize_logger(with_timestamp: bool) {
let timestamp = if cfg!(windows) {
Either::Left(timestamp)
} else {
Either::Right(ansi_term::Colour::Fixed(8).bold().paint(timestamp))
Either::Right(style(timestamp).black().bright().bold().to_string())
};

writeln!(
Expand Down Expand Up @@ -120,7 +121,7 @@ fn color_target(target: &str) -> impl Display + '_ {
if cfg!(windows) {
Either::Left(target)
} else {
Either::Right(ansi_term::Colour::Fixed(8).paint(target))
Either::Right(style(target).black().bright().to_string())
}
}

Expand All @@ -129,13 +130,12 @@ fn color_level(level: log::Level) -> impl Display {
Either::Left(level)
} else {
let s = level.to_string();
use ansi_term::Colour as Color;
Either::Right(match level {
log::Level::Error => Color::Fixed(9).bold().paint(s),
log::Level::Warn => Color::Fixed(11).bold().paint(s),
log::Level::Info => Color::Fixed(10).paint(s),
log::Level::Debug => Color::Fixed(14).paint(s),
log::Level::Trace => Color::Fixed(12).paint(s),
log::Level::Error => style(s).red().bright().bold().to_string(),
log::Level::Warn => style(s).yellow().bright().bold().to_string(),
log::Level::Info => style(s).green().bright().to_string(),
log::Level::Debug => style(s).cyan().bright().to_string(),
log::Level::Trace => style(s).blue().bright().to_string(),
})
}
}
1 change: 0 additions & 1 deletion cumulus/test/service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -891,7 +891,6 @@ pub fn node_config(
announce_block: true,
data_path: root,
base_path,
informant_output_format: Default::default(),
wasm_runtime_overrides: None,
wasmtime_precompiled: None,
runtime_cache_size: 2,
Expand Down
1 change: 0 additions & 1 deletion polkadot/node/test/service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,6 @@ pub fn node_config(
announce_block: true,
data_path: root,
base_path,
informant_output_format: Default::default(),
}
}

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

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

crates:
- name: relay-utils
bump: patch
- name: sc-informant
bump: patch
- name: sc-tracing
bump: patch
- name: sc-service
bump: major
2 changes: 0 additions & 2 deletions substrate/bin/node/cli/benches/block_production.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,6 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase {
announce_block: true,
data_path: base_path.path().into(),
base_path,
informant_output_format: Default::default(),
wasmtime_precompiled: None,
wasm_runtime_overrides: None,
};

Expand Down
2 changes: 0 additions & 2 deletions substrate/bin/node/cli/benches/transaction_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,6 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase {
announce_block: true,
data_path: base_path.path().into(),
base_path,
informant_output_format: Default::default(),
wasmtime_precompiled: None,
wasm_runtime_overrides: None,
};

Expand Down
3 changes: 1 addition & 2 deletions substrate/client/cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use names::{Generator, Name};
use sc_service::{
config::{
BasePath, Configuration, DatabaseSource, IpNetwork, KeystoreConfig, NetworkConfiguration,
NodeKeyConfig, OffchainWorkerConfig, OutputFormat, PrometheusConfig, PruningMode, Role,
NodeKeyConfig, OffchainWorkerConfig, PrometheusConfig, PruningMode, Role,
RpcBatchRequestConfig, RpcMethods, TelemetryEndpoints, TransactionPoolOptions,
WasmExecutionMethod,
},
Expand Down Expand Up @@ -558,7 +558,6 @@ pub trait CliConfiguration<DCV: DefaultConfigurationValues = ()>: Sized {
announce_block: self.announce_block()?,
role,
base_path,
informant_output_format: OutputFormat { enable_color: !self.disable_log_color()? },
runtime_cache_size,
})
}
Expand Down
1 change: 0 additions & 1 deletion substrate/client/cli/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,6 @@ mod tests {
announce_block: true,
base_path: sc_service::BasePath::new(root.clone()),
data_path: root,
informant_output_format: Default::default(),
runtime_cache_size: 2,
},
runtime,
Expand Down
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
22 changes: 9 additions & 13 deletions substrate/client/informant/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use crate::OutputFormat;
use ansi_term::Colour;
use console::style;
use log::info;
use sc_client_api::ClientInfo;
use sc_network::NetworkStatus;
Expand Down Expand Up @@ -47,19 +46,16 @@ pub struct InformantDisplay<B: BlockT> {
last_total_bytes_inbound: u64,
/// The last seen total of bytes sent.
last_total_bytes_outbound: u64,
/// The format to print output in.
format: OutputFormat,
}

impl<B: BlockT> InformantDisplay<B> {
/// Builds a new informant display system.
pub fn new(format: OutputFormat) -> InformantDisplay<B> {
pub fn new() -> InformantDisplay<B> {
InformantDisplay {
last_number: None,
last_update: Instant::now(),
last_total_bytes_inbound: 0,
last_total_bytes_outbound: 0,
format,
}
}

Expand Down Expand Up @@ -144,17 +140,17 @@ impl<B: BlockT> InformantDisplay<B> {

info!(
target: "substrate",
"{} {}{} ({} peers), best: #{} ({}), finalized #{} ({}), {} {}",
"{} {}{} ({} peers), best: #{} ({}), finalized #{} ({}), ⬇ {} ⬆ {}",
level,
self.format.print_with_color(Colour::White.bold(), status),
style(&status).white().bold(),
target,
self.format.print_with_color(Colour::White.bold(), num_connected_peers),
self.format.print_with_color(Colour::White.bold(), best_number),
style(num_connected_peers).white().bold(),
style(best_number).white().bold(),
best_hash,
self.format.print_with_color(Colour::White.bold(), finalized_number),
style(finalized_number).white().bold(),
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))),
style(TransferRateFormat(avg_bytes_per_sec_inbound)).green(),
style(TransferRateFormat(avg_bytes_per_sec_outbound)).red(),
)
}
}
Expand Down
77 changes: 9 additions & 68 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;
use futures::prelude::*;
use futures_timer::Delay;
use log::{debug, info, trace};
Expand All @@ -36,71 +36,15 @@ fn interval(duration: Duration) -> impl Stream<Item = ()> + Unpin {
futures::stream::unfold((), move |_| Delay::new(duration).map(|_| Some(((), ())))).map(drop)
}

/// The format to print telemetry output in.
#[derive(Clone, Debug)]
pub struct OutputFormat {
/// Enable color output in logs.
///
/// Is enabled by default.
pub enable_color: bool,
}

impl Default for OutputFormat {
fn default() -> Self {
Self { enable_color: true }
}
}

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 {
if self.enable_color {
color.into().paint(data.to_string()).to_string()
} else {
data.to_string()
}
}
}

/// Builds the informant and returns a `Future` that drives the informant.
pub async fn build<B: BlockT, C, N, S>(client: Arc<C>, network: N, syncing: S, format: OutputFormat)
pub async fn build<B: BlockT, C, N, S>(client: Arc<C>, network: N, syncing: S)
where
N: NetworkStatusProvider,
S: SyncStatusProvider<B>,
C: UsageProvider<B> + HeaderMetadata<B> + BlockchainEvents<B>,
<C as HeaderMetadata<B>>::Error: Display,
{
let mut display = display::InformantDisplay::new(format.clone());
let mut display = display::InformantDisplay::new();

let client_1 = client.clone();

Expand Down Expand Up @@ -130,14 +74,11 @@ where

futures::select! {
() = display_notifications.fuse() => (),
() = display_block_import(client, format).fuse() => (),
() = display_block_import(client).fuse() => (),
};
}

fn display_block_import<B: BlockT, C>(
client: Arc<C>,
format: OutputFormat,
) -> impl Future<Output = ()>
fn display_block_import<B: BlockT, C>(client: Arc<C>) -> impl Future<Output = ()>
where
C: UsageProvider<B> + HeaderMetadata<B> + BlockchainEvents<B>,
<C as HeaderMetadata<B>>::Error: Display,
Expand All @@ -161,11 +102,11 @@ 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),
style(last_num).red().bold(),
last_hash,
format.print_with_color(Colour::Green.bold(), n.header.number()),
style(n.header.number()).green().bold(),
n.hash,
format.print_with_color(Colour::White.bold(), ancestor.number),
style(ancestor.number).white().bold(),
ancestor.hash,
),
Ok(_) => {},
Expand All @@ -191,7 +132,7 @@ where
info!(
target: "substrate",
"{best_indicator} Imported #{} ({} → {})",
format.print_with_color(Colour::White.bold(), n.header.number()),
style(n.header.number()).white().bold(),
n.header.parent_hash(),
n.hash,
);
Expand Down
7 changes: 1 addition & 6 deletions substrate/client/service/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -520,12 +520,7 @@ where
spawn_handle.spawn(
"informant",
None,
sc_informant::build(
client.clone(),
network,
sync_service.clone(),
config.informant_output_format,
),
sc_informant::build(client.clone(), network, sync_service.clone()),
);

task_manager.keep_alive((config.base_path, rpc));
Expand Down
3 changes: 0 additions & 3 deletions substrate/client/service/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ use prometheus_endpoint::Registry;
use sc_chain_spec::ChainSpec;
pub use sc_client_db::{BlocksPruning, Database, DatabaseSource, PruningMode};
pub use sc_executor::{WasmExecutionMethod, WasmtimeInstantiationStrategy};
pub use sc_informant::OutputFormat;
pub use sc_network::{
config::{
MultiaddrWithPeerId, NetworkConfiguration, NodeKeyConfig, NonDefaultSetConfig, ProtocolId,
Expand Down Expand Up @@ -150,8 +149,6 @@ pub struct Configuration {
pub data_path: PathBuf,
/// Base path of the configuration. This is shared between chains.
pub base_path: BasePath,
/// Configuration of the output format that the informant uses.
pub informant_output_format: OutputFormat,
/// Maximum number of different runtime versions that can be cached.
pub runtime_cache_size: u8,
}
Expand Down
Loading

0 comments on commit ac945db

Please sign in to comment.