Skip to content
This repository has been archived by the owner on Sep 28, 2022. It is now read-only.

Commit

Permalink
[cargo-hakari] switch to owo-colors
Browse files Browse the repository at this point in the history
Some notes:
* We have to use the stylesheet approach: see the discussion in
jam1garner/owo-colors#33 (comment).
* This is an opportunity to clean up a bunch of output-related code --
  we can now switch to a type-level state machine from `OutputOpts` to
  `OutputContext`.
  • Loading branch information
sunshowers committed Dec 6, 2021
1 parent 926f260 commit 4f4c272
Show file tree
Hide file tree
Showing 9 changed files with 189 additions and 81 deletions.
34 changes: 22 additions & 12 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion tools/cargo-hakari/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,15 @@ camino = "1.0.5"
cfg-if = "1.0.0"
# disable tracing integration since we don't use it
color-eyre = { version = "0.5.11", default-features = false }
colored = "2.0.0"
dialoguer = "0.9.0"
duct = "0.13.5"
enable-ansi-support = "0.1.0"
env_logger = "0.9.0"
guppy = { version = "0.12.3", path = "../../guppy" }
hakari = { version = "0.7.3", path = "../hakari", features = ["cli-support"] }
log = "0.4.14"
owo-colors = { version = "3.1.0", features = ["supports-colors"] }
supports-color = "1.3.0"
structopt = "0.3.25"
workspace-hack = { version = "0.1", path = "../../workspace-hack" }

Expand Down
14 changes: 7 additions & 7 deletions tools/cargo-hakari/src/cargo_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,24 @@

//! Cargo CLI support.

use crate::output::OutputOpts;
use crate::output::OutputContext;
use camino::Utf8PathBuf;
use std::{convert::TryInto, env, path::PathBuf};

#[derive(Clone, Debug)]
pub(crate) struct CargoCli<'a> {
cargo_path: Utf8PathBuf,
output_opts: OutputOpts,
output: OutputContext,
command: &'a str,
args: Vec<&'a str>,
}

