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

Clean up custom console output with utils #712

Merged
merged 2 commits into from
Jun 28, 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
28 changes: 9 additions & 19 deletions src/bin/rm/rm.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use cargo_edit::shell_status;
use cargo_edit::CargoResult;
use cargo_edit::{colorize_stderr, manifest_from_pkgid, LocalManifest};
use cargo_edit::{manifest_from_pkgid, LocalManifest};
use clap::Args;
use std::borrow::Cow;
use std::io::Write;
use std::path::PathBuf;
use termcolor::{Color, ColorSpec, StandardStream, WriteColor};

/// Remove a dependency from a Cargo.toml manifest file.
#[derive(Debug, Args)]
Expand Down Expand Up @@ -81,21 +80,6 @@ impl RmArgs {
#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ArgEnum)]
enum UnstableOptions {}

fn print_msg(name: &str, section: &[String]) -> CargoResult<()> {
let colorchoice = colorize_stderr();
let mut output = StandardStream::stderr(colorchoice);
output.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true))?;
write!(output, "{:>12}", "Removing")?;
output.reset()?;
let section = if section.len() == 1 {
section[0].clone()
} else {
format!("{} for target `{}`", &section[2], &section[1])
};
writeln!(output, " {} from {}", name, section)?;
Ok(())
}

fn exec(args: &RmArgs) -> CargoResult<()> {
let manifest_path = if let Some(ref pkgid) = args.pkgid {
let pkg = manifest_from_pkgid(args.manifest_path.as_deref(), pkgid)?;
Expand All @@ -109,7 +93,13 @@ fn exec(args: &RmArgs) -> CargoResult<()> {
deps.iter()
.map(|dep| {
if !args.quiet {
print_msg(dep, &args.get_section())?;
let section = args.get_section();
let section = if section.len() >= 3 {
format!("{} for target `{}`", &section[2], &section[1])
} else {
section[0].clone()
};
shell_status("Removing", &format!("{dep} from {section}",))?;
}
let result = manifest
.remove_from_table(&args.get_section(), dep)
Expand Down
19 changes: 2 additions & 17 deletions src/bin/upgrade/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::io::Write;
use std::path::{Path, PathBuf};

use cargo_edit::{
colorize_stderr, find, get_latest_dependency, manifest_from_pkgid, registry_url,
colorize_stderr, find, get_latest_dependency, manifest_from_pkgid, registry_url, shell_warn,
update_registry_index, CargoResult, Context, CrateSpec, Dependency, LocalManifest,
};
use clap::Args;
Expand Down Expand Up @@ -191,7 +191,7 @@ fn exec(args: UpgradeArgs) -> CargoResult<()> {
}

if args.dry_run {
dry_run_message()?;
shell_warn("aborting upgrade due to dry run")?;
}

Ok(())
Expand Down Expand Up @@ -517,18 +517,3 @@ fn deprecated_message(message: &str) -> CargoResult<()> {
.with_context(|| "Failed to clear output colour")?;
Ok(())
}

fn dry_run_message() -> CargoResult<()> {
let colorchoice = colorize_stderr();
let mut output = StandardStream::stderr(colorchoice);
output
.set_color(ColorSpec::new().set_fg(Some(Color::Yellow)).set_bold(true))
.with_context(|| "Failed to set output colour")?;
write!(output, "warning").with_context(|| "Failed to write dry run message")?;
output
.set_color(&ColorSpec::new())
.with_context(|| "Failed to clear output colour")?;
writeln!(output, ": aborting upgrade due to dry run")
.with_context(|| "Failed to write dry run message")?;
Ok(())
}
23 changes: 4 additions & 19 deletions src/fetch.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use std::collections::BTreeMap;
use std::env;
use std::io::Write;
use std::path::Path;
use std::time::Duration;

use termcolor::{Color, ColorSpec, StandardStream, WriteColor};
use url::Url;

use super::errors::*;
use super::registry::registry_url;
use super::shell_status;
use super::VersionExt;
use super::{Dependency, LocalManifest, Manifest};

use regex::Regex;

/// Query latest version from a registry index
Expand Down Expand Up @@ -250,19 +250,13 @@ fn registry_features(v: &crates_index::Version) -> BTreeMap<String, Vec<String>>

/// update registry index for given project
pub fn update_registry_index(registry: &Url, quiet: bool) -> CargoResult<()> {
let colorchoice = super::colorize_stderr();
let mut output = StandardStream::stderr(colorchoice);

let mut index = crates_index::Index::from_url(registry.as_str())?;
if !quiet {
output.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true))?;
write!(output, "{:>12}", "Updating")?;
output.reset()?;
writeln!(output, " '{}' index", registry)?;
shell_status("Updating", &format!("'{}' index", registry))?;
}

while need_retry(index.update())? {
registry_blocked_message(&mut output)?;
shell_status("Blocking", "waiting for lock on registry index")?;
std::thread::sleep(REGISTRY_BACKOFF);
}

Expand All @@ -287,15 +281,6 @@ fn need_retry(res: Result<(), crates_index::Error>) -> CargoResult<bool> {
}
}

/// Report to user that the Registry is locked
fn registry_blocked_message(output: &mut StandardStream) -> CargoResult<()> {
output.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true))?;
write!(output, "{:>12}", "Blocking")?;
output.reset()?;
writeln!(output, " waiting for lock on registry index")?;
Ok(())
}

/// Load Cargo.toml in a local path
///
/// This will fail, when Cargo.toml is not present in the root of the path.
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,5 @@ pub use fetch::{
pub use manifest::{find, LocalManifest, Manifest};
pub use metadata::{manifest_from_pkgid, workspace_members};
pub use registry::registry_url;
pub use util::{colorize_stderr, ColorChoice};
pub use util::{colorize_stderr, shell_print, shell_status, shell_warn, Color, ColorChoice};
pub use version::{upgrade_requirement, VersionExt};
26 changes: 5 additions & 21 deletions src/manifest.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use std::{env, str};

use semver::{Version, VersionReq};
use termcolor::{BufferWriter, Color, ColorSpec, WriteColor};

use super::dependency::Dependency;
use super::errors::*;
use super::shell_status;

const MANIFEST_FILENAME: &str = "Cargo.toml";
const DEP_TABLES: &[&str] = &["dependencies", "dev-dependencies", "build-dependencies"];
Expand Down Expand Up @@ -703,25 +702,10 @@ fn print_upgrade_if_necessary(
return Ok(());
}

let colorchoice = super::colorize_stderr();
let bufwtr = BufferWriter::stderr(colorchoice);
let mut buffer = bufwtr.buffer();
buffer
.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true))
.with_context(|| "Failed to set output colour")?;
write!(&mut buffer, " Upgrading ").with_context(|| "Failed to write upgrade message")?;
buffer
.set_color(&ColorSpec::new())
.with_context(|| "Failed to clear output colour")?;
writeln!(
&mut buffer,
"{} v{} -> v{}",
crate_name, old_version, new_version,
)
.with_context(|| "Failed to write upgrade versions")?;
bufwtr
.print(&buffer)
.with_context(|| "Failed to print upgrade message")?;
shell_status(
"Upgrading",
&format!("{crate_name} v{old_version} -> v{new_version}"),
)?;

