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

feat: dynamic colors #86

Merged
merged 7 commits into from
Nov 10, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Highlight: We revised the overall experience of the CLI, making it more accessib
- `cargo-near` no longer requires explicitly activating the `abi` feature for the SDK. </~https://github.com/near/cargo-near/pull/85>
- Fixed a bug where `cargo-near` exports an empty ABI file when the target directory is explicitly specified. </~https://github.com/near/cargo-near/pull/75>
- Introduced build stages with a neat report interface. </~https://github.com/near/cargo-near/pull/59>, </~https://github.com/near/cargo-near/pull/63>, </~https://github.com/near/cargo-near/pull/69>
- Added the `--color` flag to control the color output. </~https://github.com/near/cargo-near/pull/86>
- Ensured all forwarded `cargo` output retains colors in it's report, maintaining tooling familiarity. </~https://github.com/near/cargo-near/pull/66>
- Removed the buffering that made `cargo`'s `stdout` lag behind its `stderr`. </~https://github.com/near/cargo-near/pull/65>
- When building contracts, `cargo`'s warnings are only emitted at the build stage, and not duplicated. </~https://github.com/near/cargo-near/pull/68>
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions cargo-near/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@ schemars = "0.8"
near-abi = { version = "0.3.0", features = ["__chunked-entries"] }
libloading = "0.7.3"
zstd = "0.11"
atty = "0.2.14"
8 changes: 6 additions & 2 deletions cargo-near/src/abi.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::cargo::{manifest::CargoManifestPath, metadata::CrateMetadata};
use crate::{util, AbiCommand};
use crate::{util, AbiCommand, ColorPreference};
use camino::Utf8PathBuf;
use colored::Colorize;
use near_abi::AbiRoot;
Expand Down Expand Up @@ -28,6 +28,7 @@ pub(crate) fn generate_abi(
crate_metadata: &CrateMetadata,
generate_docs: bool,
hide_warnings: bool,
color: ColorPreference,
) -> anyhow::Result<AbiRoot> {
let root_node = crate_metadata
.raw_metadata
Expand Down Expand Up @@ -89,6 +90,7 @@ pub(crate) fn generate_abi(
],
util::dylib_extension(),
hide_warnings,
color,
)?;