impl<'a> CargoCli<'a> {
pub(crate) fn new(command: &'a str, output_opts: OutputOpts) -> Self {
pub(crate) fn new(command: &'a str, output: OutputContext) -> Self {
let cargo_path = cargo_path();
Self {
cargo_path,
output_opts,
output,
command,
args: vec![],
}
Expand All @@ -44,13 +44,13 @@ impl<'a> CargoCli<'a> {

pub(crate) fn to_expression(&self) -> duct::Expression {
let mut initial_args = vec![];
if self.output_opts.quiet {
if self.output.quiet {
initial_args.push("--quiet");
}
if self.output_opts.verbose {
if self.output.verbose {
initial_args.push("--verbose");
}
initial_args.push(self.output_opts.color.to_arg());
initial_args.push(self.output.color.to_arg());

initial_args.push(self.command);

Expand Down
63 changes: 37 additions & 26 deletions tools/cargo-hakari/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@

use crate::{
helpers::{read_contents, regenerate_lockfile},
output::OutputOpts,
output::{OutputContext, OutputOpts},
publish::publish_hakari,
};
use camino::{Utf8Path, Utf8PathBuf};
use color_eyre::eyre::{eyre, Result, WrapErr};
use colored::Colorize;
use guppy::{
graph::{PackageGraph, PackageSet},
MetadataCommand,
Expand All @@ -20,6 +19,7 @@ use hakari::{
HakariBuilder, HakariCargoToml, HakariOutputOptions, TomlOutError,
};
use log::{error, info};
use owo_colors::OwoColorize;
use std::convert::TryFrom;
use structopt::{clap::AppSettings, StructOpt};

Expand Down Expand Up @@ -61,7 +61,7 @@ impl Args {
}
}

#[derive(Clone, Debug, StructOpt)]
#[derive(Debug, StructOpt)]
struct GlobalOpts {
#[structopt(flatten)]
output: OutputOpts,
Expand Down Expand Up @@ -102,7 +102,7 @@ enum Command {

impl Command {
fn exec(self, output: OutputOpts) -> Result<i32> {
output.init_logger();
let output = output.init();
let metadata_command = MetadataCommand::new();
let package_graph = metadata_command
.build_graph()
Expand Down Expand Up @@ -130,14 +130,17 @@ impl Command {
let ops = init.make_ops();
apply_on_dialog(dry_run, yes, &ops, &output, || {
let steps = [
format!("* configure at {}", DEFAULT_CONFIG_PATH.bold()),
format!(
"* configure at {}",
DEFAULT_CONFIG_PATH.style(output.styles.config_path),
),
format!(
"* run {} to generate contents",
"cargo hakari generate".bold()
"cargo hakari generate".style(output.styles.command),
),
format!(
"* run {} to add dependency lines",
"cargo hakari manage-deps".bold()
"cargo hakari manage-deps".style(output.styles.command),
),
];
info!("next steps:\n{}\n", steps.join("\n"));
Expand Down Expand Up @@ -263,7 +266,7 @@ impl CommandWithBuilder {
self,
builder: HakariBuilder<'_>,
hakari_output: HakariOutputOptions,
output: OutputOpts,
output: OutputContext,
) -> Result<i32> {
let hakari_package = *builder
.hakari_package()
Expand All @@ -283,12 +286,13 @@ impl CommandWithBuilder {
let package = package_graph
.metadata(&package_id)
.expect("package ID obtained from the same graph");
error!("unrecognized registry URL {} found for {} {}\n(add to {} section of {})",
registry_url.bold(),
package.name().bold(),
format!("v{}", package.version()).bold(),
"[registries]".bold(),
DEFAULT_CONFIG_PATH.blue().bold(),
error!(
"unrecognized registry URL {} found for {} v{}\n\
(add to [registries] section of {})",
registry_url.style(output.styles.registry_url),
package.name().style(output.styles.package_name),
package.version().style(output.styles.package_version),
"hakari.toml".style(output.styles.config_path),
);
// 102 is picked pretty arbitrarily because regular errors exit with 101.
return Ok(102);
Expand All @@ -304,17 +308,20 @@ impl CommandWithBuilder {
}
CommandWithBuilder::Verify => match builder.verify() {
Ok(()) => {
info!("{} works correctly", hakari_package.name().bold());
info!(
"{} works correctly",
hakari_package.name().style(output.styles.package_name),
);
Ok(0)
}
Err(errs) => {
let mut display = errs.display();
if output.should_colorize() {
display.color();
if output.color.is_enabled() {
display.colorize();
}
info!(
"{} didn't work correctly:\n{}",
hakari_package.name().bold(),
hakari_package.name().style(output.styles.package_name),
display,
);
Ok(1)
Expand All @@ -333,7 +340,9 @@ impl CommandWithBuilder {
return Ok(0);
}

apply_on_dialog(dry_run, yes, &ops, &output, || regenerate_lockfile(output))
apply_on_dialog(dry_run, yes, &ops, &output, || {
regenerate_lockfile(output.clone())
})
}
CommandWithBuilder::RemoveDeps {
packages,
Expand All @@ -348,7 +357,9 @@ impl CommandWithBuilder {
return Ok(0);
}

apply_on_dialog(dry_run, yes, &ops, &output, || regenerate_lockfile(output))
apply_on_dialog(dry_run, yes, &ops, &output, || {
regenerate_lockfile(output.clone())
})
}
CommandWithBuilder::Explain {
dep_name: crate_name,
Expand All @@ -367,7 +378,7 @@ impl CommandWithBuilder {
.explain(dep.id())
.expect("package ID should be known since it was in the output");
let mut display = explain.display();
if output.should_colorize() {
if output.color.is_enabled() {
display.colorize();
}
info!("\n{}", display);
Expand Down Expand Up @@ -460,12 +471,12 @@ fn write_to_cargo_toml(
existing_toml: HakariCargoToml,
new_contents: &str,
diff: bool,
output: OutputOpts,
output: OutputContext,
) -> Result<i32> {
if diff {
let patch = existing_toml.diff_toml(new_contents);
let mut formatter = PatchFormatter::new();
if output.should_colorize() {
if output.color.is_enabled() {
formatter = formatter.with_color();
}
info!("\n{}", formatter.fmt_patch(&patch));
Expand Down Expand Up @@ -493,11 +504,11 @@ fn apply_on_dialog(
dry_run: bool,
yes: bool,
ops: &WorkspaceOps<'_, '_>,
output: &OutputOpts,
output: &OutputContext,
after: impl FnOnce() -> Result<()>,
) -> Result<i32> {
let mut display = ops.display();
if output.should_colorize() {
if output.color.is_enabled() {
display.colorize();
}
info!("operations to perform:\n\n{}", display);
Expand All @@ -511,7 +522,7 @@ fn apply_on_dialog(
true
} else {
let colorful_theme = dialoguer::theme::ColorfulTheme::default();
let mut confirm = if output.should_colorize() {
let mut confirm = if output.color.is_enabled() {
dialoguer::Confirm::with_theme(&colorful_theme)
} else {
dialoguer::Confirm::with_theme(&dialoguer::theme::SimpleTheme)
Expand Down
4 changes: 2 additions & 2 deletions tools/cargo-hakari/src/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) The cargo-guppy Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::{cargo_cli::CargoCli, output::OutputOpts};
use crate::{cargo_cli::CargoCli, output::OutputContext};
use camino::{Utf8Path, Utf8PathBuf};
use color_eyre::{
eyre::{bail, WrapErr},
Expand Down Expand Up @@ -36,7 +36,7 @@ pub(crate) fn read_contents(
}

/// Regenerate the lockfile after dependency updates.
pub(crate) fn regenerate_lockfile(output: OutputOpts) -> Result<()> {
pub(crate) fn regenerate_lockfile(output: OutputContext) -> Result<()> {
// This seems to be the cheapest way to update the lockfile.
// cargo update -p <hakari-package> can sometimes cause unnecessary index updates.
let cargo_cli = CargoCli::new("tree", output);
Expand Down
Loading

0 comments on commit 4f4c272

Please sign in to comment.