Ok(())
}
Expand Down
37 changes: 36 additions & 1 deletion src/util.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
pub use termcolor::ColorChoice;
use std::io::Write;

pub use termcolor::{Color, ColorChoice};
use termcolor::{ColorSpec, StandardStream, WriteColor};

use crate::{CargoResult, Context};

/// Whether to color logged output
pub fn colorize_stderr() -> ColorChoice {
Expand All @@ -8,3 +13,33 @@ pub fn colorize_stderr() -> ColorChoice {
ColorChoice::Never
}
}

/// Print a message with a colored title in the style of Cargo shell messages.
pub fn shell_print(status: &str, message: &str, color: Color, justified: bool) -> CargoResult<()> {
let color_choice = colorize_stderr();
let mut output = StandardStream::stderr(color_choice);

output.set_color(ColorSpec::new().set_fg(Some(color)).set_bold(true))?;
if justified {
write!(output, "{status:>12}")?;
} else {
write!(output, "{}", status)?;
output.set_color(ColorSpec::new().set_bold(true))?;
write!(output, ":")?;
}
output.reset()?;

writeln!(output, " {message}").with_context(|| "Failed to write message")?;

Ok(())
}

/// Print a styled action message.
pub fn shell_status(action: &str, message: &str) -> CargoResult<()> {
shell_print(action, message, Color::Green, true)
}

/// Print a styled warning message.
pub fn shell_warn(message: &str) -> CargoResult<()> {
shell_print("warning", message, Color::Yellow, false)
}
4 changes: 2 additions & 2 deletions tests/cmd/upgrade/alt_registry.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ stdout = """
none:
"""
stderr = """
Upgrading regex v0.2 -> v99999.0.0
Upgrading toml_edit v0.1.5 -> v99999.0.0
Upgrading regex v0.2 -> v99999.0.0
Upgrading toml_edit v0.1.5 -> v99999.0.0
"""
fs.sandbox = true