let mut contract_abi = util::handle_step("Extracting ABI...", || {
Expand Down Expand Up @@ -173,6 +175,8 @@ fn strip_docs(abi_root: &mut near_abi::AbiRoot) {
}

pub(crate) fn run(args: AbiCommand) -> anyhow::Result<()> {
args.color.apply();

let crate_metadata = util::handle_step("Collecting cargo project metadata...", || {
CrateMetadata::collect(CargoManifestPath::try_from(
args.manifest_path.unwrap_or_else(|| "Cargo.toml".into()),
Expand All @@ -190,7 +194,7 @@ pub(crate) fn run(args: AbiCommand) -> anyhow::Result<()> {
} else {
AbiFormat::Json
};
let contract_abi = generate_abi(&crate_metadata, args.doc, false)?;
let contract_abi = generate_abi(&crate_metadata, args.doc, false, args.color)?;
let AbiResult { path } =
write_to_file(&contract_abi, &crate_metadata, format, AbiCompression::NoOp)?;

Expand Down
5 changes: 4 additions & 1 deletion cargo-near/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ use std::io::BufRead;
const COMPILATION_TARGET: &str = "wasm32-unknown-unknown";

pub(crate) fn run(args: BuildCommand) -> anyhow::Result<()> {
args.color.apply();

util::handle_step("Checking the host environment...", || {
if !util::invoke_rustup(&["target", "list", "--installed"])?
.lines()
Expand Down Expand Up @@ -40,7 +42,7 @@ pub(crate) fn run(args: BuildCommand) -> anyhow::Result<()> {
let mut abi = None;
let mut min_abi_path = None;
if !args.no_abi {
let mut contract_abi = abi::generate_abi(&crate_metadata, args.doc, true)?;
let mut contract_abi = abi::generate_abi(&crate_metadata, args.doc, true, args.color)?;
contract_abi.metadata.build = Some(BuildInfo {
compiler: format!("rustc {}", rustc_version::version()?),
builder: format!("cargo-near {}", env!("CARGO_PKG_VERSION")),
Expand Down Expand Up @@ -72,6 +74,7 @@ pub(crate) fn run(args: BuildCommand) -> anyhow::Result<()> {
build_env,
"wasm",
false,
args.color,
)?;

wasm_artifact.path = util::copy(&wasm_artifact.path, &out_dir)?;
Expand Down
58 changes: 58 additions & 0 deletions cargo-near/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::{env, str::FromStr};

use camino::Utf8PathBuf;
use clap::{AppSettings, Args, Parser, Subcommand};

Expand Down Expand Up @@ -45,6 +47,12 @@ pub struct AbiCommand {
/// Path to the `Cargo.toml` of the contract to build
#[clap(long, parse(from_str), value_name = "PATH")]
pub manifest_path: Option<Utf8PathBuf>,
/// Coloring: auto, always, never
#[clap(long, value_name = "WHEN")]
#[clap(default_value = "auto", possible_values = &["auto", "always", "never"])]
#[clap(hide_default_value = true, hide_possible_values = true)]
#[clap(parse(try_from_str = ColorPreference::from_str))]
pub color: ColorPreference,
}

#[derive(Debug, clap::Args)]
Expand All @@ -68,6 +76,56 @@ pub struct BuildCommand {
/// Path to the `Cargo.toml` of the contract to build
#[clap(long, parse(from_str), value_name = "PATH")]
pub manifest_path: Option<Utf8PathBuf>,
/// Coloring: auto, always, never
#[clap(long, value_name = "WHEN")]
#[clap(default_value = "auto", possible_values = &["auto", "always", "never"])]
#[clap(hide_default_value = true, hide_possible_values = true)]
#[clap(parse(try_from_str = ColorPreference::from_str))]
pub color: ColorPreference,
}

#[derive(Copy, Clone, Debug)]
pub enum ColorPreference {
Always,
Never,
}

impl FromStr for ColorPreference {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"auto" => match env::var("NO_COLOR") {
Ok(v) if v != "0" => Ok(ColorPreference::Never),
_ => {
if atty::is(atty::Stream::Stderr) {
Ok(ColorPreference::Always)
} else {
Ok(ColorPreference::Never)
}
}
},
"always" => Ok(ColorPreference::Always),
"never" => Ok(ColorPreference::Never),
_ => Err(format!("invalid color preference: {}", s)),
}
}
}

impl ColorPreference {
pub fn as_str(&self) -> &str {
match self {
ColorPreference::Always => "always",
ColorPreference::Never => "never",
}
}

pub fn apply(&self) {
match self {
ColorPreference::Always => colored::control::set_override(true),
ColorPreference::Never => colored::control::set_override(false),
}
}
}

pub fn exec(cmd: NearCommand) -> anyhow::Result<()> {
Expand Down
6 changes: 6 additions & 0 deletions cargo-near/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
use cargo_near::Opts;
use clap::Parser;
use colored::Colorize;
use std::env;

fn main() {
env_logger::init();

match env::var("NO_COLOR") {
Ok(v) if v != "0" => colored::control::set_override(false),
_ => colored::control::set_override(atty::is(atty::Stream::Stderr)),
}

let Opts::Near(args) = Opts::parse();
match cargo_near::exec(args.cmd) {
Ok(()) => {}
Expand Down
11 changes: 9 additions & 2 deletions cargo-near/src/util/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::cargo::manifest::CargoManifestPath;
use crate::ColorPreference;
use anyhow::{Context, Result};
use camino::{Utf8Path, Utf8PathBuf};
use cargo_metadata::{Artifact, Message};
Expand Down Expand Up @@ -36,6 +37,7 @@ fn invoke_cargo<A, P, E, S, EK, EV>(
args: A,
working_dir: Option<P>,
env: E,
color: ColorPreference,
) -> Result<Vec<Artifact>>
where
A: IntoIterator<Item = S>,
Expand All @@ -58,8 +60,11 @@ where

cmd.arg(command);
cmd.args(args);
// Ensure that cargo uses color output for piped stderr.
cmd.args(["--color", "always"]);

match color {
ColorPreference::Always => cmd.args(["--color", "always"]),
ColorPreference::Never => cmd.args(["--color", "never"]),
};

log::info!("Invoking cargo: {:?}", cmd);

Expand Down Expand Up @@ -161,6 +166,7 @@ pub(crate) fn compile_project(
mut env: Vec<(&str, &str)>,
artifact_extension: &str,
hide_warnings: bool,
color: ColorPreference,
) -> anyhow::Result<CompilationArtifact> {
let mut final_env = BTreeMap::new();

Expand Down Expand Up @@ -190,6 +196,7 @@ pub(crate) fn compile_project(
[&["--message-format=json-render-diagnostics"], args].concat(),
manifest_path.directory().ok(),
final_env.iter(),
color,
)?;

// We find the last compiler artifact message which should contain information about the
Expand Down