refactor: Replace termcolor with anstream #4520
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
anstream
is an existing dependency through clap that allows a simpler, more natural way of writing styled text by making ANSI escape codes the API for styling, rather than astream.set_color(_)
. You write ANSI escape codes unconditionally, andanstream
will automatically strip them if needed (or convert them to wincon API calls for old Windows 8 systems). The caller can use whatever styling API they want and don't have to worry about what stream type they are ultimately written to.This will unblock
clap
output being styled. Clap can either directly handle writing output to the terminal, write unstyled output to a string, or write styled output to a string. With Rustup requiring all output to go through custom, termcolor-like streams for testing, this limited Rustup to only getting unstyled output. With this change, Rustup can get Clap's styled output and then haveanstream
process it as needed.To generate ANSI escape codes, this uses
anstyle
which is primarily intended to be a low-policy API for ANSI escape codes so they are API stable for theming in APIs likeclap
orannotate-snippets
. Using the formattingalternate
though provides a nice way to reset the stream.To simplify the transition for callers of
ColorableTerminal
through this transition, intermediate steps are taken, including adding theanstyle-termcolor
adapter and then removing it.I manually tested what I could of Rustup's output to spot check the styling. Cargo uses
snapbox
(the core oftrycmd
) to perform snapshot testing of ANSI escape codes by rendering them as SVGs which get rendered in GitHub diffs. Rustc integrated the lower levelanstyle-svg
package into their existing snapshotting system. I have considered SVG support fortrycmd
but haven't implemented it yet.