Skip to content

Commit

Permalink
internal: decolorize to prepare for proper colorization
Browse files Browse the repository at this point in the history
  • Loading branch information
nc7s committed Nov 9, 2023
1 parent 69094ae commit 4530e08
Show file tree
Hide file tree
Showing 6 changed files with 13 additions and 74 deletions.
32 changes: 0 additions & 32 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 @@ -33,7 +33,6 @@ unescape = "0.1.0"
memmap2 = "0.9.0"
tempfile = "3.8.0"
thiserror = "1.0.50"
ansi_term = "0.12.1"
clap.workspace = true

[dev-dependencies]
Expand Down
3 changes: 1 addition & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ pub(crate) mod utils;
use std::process;

pub(crate) use self::input::{App, Source};
use ansi_term::{Color, Style};
pub(crate) use error::{Error, Result};
use replacer::Replacer;

use clap::Parser;

fn main() {
if let Err(e) = try_main() {
eprintln!("{}: {}", Style::from(Color::Red).bold().paint("error"), e);
eprintln!("{}: {}", "error", e);
process::exit(1);
}
}
Expand Down
12 changes: 1 addition & 11 deletions src/replacer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ impl Replacer {
regex: &regex::bytes::Regex,
limit: usize,
haystack: &'haystack [u8],
use_color: bool,
_use_color: bool,
mut rep: R,
) -> Cow<'haystack, [u8]> {
let mut it = regex.captures_iter(haystack).enumerate().peekable();
Expand All @@ -116,17 +116,7 @@ impl Replacer {
// unwrap on 0 is OK because captures only reports matches
let m = cap.get(0).unwrap();
new.extend_from_slice(&haystack[last_match..m.start()]);
if use_color {
new.extend_from_slice(
ansi_term::Color::Blue.prefix().to_string().as_bytes(),
);
}
rep.replace_append(&cap, &mut new);
if use_color {
new.extend_from_slice(
ansi_term::Color::Blue.suffix().to_string().as_bytes(),
);
}
last_match = m.end();
if limit > 0 && i >= limit - 1 {
break;
Expand Down
18 changes: 7 additions & 11 deletions src/replacer/validate.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use std::{error::Error, fmt, str::CharIndices};

use ansi_term::{Color, Style};

#[derive(Debug)]
pub struct InvalidReplaceCapture {
original_replace: String,
Expand Down Expand Up @@ -53,21 +51,19 @@ impl fmt::Display for InvalidReplaceCapture {
// Build up the error to show the user
let mut formatted = String::new();
let mut arrows_start = Span::start_at(0);
let special = Style::new().bold();
let error = Style::from(Color::Red).bold();
for (byte_index, c) in original_replace.char_indices() {
let (prefix, suffix, text) = match SpecialChar::new(c) {
Some(c) => {
(Some(special.prefix()), Some(special.suffix()), c.render())
(Some("" /* special prefix */), Some("" /* special suffix */), c.render())
}
None => {
let (prefix, suffix) = if byte_index == invalid_ident.start
{
(Some(error.prefix()), None)
(Some("" /* error prefix */), None)
} else if byte_index
== invalid_ident.end.checked_sub(1).unwrap()
{
(None, Some(error.suffix()))
(None, Some("" /* error suffix */))
} else {
(None, None)
};
Expand Down Expand Up @@ -99,20 +95,20 @@ impl fmt::Display for InvalidReplaceCapture {
let mut arrows = " ".repeat(arrows_span.start);
arrows.push_str(&format!(
"{}",
Style::new().bold().paint("^".repeat(arrows_span.len()))
"^".repeat(arrows_span.len())
));

let ident = invalid_ident.slice(original_replace);
let (number, the_rest) = ident.split_at(*num_leading_digits);
let disambiguous = format!("${{{number}}}{the_rest}");
let error_message = format!(
"The numbered capture group `{}` in the replacement text is ambiguous.",
Style::new().bold().paint(format!("${}", number).to_string())
format!("${}", number).to_string()
);
let hint_message = format!(
"{}: Use curly braces to disambiguate it `{}`.",
Style::from(Color::Blue).bold().paint("hint"),
Style::new().bold().paint(disambiguous)
"hint",
disambiguous
);

writeln!(f, "{}", error_message)?;
Expand Down
21 changes: 4 additions & 17 deletions tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,7 @@ mod cli {
sd().args(["-p", "abc\\d+", "", file.path().to_str().unwrap()])
.assert()
.success()
.stdout(format!(
"{}{}def\n",
ansi_term::Color::Blue.prefix(),
ansi_term::Color::Blue.suffix()
));
.stdout("def");

assert_file(file.path(), "abc123def");

Expand Down Expand Up @@ -113,13 +109,7 @@ mod cli {

fn bad_replace_helper_plain(replace: &str) -> String {
let stderr = bad_replace_helper_styled(replace);

// TODO: no easy way to toggle off styling yet. Add a `--color <when>`
// flag, and respect things like `$NO_COLOR`. `ansi_term` is
// unmaintained, so we should migrate off of it anyways
console::AnsiCodeIterator::new(&stderr)
.filter_map(|(s, is_ansi)| (!is_ansi).then_some(s))
.collect()
stderr
}

#[test]
Expand Down Expand Up @@ -182,7 +172,7 @@ mod cli {

// NOTE: styled terminal output is platform dependent, so convert to a
// common format, in this case HTML, to check
#[test]
//#[test]
fn ambiguous_replace_ensure_styling() {
let styled_stderr = bad_replace_helper_styled("\t$1bad after");
let html_stderr =
Expand Down Expand Up @@ -225,10 +215,7 @@ mod cli {
])
.assert()
.success()
.stdout(format!(
"{}\nfoo\nfoo\n",
ansi_term::Color::Blue.paint("bar")
));
.stdout("bar\nfoo\nfoo");

Ok(())
}
Expand Down

0 comments on commit 4530e08

Please sign in to comment.