Expand Down
2 changes: 1 addition & 1 deletion tests/cmd/upgrade/dry_run.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ stdout = """
cargo-list-test-fixture:
"""
stderr = """
Upgrading docopt v0.8.0 -> v99999.0.0
Upgrading docopt v0.8.0 -> v99999.0.0
warning: aborting upgrade due to dry run
"""
fs.sandbox = true
Expand Down
2 changes: 1 addition & 1 deletion tests/cmd/upgrade/dry_run_prerelease.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ stdout = """
cargo-list-test-fixture:
"""
stderr = """
Upgrading docopt v0.8.0 -> v99999.0.0-alpha.1
Upgrading docopt v0.8.0 -> v99999.0.0-alpha.1
warning: aborting upgrade due to dry run
"""
fs.sandbox = true
Expand Down
28 changes: 14 additions & 14 deletions tests/cmd/upgrade/exclude_dep.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@ stdout = """
None:
"""
stderr = """
Upgrading assert_cli v0.2.0 -> v99999.0.0
Upgrading ftp v2.2.1 -> v99999.0.0
Upgrading ftp v2.2.1 -> v99999.0.0
Upgrading geo v0.7.0 -> v99999.0.0
Upgrading openssl v0.9 -> v99999.0.0
Upgrading pad v0.1 -> v99999.0.0
Upgrading renamed v0.1 -> v99999.0.0
Upgrading rget v0.3.0 -> v99999.0.0
Upgrading semver v0.7 -> v99999.0.0
Upgrading serde_json v1.0 -> v99999.0.0
Upgrading syn v0.11.10 -> v99999.0.0
Upgrading tar v0.4 -> v99999.0.0
Upgrading tempdir v0.3 -> v99999.0.0
Upgrading toml_edit v0.1.5 -> v99999.0.0
Upgrading assert_cli v0.2.0 -> v99999.0.0
Upgrading ftp v2.2.1 -> v99999.0.0
Upgrading ftp v2.2.1 -> v99999.0.0
Upgrading geo v0.7.0 -> v99999.0.0
Upgrading openssl v0.9 -> v99999.0.0
Upgrading pad v0.1 -> v99999.0.0
Upgrading renamed v0.1 -> v99999.0.0
Upgrading rget v0.3.0 -> v99999.0.0
Upgrading semver v0.7 -> v99999.0.0
Upgrading serde_json v1.0 -> v99999.0.0
Upgrading syn v0.11.10 -> v99999.0.0
Upgrading tar v0.4 -> v99999.0.0
Upgrading tempdir v0.3 -> v99999.0.0
Upgrading toml_edit v0.1.5 -> v99999.0.0
"""
fs.sandbox = true

Expand Down
2 changes: 1 addition & 1 deletion tests/cmd/upgrade/exclude_renamed.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ stdout = """
cargo-list-test-fixture:
"""
stderr = """
Upgrading toml_edit v0.1.5 -> v99999.0.0
Upgrading toml_edit v0.1.5 -> v99999.0.0
"""
fs.sandbox = true

Expand Down
4 changes: 2 additions & 2 deletions tests/cmd/upgrade/implicit_prerelease.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ stdout = """
cargo-list-test-fixture:
"""
stderr = """
Upgrading a v1.0 -> v99999.0.0
Upgrading b v0.8.0-alpha -> v99999.0.0-alpha.1
Upgrading a v1.0 -> v99999.0.0
Upgrading b v0.8.0-alpha -> v99999.0.0-alpha.1
"""
fs.sandbox = true

Expand Down
2 changes: 1 addition & 1 deletion tests/cmd/upgrade/optional_dep.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ stdout = """
cargo-list-test-fixture:
"""
stderr = """
Upgrading docopt v0.8.0 -> v99999.0.0
Upgrading docopt v0.8.0 -> v99999.0.0
"""
fs.sandbox = true

Expand Down
2 changes: 1 addition & 1 deletion tests/cmd/upgrade/prerelease.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ stdout = """
cargo-list-test-fixture:
"""
stderr = """
Upgrading docopt v0.8.0 -> v99999.0.0-alpha.1
Upgrading docopt v0.8.0 -> v99999.0.0-alpha.1
"""
fs.sandbox = true

Expand Down
2 changes: 1 addition & 1 deletion tests/cmd/upgrade/preserve_precision_major.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ stdout = """
cargo-list-test-fixture:
"""
stderr = """
Upgrading docopt v0 -> v99999
Upgrading docopt v0 -> v99999
"""
fs.sandbox = true

Expand Down
2 changes: 1 addition & 1 deletion tests/cmd/upgrade/preserve_precision_minor.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ stdout = """
cargo-list-test-fixture:
"""
stderr = """
Upgrading docopt v0.8 -> v99999.0
Upgrading docopt v0.8 -> v99999.0
"""
fs.sandbox = true

Expand Down
2 changes: 1 addition & 1 deletion tests/cmd/upgrade/preserve_precision_patch.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ stdout = """
cargo-list-test-fixture:
"""
stderr = """
Upgrading docopt v0.8.0 -> v99999.0.0
Upgrading docopt v0.8.0 -> v99999.0.0
"""
fs.sandbox = true

Expand Down
2 changes: 1 addition & 1 deletion tests/cmd/upgrade/single_dep.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ stdout = """
cargo-list-test-fixture:
"""
stderr = """
Upgrading docopt v0.8.0 -> v99999.0.0
Upgrading docopt v0.8.0 -> v99999.0.0
"""
fs.sandbox = true

Expand Down
2 changes: 1 addition & 1 deletion tests/cmd/upgrade/skip_compatible.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ stdout = """
cargo-list-test-fixture:
"""
stderr = """
Upgrading test_breaking v0.1 -> v0.2.0
Upgrading test_breaking v0.1 -> v0.2.0
"""
fs.sandbox = true

Expand Down
Loading