Vendor dependencies

This commit is contained in:
2026-08-01 16:11:49 +03:00
parent 7f139a0241
commit 6b5e7f0f8b
29706 changed files with 9575646 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"c3365e9dc64d32373afb66743a926ca5c735a7dd1488d6513528e780b3187185",".github/workflows/ci.yml":"afd071ff380511114cb907652410f558f0e01db541d90604985fd10b88dfe0ae",".github/yansi-example.svg":"0107acdb252027c31429b402e787196b1a3e90427937e6b5b5d12c39816f823c",".github/yansi-logo.png":"4839ae7c250815e64aa8819671a478724ce39c4786fe0b37fe951f44158d204c","Cargo.toml":"8908ed99df666028b0f0586fd3ab4851e94a95644b387c5078637dee10dc396e","Cargo.toml.orig":"5b46dcde0ef618bf66e17b926ab749681358af932e2f0b5f7a4030b812bb13fa","LICENSE-APACHE":"a8410ec5312922e0edae227ae056c7ea78093092503717ae377a2be4f0d295f1","LICENSE-MIT":"ce1f970284c4ab06e90671a984086692dc44da3e2b8ee86444d79b6f77bcf9e7","README.md":"9dc47127789cc349f5b13ae70b064449e4a17f4ee3020e6e11194f67692e9f2a","src/attr_quirk.rs":"b314f91d4beca906dd41789d65e1f627ffc512844fc8494affa27d06ca75e980","src/bitops.rs":"9417de2135b756a70be77cbfc96fb103185246c4a9299eaa719c8050df56d696","src/color.rs":"3e5993c0b1078be1708d69d67f4a83f6347b14efe9d440096fcb95cd1f3ee49a","src/condition.rs":"504413832b67b10cb48cb4a5cea994d278f39b8557ed30fcfe80d7ce1ff0ed00","src/global.rs":"bdd5b85f149660bb99ced27d4df3b41a9c3150c260e6a232a9a86c3fe3dcca78","src/hyperlink.rs":"4dbbdc4a84a3b599fe177904b3a523a1abf2d14dbd6aff71b5f50713bf40e604","src/lib.rs":"3a2eca594768c44a5aed88c422910b1d49926ebed43b2459d477bf0d045706b9","src/macros.rs":"45a978df474134889e773525b77a1e46844f39baac44b1f9ac86b67e934dff8e","src/paint.rs":"c64325a6e8570a69fd17a4b52710a366e20783ffe20a86eec98b6a1015a47b8e","src/set.rs":"dbcb24b9cc8824a9e379c68a649a222489b392c1fc83a559c51007bea8914a87","src/style.rs":"79b124d535ebce74280ef1f590d4646bac964a3ba27a57fae700bf6d83f34821","src/windows.rs":"f01a2e20a060fde7196153deac1e4b4943fda069b81058c8ca6dbce73f5fba48","tests/basic.rs":"4f4f0df3dfe15db8f39170933f98917f7f5047ed8a22ffae6cd1304a2623ac4a"},"package":"cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"}
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "3e35184fc181fef63bc11dedb22413e821168255"
},
"path_in_vcs": ""
}
+41
View File
@@ -0,0 +1,41 @@
name: CI
on: [push, pull_request]
env:
CARGO_TERM_COLOR: always
defaults:
run:
shell: bash
jobs:
test:
name: "${{ matrix.os.name }} ${{ matrix.test.name }} (${{ matrix.toolchain }})"
continue-on-error: false
runs-on: ${{ matrix.os.distro }}
strategy:
fail-fast: false
matrix:
os:
- { name: Linux, distro: ubuntu-latest }
- { name: Windows, distro: windows-latest }
- { name: macOS, distro: macOS-latest }
toolchain: [nightly, stable, "1.63"]
steps:
- name: Checkout Sources
uses: actions/checkout@v4
- name: Install Rust (${{ matrix.toolchain }})
uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{ matrix.toolchain }}
- name: Install Cargo Hack
uses: taiki-e/install-action@cargo-hack
- name: Check Feature Combinations
run: cargo hack check --feature-powerset --no-dev-deps --skip _nightly
- name: Run Tests
run: cargo hack test --feature-powerset --skip _nightly
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

+50
View File
@@ -0,0 +1,50 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.63"
name = "yansi"
version = "1.0.1"
authors = ["Sergio Benitez <sb@sergio.bz>"]
description = "A dead simple ANSI terminal color painting library."
documentation = "https://docs.rs/yansi"
readme = "README.md"
keywords = [
"ansi",
"terminal",
"color",
"format",
"paint",
]
categories = ["command-line-interface"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/SergioBenitez/yansi"
resolver = "2"
[package.metadata.docs.rs]
all-features = true
[dependencies.is-terminal]
version = "0.4.11"
optional = true
[features]
_nightly = []
alloc = []
default = ["std"]
detect-env = ["std"]
detect-tty = [
"is-terminal",
"std",
]
hyperlink = ["std"]
std = ["alloc"]
+31
View File
@@ -0,0 +1,31 @@
[package]
name = "yansi"
version = "1.0.1"
authors = ["Sergio Benitez <sb@sergio.bz>"]
repository = "https://github.com/SergioBenitez/yansi"
documentation = "https://docs.rs/yansi"
description = "A dead simple ANSI terminal color painting library."
keywords = ["ansi", "terminal", "color", "format", "paint"]
readme = "README.md"
license = "MIT OR Apache-2.0"
categories = ["command-line-interface"]
rust-version = "1.63"
edition = "2021"
resolver = "2"
[package.metadata.docs.rs]
all-features = true
[features]
default = ["std"]
detect-tty = ["is-terminal", "std"]
detect-env = ["std"]
hyperlink = ["std"]
std = ["alloc"]
alloc = []
# hidden feature to enable nightly doc cfg
_nightly = []
[dependencies]
is-terminal = { version = "0.4.11", optional = true }
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2017 Sergio Benitez
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+19
View File
@@ -0,0 +1,19 @@
The MIT License (MIT)
Copyright (c) 2017 Sergio Benitez
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+86
View File
@@ -0,0 +1,86 @@
<div align="left">
<img src="https://raw.githubusercontent.com/SergioBenitez/yansi/master/.github/yansi-logo.png"
align="center" alt="yansi logo" width="64" height="64">
<span>&nbsp;<b>Yansi</b></span>
<p>A dead simple ANSI terminal color painting library.</p>
[![Build Status](https://github.com/SergioBenitez/yansi/workflows/CI/badge.svg)](https://github.com/SergioBenitez/yansi/actions)
[![Current Crates.io Version](https://img.shields.io/crates/v/yansi.svg)](https://crates.io/crates/yansi)
[![Documentation](https://docs.rs/yansi/badge.svg)](https://docs.rs/yansi)
</div>
## Usage
In your `Cargo.toml`:
```toml
[dependencies]
yansi = "1.0"
```
In your source code:
```rust
use yansi::Paint;
println!("Testing, {}, {}, {}!",
"Ready".bold(),
"Set".black().on_yellow().invert().italic(),
"STOP".white().on_red().bright().underline().bold());
```
![> Testing, Ready, Set, STOP!](https://raw.githubusercontent.com/SergioBenitez/yansi/master/.github/yansi-example.svg)
[See the rustdocs](https://docs.rs/yansi) for complete usage details.
## Features
Why *y*et another *ANSI* terminal coloring library? Here are some reasons:
* This library makes simple things _simple_: `use` [`Paint`] and go!
* Zero dependencies by default. It really is simple.
* Zero allocations except as needed by opt-in [wrapping].
* [Automatic Windows support] for the vast majority (95%+) of Windows users.
* [Featureful `no_std`], no-`alloc`, support with `default-features = false`.
* [`Style` constructors are `const`]: store styles statically, even with
dynamic conditions!
* _Any_ type implementing a formatting trait can be styled, not just strings.
* Styling can be [enabled] and [disabled] globally and [dynamically], on the
fly.
* A `Style` can be predicated on arbitrary [conditions].
* Formatting specifiers like `{:x}` and `{:08b}` are supported and preserved!
* [Built-in (optional) conditions] for [TTY detection] and [common environment
variables].
* Arbitrary items can be [_masked_] for selective disabling.
* Styling can [_wrap_] to preserve styling across resets.
* Styling can [_linger_] beyond a single value.
* Experimental support for [hyperlinking] is included.
* The name `yansi` is pretty cool 😎.
[`Paint`]: https://docs.rs/yansi/1.0.0/yansi/trait.Paint.html
[`ansi_term`]: https://crates.io/crates/ansi_term
[`colored`]: https://crates.io/crates/colored
[`term_painter`]: https://crates.io/crates/term-painter
[_masked_]: https://docs.rs/yansi/1.0.0/yansi/#masking
[wrapping]: https://docs.rs/yansi/1.0.0/yansi/#wrapping
[_wrap_]: https://docs.rs/yansi/1.0.0/yansi/#wrapping
[_linger_]: https://docs.rs/yansi/1.0.0/yansi/#lingering
[conditions]: https://docs.rs/yansi/1.0.0/yansi/#per-style
[enabled]: https://docs.rs/yansi/1.0.0/yansi/fn.enable.html
[disabled]: https://docs.rs/yansi/1.0.0/yansi/fn.disable.html
[dynamically]: https://docs.rs/yansi/1.0.0/yansi/fn.whenever.html
[enabled conditionally]: https://docs.rs/yansi/1.0.0/yansi/struct.Condition.html
[TTY detection]: https://docs.rs/yansi/1.0.0/yansi/struct.Condition.html#impl-Condition-1
[common environment variables]: https://docs.rs/yansi/1.0.0/yansi/struct.Condition.html#impl-Condition-2
[Automatic Windows support]: https://docs.rs/yansi/1.0.0/yansi/#windows
[Built-in (optional) conditions]: https://docs.rs/yansi/1.0.0/yansi/struct.Condition.html#built-in-conditions
[hyperlinking]: https://docs.rs/yansi/1.0.0/yansi/hyperlink/index.html
[`Style` constructors are `const`]: https://docs.rs/yansi/1.0.0/yansi/#uniform-const-builders
[Featureful `no_std`]: https://docs.rs/yansi/1.0.0/yansi/#crate-features
## License
`yansi` is licensed under either of the following, at your option:
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT License ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
+207
View File
@@ -0,0 +1,207 @@
use crate::Style;
/// Enum representing text attributes, largely for text formatting.
///
/// Text attributes are typically applied to a [`Style`], [`Color`], or
/// [`Painted`] struct via the corresponding chainable builder methods such as
/// [`bold()`] or [`italic()`]. The returned value will apply the attribute(s)
/// when rendered or printed.
///
/// Attributes are idempotent, so applying an attribute more than once has no
/// more affect than applying it once.
///
/// # Terminal Support
///
/// Whether an applied attribute actually has an effect on how text is rendered
/// in a terminal depends on the terminal's support for the attribute as well as
/// the terminal's configuration. Common attributes, such as `bold`, `dim`,
/// `italic`, `underline`, and `strike` typically have good support and are
/// largely reliable. Less commonly supported attributes like `conceal` and
/// `invert` will _usually_ be supported by "modern" terminals. Rarely supported
/// attributes, such as `blink` and `rapid blink`, will typically have no
/// effect when applied.
///
/// # Example
///
/// ```rust
/// use yansi::{Style, Color::Red};
///
/// /// A style with red foreground and every "common" attribute applied.
/// static MAD: Style = Red.bold().dim().italic().underline().strike();
/// ```
///
/// [`Style`]: crate::Style
/// [`Painted`]: crate::Painted
/// [`Color`]: crate::Painted
/// [`bold()`]: crate::Style::bold()
/// [`italic()`]: crate::Style::italic()
#[derive(Debug, PartialEq, Eq, Copy, Clone, PartialOrd, Ord, Hash)]
pub enum Attribute {
/// Makes text <b>bold</b>.
///
/// Typically used via the [`bold()`](crate::Style::bold()) builder method.
Bold,
/// Makes text <span style="opacity: 50%">dim</span>.
///
/// Typically used via the [`dim()`](crate::Style::dim()) builder method.
Dim,
/// Display text in <i>italics</i>.
///
/// Typically used via the [`italic()`](crate::Style::italic()) builder
/// method.
Italic,
/// <u>Underline</u> text.
///
/// Typically used via the [`underline()`](crate::Style::underline())
/// builder method.
Underline,
/// <style>@keyframes blinker { 50% { opacity: 0; } }</style>
/// <span style="animation: blinker 1s linear infinite;">Blink.</span>
///
/// Typically used via the [`blink()`](crate::Style::blink()) builder
/// method.
Blink,
/// <style>@keyframes blinker { 50% { opacity: 0; } }</style>
/// <span style="animation: blinker 0.5s linear infinite;">Blink rapidly.</span>
///
/// Typically used via the [`rapid_blink()`](crate::Style::rapid_blink())
/// builder method.
RapidBlink,
/// <span style="background: black; color: white;">Invert</span>
/// (flip) the foreground and background colors.
///
/// Typically used via the [`invert()`](crate::Style::invert()) builder
/// method.
Invert,
/// <span style="color: #333; background: #000;">Conceal</span> text.
///
/// Typically used via the [`conceal()`](crate::Style::conceal()) builder
/// method.
Conceal,
/// Display text with a <s>strike</s> through it.
///
/// Typically used via the [`strike()`](crate::Style::strike()) builder
/// method.
Strike,
}
/// Enum representing a `yansi` quirk.
///
/// See the [crate level docs](crate#quirks) for details.
#[derive(Debug, PartialEq, Eq, Copy, Clone, PartialOrd, Ord, Hash)]
pub enum Quirk {
/// Mask: omit when painting is disabled.
///
/// Typically applied via the [`mask()`](crate::Painted::mask()) builder
/// method.
///
/// See the [crate level docs](crate#masking) for details.
Mask,
/// Wrap the value: replace resets with the wrapped styling.
///
/// Typically applied via the [`wrap()`](crate::Painted::wrap()) builder
/// method.
///
/// See the [crate level docs](crate#wrapping) for details.
Wrap,
/// Linger: do not reset the style after it is applied.
///
/// Typically applied via the [`linger()`](crate::Painted::linger()) builder
/// method.
///
/// See the [crate level docs](crate#lingering) for details.
Linger,
/// **Deprecated:** Use [`Quirk::Resetting`] instead.
#[deprecated(
since = "1.0.1",
note = "renamed to `Resetting` due to builder method conflicts with `Vec::clear()`.\n\
`Quirk::Clear` will be removed in a future release."
)]
Clear,
/// Always reset styling afterwards, even if no actual styling was applied.
///
/// Overrides the [`Linger`](Quirk::Linger) quirk if present.
///
/// Typically applied via the [`resetting()`](crate::Painted::resetting())
/// builder method.
Resetting,
/// Brighten the foreground color if it is not already bright.
///
/// Typically applied via the [`bright()`](crate::Painted::bright()) builder
/// method.
///
/// See the [crate level docs](crate#brightening) for details.
Bright,
/// Brighten the background color if it is not already bright.
///
/// Typically applied via the [`on_bright()`](crate::Painted::on_bright())
/// builder
/// method.
///
/// See the [crate level docs](crate#brightening) for details.
OnBright,
}
set_enum! {
Attribute { Bold, Dim, Italic, Underline, Blink, RapidBlink, Invert, Conceal, Strike }
}
set_enum! {
Quirk { Mask, Wrap, Linger, Clear, Resetting, Bright, OnBright }
}
impl Attribute {
pub(crate) fn fmt(&self, f: &mut dyn core::fmt::Write) -> core::fmt::Result {
write!(f, "{}", match self {
Attribute::Bold => 1,
Attribute::Dim => 2,
Attribute::Italic => 3,
Attribute::Underline => 4,
Attribute::Blink => 5,
Attribute::RapidBlink => 6,
Attribute::Invert => 7,
Attribute::Conceal => 8,
Attribute::Strike => 9,
})
}
/// Returns a `Style` with the attribute `self` enabled.
///
/// # Example
///
/// ```rust
/// use yansi::{Style, Attribute::Bold};
///
/// static EMBOLDEN: Style = Bold.style();
/// ```
pub const fn style(self) -> Style {
Style::new().attr(self)
}
}
impl Quirk {
/// Returns a `Style` with the quirk `self` enabled.
///
/// # Example
///
/// ```rust
/// use yansi::{Style, Quirk::Mask};
///
/// static MASKED: Style = Mask.style();
/// ```
pub const fn style(self) -> Style {
Style::new().quirk(self)
}
}
impl From<Attribute> for crate::Style {
fn from(attr: Attribute) -> Self {
attr.style()
}
}
impl From<Quirk> for crate::Style {
fn from(quirk: Quirk) -> Self {
quirk.style()
}
}
+67
View File
@@ -0,0 +1,67 @@
use std::ops::{BitOr, BitOrAssign};
use crate::Style;
impl<T: Into<Set<T>>> BitOr<T> for Set<T> {
type Output = Self;
fn bitor(self, rhs: T) -> Self::Output {
Set(PhantomData, self.1 | rhs.into().1)
}
}
impl<T: Into<Set<T>>> BitOr<Set<T>> for Set<T> {
type Output = Self;
fn bitor(self, rhs: Set<T>) -> Self::Output {
Set(PhantomData, self.1 | rhs.1)
}
}
impl<T: Into<Set<T>>> BitOrAssign<T> for Set<T> {
fn bitor_assign(&mut self, rhs: T) {
self.1 |= rhs.into().1;
}
}
impl BitOr for Emphasis {
type Output = Style;
fn bitor(self, rhs: Self) -> Style {
let attribute = Set::from(self) | Set::from(rhs);
Style { attribute, ..Default::default() }
}
}
impl BitOr<Style> for Emphasis {
type Output = Style;
fn bitor(self, mut rhs: Style) -> Style {
rhs.attribute |= self;
rhs
}
}
impl BitOr<Emphasis> for Style {
type Output = Style;
fn bitor(self, rhs: Emphasis) -> Style {
rhs | self
}
}
impl BitOr<Emphasis> for Color {
type Output = Style;
fn bitor(self, rhs: Emphasis) -> Self::Output {
Style::from(self) | rhs
}
}
impl BitOr<Color> for Emphasis {
type Output = Style;
fn bitor(self, rhs: Color) -> Self::Output {
Style::from(rhs) | self
}
}
+227
View File
@@ -0,0 +1,227 @@
use crate::{Style, Attribute, Quirk, Condition};
/// Enum representing a terminal color.
///
/// **Note:** The color examples below are purely demonstrative. The actual
/// color rendered depends entirely on the terminal and its configuration, the
/// latter of which is entirely arbitrary.
#[derive(Debug, PartialEq, Eq, Copy, Clone, PartialOrd, Ord, Hash)]
pub enum Color {
/// Terminal primary color #9. (foreground code `39`, background code `49`).
///
/// This is the terminal's defined "primary" color, that is, the configured
/// default foreground and background colors. As such, this color as a
/// foreground looks "good" against the terminal's default background color,
/// and this color is a "good" background color for the terminal's default
/// foreground color.
Primary,
/// A color from 0 to 255, for use in 256-color terminals.
Fixed(u8),
/// A 24-bit
/// <span style="background: red; color: white;">R</span>
/// <span style="background: green; color: white;">G</span>
/// <span style="background: blue; color: white;">B</span>
/// "true color", as specified by ISO-8613-3.
Rgb(u8, u8, u8),
/// <span style="background: black; color: white;">Black #0</span>
/// (foreground code `30`, background code `40`).
Black,
/// <span style="background: red; color: white;">Red #1</span>
/// (foreground code `31`, background code `41`).
Red,
/// <span style="background: green; color: white;">Green: #2</span>
/// (foreground code `32`, background code `42`).
Green,
/// <span style="background: gold; color: black;">Yellow: #3</span>
/// (foreground code `33`, background code `43`).
Yellow,
/// <span style="background: blue; color: white;">Blue: #4</span>
/// (foreground code `34`, background code `44`).
Blue,
/// <span style="background: darkmagenta; color: white;">Magenta: #5</span>
/// (foreground code `35`, background code `45`).
Magenta,
/// <span style="background: deepskyblue; color: black;">Cyan: #6</span>
/// (foreground code `36`, background code `46`).
Cyan,
/// <span style="background: #eeeeee; color: black;">White: #7</span>
/// (foreground code `37`, background code `47`).
White,
/// <span style="background: gray; color: white;">Bright Black #0</span>
/// (foreground code `90`, background code `100`).
BrightBlack,
/// <span style="background: hotpink; color: white;">Bright Red #1</span>
/// (foreground code `91`, background code `101`).
BrightRed,
/// <span style="background: greenyellow; color: black;">Bright Green: #2</span>
/// (foreground code `92`, background code `102`).
BrightGreen,
/// <span style="background: yellow; color: black;">Bright Yellow: #3</span>
/// (foreground code `93`, background code `103`).
BrightYellow,
/// <span style="background: dodgerblue; color: white;">Bright Blue: #4</span>
/// (foreground code `94`, background code `104`).
BrightBlue,
/// <span style="background: magenta; color: white;">Bright Magenta: #5</span>
/// (foreground code `95`, background code `105`).
BrightMagenta,
/// <span style='background: cyan; color: black;'>Bright Cyan: #6</span>
/// (foreground code `96`, background code `106`).
BrightCyan,
/// <span style="background: white; color: black;">Bright White: #7</span>
/// (foreground code `97`, background code `107`).
BrightWhite,
}
pub(crate) enum Variant { Fg, Bg, }
impl Color {
fn fg_base(&self) -> u8 {
match self {
Color::Black => 30,
Color::Red => 31,
Color::Green => 32,
Color::Yellow => 33,
Color::Blue => 34,
Color::Magenta => 35,
Color::Cyan => 36,
Color::White => 37,
Color::Fixed(_) | Color::Rgb(..) => 38,
Color::Primary => 39,
Color::BrightBlack => 30 + 60,
Color::BrightRed => 31 + 60,
Color::BrightGreen => 32 + 60,
Color::BrightYellow => 33 + 60,
Color::BrightBlue => 34 + 60,
Color::BrightMagenta => 35 + 60,
Color::BrightCyan => 36 + 60,
Color::BrightWhite => 37 + 60,
}
}
pub(crate) const fn to_bright(self) -> Self {
match self {
Color::Black => Color::BrightBlack,
Color::Red => Color::BrightRed,
Color::Green => Color::BrightGreen,
Color::Yellow => Color::BrightYellow,
Color::Blue => Color::BrightBlue,
Color::Magenta => Color::BrightMagenta,
Color::Cyan => Color::BrightCyan,
Color::White => Color::BrightWhite,
Color::Fixed(_)
| Color::Primary
| Color::Rgb(_, _, _)
| Color::BrightBlack
| Color::BrightRed
| Color::BrightGreen
| Color::BrightYellow
| Color::BrightBlue
| Color::BrightMagenta
| Color::BrightCyan
| Color::BrightWhite => self
}
}
pub(crate) fn fmt(&self, f: &mut dyn core::fmt::Write, variant: Variant) -> core::fmt::Result {
let base = match variant {
Variant::Fg => self.fg_base(),
Variant::Bg => self.fg_base() + 10,
};
match *self {
Color::Fixed(num) => write!(f, "{};5;{}", base, num),
Color::Rgb(r, g, b) => write!(f, "{};2;{};{};{}", base, r, g, b),
_ => write!(f, "{}", base)
}
}
#[inline(always)]
const fn apply(self, a: crate::style::Application) -> Style {
Style::new().fg(self).apply(a)
}
/// Returns a `Style` with a foreground color of `self`.
///
/// # Example
///
/// ```rust
/// use yansi::{Style, Color::*};
///
/// // A style with a foreground color of "yellow".
/// static DEBUG: Style = Yellow.foreground();
///
/// // This is equivalent to the above.
/// static DEBUG_S: Style = Style::new().fg(Yellow);
///
/// // The following two are equivalent. The latter is preferred.
/// static DEBUG_A: Style = Yellow.foreground().bold();
/// static DEBUG_B: Style = Yellow.bold();
/// # use yansi::Paint;
/// # assert_eq!("-".paint(DEBUG_A).to_string(), "-".paint(DEBUG_B).to_string());
/// ```
pub const fn foreground(self) -> Style {
Style::new().fg(self)
}
/// Returns a `Style` with a background color of `self`.
///
/// # Example
///
/// ```rust
/// use yansi::{Style, Color::*};
///
/// // A style with a background color of "yellow".
/// static DEBUG: Style = Yellow.background();
///
/// // This is equivalent to the above.
/// static DEBUG_S: Style = Style::new().bg(Yellow);
///
/// // The following two are equivalent. The latter is preferred.
/// static DEBUG_A: Style = Yellow.background().green();
/// static DEBUG_B: Style = Green.on_yellow();
/// # use yansi::Paint;
/// # assert_eq!("-".paint(DEBUG_A).to_string(), "-".paint(DEBUG_B).to_string());
/// ```
pub const fn background(self) -> Style {
Style::new().bg(self)
}
bg!([pub const] constructor(Self) -> Style);
attr!([pub const] constructor(Self) -> Style);
quirk!([pub const] constructor(Self) -> Style);
whenever!([pub const] constructor(Self) -> Style);
}
impl Default for Color {
fn default() -> Self {
Color::Primary
}
}
impl From<Color> for Style {
fn from(color: Color) -> Self {
color.foreground()
}
}
+356
View File
@@ -0,0 +1,356 @@
use core::fmt;
use core::sync::atomic::AtomicU8;
use core::sync::atomic::{AtomicPtr, Ordering};
/// A function that decides whether styling should be applied.
///
/// A styling `Condition` can be specified globally via
/// [`yansi::whenever()`](crate::whenever()) or locally to a specific style via
/// the [`whenever()`](crate::Style::whenever()) builder method. Any time a
/// [`Painted`](crate::Painted) value is formatted, both the local and global
/// conditions are checked, and only when both evaluate to `true` is styling
/// actually applied.
///
/// A `Condition` is nothing more than a function that returns a `bool`. The
/// function is called each and every time a `Painted` is formatted, and so it
/// is expected to be fast. All of the built-in conditions (except for their
/// "live" variants) cache their first evaluation as a result: the
/// [`Condition::cached()`] constructor can do the same for your conditions.
///
/// # Built-In Conditions
///
/// `yansi` comes with built-in conditions for common scenarios that can be
/// enabled via crate features:
///
/// | feature(s) | condition | implication |
/// |------------------------------|---------------------------------|------------------------|
/// | `detect-tty` | [TTY Detectors] | `std`, [`is-terminal`] |
/// | `detect-env` | [Environment Variable Checkers] | `std` |
/// | [`detect-tty`, `detect-env`] | All Above, [Combo Detectors] | `std`, [`is-terminal`] |
///
/// [`is-terminal`]: https://docs.rs/is-terminal
///
/// For example, to enable the TTY detectors, enable the `detect-tty` feature:
///
/// ```toml
/// yansi = { version = "...", features = ["detect-tty"] }
/// ```
///
/// To enable the TTY detectors, env-var checkers, and combo detectors, enable
/// `detect-tty` _and_ `detect-env`:
///
/// ```toml
/// yansi = { version = "...", features = ["detect-tty", "detect-env"] }
/// ```
///
/// ```rust
/// # #[cfg(all(feature = "detect-tty", feature = "detect-env"))] {
/// use yansi::Condition;
///
/// yansi::whenever(Condition::TTY_AND_COLOR);
/// # }
/// ```
///
/// [TTY detectors]: Condition#impl-Condition-1
/// [Environment Variable Checkers]: Condition#impl-Condition-2
/// [Combo Detectors]: Condition#impl-Condition-3
///
/// # Custom Conditions
///
/// Custom, arbitrary conditions can be created with [`Condition::from()`] or
/// [`Condition::cached()`].
///
/// ```rust
/// # #[cfg(all(feature = "detect-tty", feature = "detect-env"))] {
/// use yansi::{Condition, Style, Color::*};
///
/// // Combine two conditions (`stderr` is a TTY, `CLICOLOR` is set) into one.
/// static STDERR_COLOR: Condition = Condition::from(||
/// Condition::stderr_is_tty() && Condition::clicolor()
/// );
///
/// static DEBUG: Style = Yellow.bold().on_primary().invert().whenever(STDERR_COLOR);
/// # }
/// ```
#[repr(transparent)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Condition(
/// The function that gets called to check the condition.
pub fn() -> bool
);
#[repr(transparent)]
pub struct AtomicCondition(AtomicPtr<()>);
#[allow(unused)]
#[repr(transparent)]
pub struct CachedBool(AtomicU8);
impl Condition {
/// A condition that evaluates to `true` if the OS supports coloring.
///
/// Uses [`Condition::os_support()`]. On Windows, this condition tries to
/// enable coloring support on the first call and caches the result for
/// subsequent calls. Outside of Windows, this always evaluates to `true`.
pub const DEFAULT: Condition = Condition(Condition::os_support);
/// A condition that always evaluates to `true`.
pub const ALWAYS: Condition = Condition(Condition::always);
/// A condition that always evaluated to `false`.
pub const NEVER: Condition = Condition(Condition::never);
/// Creates a dynamically checked condition from a function `f`.
///
/// The function `f` is called anytime the condition is checked, including
/// every time a style with the condition is used.
///
/// # Example
///
/// ```rust,no_run
/// use yansi::Condition;
///
/// fn some_function() -> bool {
/// /* checking arbitrary conditions */
/// todo!()
/// }
///
/// // Create a custom static condition from a function.
/// static MY_CONDITION: Condition = Condition::from(some_function);
///
/// // Create a condition on the stack from a function.
/// let my_condition = Condition::from(some_function);
///
/// // Create a static condition from a closure that becomes a `fn`.
/// static MY_CONDITION_2: Condition = Condition::from(|| false);
///
/// // Create a condition on the stack from a closure that becomes a `fn`.
/// let my_condition = Condition::from(|| some_function());
/// ```
pub const fn from(f: fn() -> bool) -> Self {
Condition(f)
}
/// Creates a condition that is [`ALWAYS`](Self::ALWAYS) when `value` is
/// `true` and [`NEVER`](Self::NEVER) otherwise.
///
/// # Example
///
/// ```rust,no_run
/// use yansi::Condition;
///
/// fn some_function() -> bool {
/// /* checking arbitrary conditions */
/// todo!()
/// }
///
/// // Cache the result of `some_function()` so it doesn't get called each
/// // time the condition needs to be checked.
/// let my_condition = Condition::cached(some_function());
/// ```
pub const fn cached(value: bool) -> Self {
match value {
true => Condition::ALWAYS,
false => Condition::NEVER,
}
}
/// The backing function for [`Condition::ALWAYS`]. Returns `true` always.
pub const fn always() -> bool { true }
/// The backing function for [`Condition::NEVER`]. Returns `false` always.
pub const fn never() -> bool { false }
/// The backing function for [`Condition::DEFAULT`].
///
/// Returns `true` if the current OS supports ANSI escape sequences for
/// coloring. Outside of Windows, this always returns `true`. On Windows,
/// the first call to this function attempts to enable support and returns
/// whether it was successful every time thereafter.
pub fn os_support() -> bool {
crate::windows::cache_enable()
}
}
impl Default for Condition {
fn default() -> Self {
Condition::DEFAULT
}
}
impl core::ops::Deref for Condition {
type Target = fn() -> bool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl AtomicCondition {
pub const DEFAULT: AtomicCondition = AtomicCondition::from(Condition::DEFAULT);
pub const fn from(value: Condition) -> Self {
AtomicCondition(AtomicPtr::new(value.0 as *mut ()))
}
pub fn store(&self, cond: Condition) {
self.0.store(cond.0 as *mut (), Ordering::Release)
}
pub fn read(&self) -> bool {
let condition = unsafe {
Condition(core::mem::transmute(self.0.load(Ordering::Acquire)))
};
condition()
}
}
#[allow(unused)]
impl CachedBool {
const TRUE: u8 = 1;
const UNINIT: u8 = 2;
const INITING: u8 = 3;
pub const fn new() -> Self {
CachedBool(AtomicU8::new(Self::UNINIT))
}
pub fn get_or_init(&self, f: impl FnOnce() -> bool) -> bool {
use core::sync::atomic::Ordering::*;
match self.0.compare_exchange(Self::UNINIT, Self::INITING, AcqRel, Relaxed) {
Ok(_) => {
let new_value = f();
self.0.store(new_value as u8 /* false = 0, true = 1 */, Release);
new_value
}
Err(Self::INITING) => {
let mut value;
while { value = self.0.load(Acquire); value } == Self::INITING {
#[cfg(feature = "std")]
std::thread::yield_now();
}
value == Self::TRUE
},
Err(value) => value == Self::TRUE,
}
}
}
impl fmt::Debug for Condition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if *self == Condition::DEFAULT {
f.write_str("Condition::DEFAULT")
} else if *self == Condition::ALWAYS {
f.write_str("Condition::ALWAYS")
} else if *self == Condition::NEVER {
f.write_str("Condition::NEVER")
} else {
f.debug_tuple("Condition").field(&self.0).finish()
}
}
}
macro_rules! conditions {
($feat:meta $($f:expr, $CACHED:ident: $cached:ident, $LIVE:ident: $live:ident),* $(,)?) => (
#[cfg($feat)]
#[cfg_attr(feature = "_nightly", doc(cfg($feat)))]
/// Feature dependent conditions.
///
/// Available when compiled with
#[doc = concat!('`', stringify!($feat), "`.")]
impl Condition {
$(
/// Evaluates to `true` if
#[doc = concat!('`', stringify!($f), "`.")]
///
/// The result of the first check is cached for subsequent
/// checks. Internally uses
#[doc = concat!("[`", stringify!($cached), "`](Condition::", stringify!($cached), ").")]
pub const $CACHED: Condition = Condition(Condition::$cached);
)*
$(
/// Evaluates to `true` if
#[doc = concat!('`', stringify!($f), "`.")]
///
/// A call is dispatched each time the condition is checked.
/// This is expensive, so prefer to use
#[doc = concat!("[`", stringify!($CACHED), "`](Condition::", stringify!($CACHED), ")")]
/// instead.
///
/// Internally uses
#[doc = concat!("[`", stringify!($live), "`](Condition::", stringify!($live), ").")]
pub const $LIVE: Condition = Condition(Condition::$live);
)*
$(
/// Returns `true` if
#[doc = concat!('`', stringify!($f), "`.")]
///
/// The result of the first check is cached for subsequent
/// checks. This is the backing function for
#[doc = concat!("[`", stringify!($CACHED), "`](Condition::", stringify!($CACHED), ").")]
pub fn $cached() -> bool {
static IS_TTY: CachedBool = CachedBool::new();
IS_TTY.get_or_init(Condition::$live)
}
)*
$(
/// Returns `true` if
#[doc = concat!('`', stringify!($f), "`.")]
///
/// This is the backing function for
#[doc = concat!("[`", stringify!($LIVE), "`](Condition::", stringify!($LIVE), ").")]
pub fn $live() -> bool {
$f
}
)*
}
)
}
#[cfg(feature = "detect-tty")]
use is_terminal::is_terminal as is_tty;
conditions! { feature = "detect-tty"
is_tty(&std::io::stdout()),
STDOUT_IS_TTY: stdout_is_tty,
STDOUT_IS_TTY_LIVE: stdout_is_tty_live,
is_tty(&std::io::stderr()),
STDERR_IS_TTY: stderr_is_tty,
STDERR_IS_TTY_LIVE: stderr_is_tty_live,
is_tty(&std::io::stdin()),
STDIN_IS_TTY: stdin_is_tty,
STDIN_IS_TTY_LIVE: stdin_is_tty_live,
is_tty(&std::io::stdout()) && is_tty(&std::io::stderr()),
STDOUTERR_ARE_TTY: stdouterr_are_tty,
STDOUTERR_ARE_TTY_LIVE: stdouterr_are_tty_live,
}
#[cfg(feature = "detect-env")]
pub fn env_set_or(name: &str, default: bool) -> bool {
std::env::var_os(name).map_or(default, |v| v != "0")
}
conditions! { feature = "detect-env"
env_set_or("CLICOLOR_FORCE", false) || env_set_or("CLICOLOR", true),
CLICOLOR: clicolor,
CLICOLOR_LIVE: clicolor_live,
!env_set_or("NO_COLOR", false),
YES_COLOR: no_color,
YES_COLOR_LIVE: no_color_live,
}
conditions! { all(feature = "detect-env", feature = "detect-tty")
Condition::stdouterr_are_tty() && Condition::clicolor() && Condition::no_color(),
TTY_AND_COLOR: tty_and_color,
TTY_AND_COLOR_LIVE: tty_and_color_live,
}
+110
View File
@@ -0,0 +1,110 @@
use crate::condition::{AtomicCondition, Condition};
static ENABLED: AtomicCondition = AtomicCondition::DEFAULT;
/// Unconditionally disables styling globally.
///
/// # Example
///
/// ```rust
/// use yansi::Paint;
///
/// // With styling enabled, ANSI color codes are emitted, thus `ne`.
/// assert_ne!("go".green().to_string(), "go".to_string());
///
/// // With styling disabled, ANSI color codes are _not_ emitted.
/// yansi::disable();
/// assert_eq!("go".green().to_string(), "go".to_string());
/// ```
pub fn disable() {
ENABLED.store(Condition::NEVER);
}
/// Unconditionally enables styling globally.
///
/// By default, styling is enabled based on [`Condition::DEFAULT`], which checks
/// for operating system support.
///
/// # Example
///
/// ```rust
/// use yansi::Paint;
///
/// // With styling disabled, ANSI color codes are _not_ emitted.
/// yansi::disable();
/// assert_eq!("go".green().to_string(), "go".to_string());
///
/// // Reenabling causes color code to be emitted.
/// yansi::enable();
/// assert_ne!("go".green().to_string(), "go".to_string());
/// ```
pub fn enable() {
ENABLED.store(Condition::ALWAYS);
}
/// Dynamically enables and disables styling globally based on `condition`.
///
/// `condition` is expected to be fast: it is checked dynamically, each time a
/// [`Painted`](crate::Painted) value is displayed.
///
/// # Example
///
/// ```rust
/// # #[cfg(all(feature = "detect-tty", feature = "detect-env"))] {
/// use yansi::Condition;
///
/// yansi::whenever(Condition::STDOUT_IS_TTY);
///
/// // On each styling, check if we have TTYs.
/// yansi::whenever(Condition::STDOUTERR_ARE_TTY_LIVE);
///
/// // Check `NO_COLOR`, `CLICOLOR`, and if we have TTYs.
/// const HAVE_COLOR: Condition = Condition(|| {
/// std::env::var_os("NO_COLOR").is_none()
/// && (Condition::CLICOLOR_LIVE)()
/// && Condition::stdouterr_are_tty_live()
/// });
///
/// // This will call `HAVE_COLOR` every time styling is needed. In this
/// // example, this means that env vars will be checked on each styling.
/// yansi::whenever(HAVE_COLOR);
///
/// // This instead caches the value (checking `env()` exactly once, now).
/// yansi::whenever(Condition::cached((HAVE_COLOR)()));
///
/// // Is identical to this:
/// match (HAVE_COLOR)() {
/// true => yansi::enable(),
/// false => yansi::disable(),
/// }
/// # }
/// ```
pub fn whenever(condition: Condition) {
ENABLED.store(condition);
}
/// Returns `true` if styling is globally enabled and `false` otherwise.
///
/// By default, styling is enabled based on [`Condition::DEFAULT`], which checks
/// for operating system support. It can be enabled and disabled on-the-fly with
/// [`enable()`] and [`disable()`] and via a dynamic condition with
/// [`whenever()`].
///
/// # Example
///
/// ```rust
/// // Styling is enabled by default.
/// # yansi::enable();
/// assert!(yansi::is_enabled());
///
/// // Disable it with `Painted::disable()`.
/// yansi::disable();
/// assert!(!yansi::is_enabled());
///
/// // Reenable with `Painted::enable()`.
/// yansi::enable();
/// assert!(yansi::is_enabled());
/// ```
pub fn is_enabled() -> bool {
ENABLED.read()
}
+138
View File
@@ -0,0 +1,138 @@
//! Experimental support for hyperlinking.
//!
//! # Usage
//!
//! Enable the `hyperlink` crate feature. Enabling `hyperlink` implicitly
//! enables `std`.
//!
//! Import the `HyperlinkExt` extension trait and use the [`link()`] builder
//! method.
//!
//! [`link()`]: HyperlinkExt::link()
//!
//! ```rust
//! use yansi::Paint;
//! use yansi::hyperlink::HyperlinkExt;
//!
//! println!("Go to {}.", "our docs".link("https://docs.rs/yansi").green());
//! ```
//!
//! `>` Go to <a href="https://docs.rs/yansi"><span style="color: green;">our docs</span></a>.
//!
//! The `link()` method returns a [`PaintedLink`] structure which implements all
//! of the unverisal chainable methods available across the library.
//! Furthermore, [`Painted`] is extended with a [`link()`](Painted::link())
//! method. The net effect is that you can use `link()` as if it were any other
//! styling method:
//!
//! ```rust
//! use yansi::Paint;
//! use yansi::hyperlink::HyperlinkExt;
//!
//! println!("Go to {}.", "our docs".green().link("https://docs.rs/yansi").on_black().invert());
//! ```
//!
//! `>` Go to <a href="https://docs.rs/yansi">
//! <span style="background: green; color: black;">our docs</span>
//! </a>.
//!
//! # Caveats
//!
//! 1. You can only create a link when there is a target value to print, that
//! is, when the receiver is something "printable". In other words, you
//! _cannot_ apply `link()` to a bare `Style`. This means the following will
//! not work:
//!
//! ```rust,compile_fail
//! use yansi::{Paint, Style, Color::*};
//! use yansi::hyperlink::HyperlinkExt;
//!
//! static LINKED: Style = Green.link("https://docs.rs/yansi");
//! ```
//! <br/>
//!
//! 2. While some modern terminals support hyperlinking, many do not. Those that
//! do not _should_ gracefully ignore the target URL and print the original
//! value. That is, instead of `>` <a href="https://docs.rs/yansi">our
//! docs</a>, such terminals would print `>` our docs.
use core::fmt;
use crate::*;
/// A [`Painted`] with an associated target URL to hyperlink.
pub struct PaintedLink<T> {
painted: Painted<T>,
link: String,
}
/// Extension trait to apply hyperlinks to any value, implemented for all types.
///
/// See the [module level docs](hyperlink) for usage details.
pub trait HyperlinkExt {
/// Create a painted hyperlink with a target URL of `url`.
///
/// See [`hyperlink`] for details.
///
/// # Example
///
/// ```rust
/// use yansi::hyperlink::HyperlinkExt;
///
/// println!("See {}.", "our docs".link("https://docs.rs/yansi"));
/// ```
fn link(&self, url: impl ToString) -> PaintedLink<&Self>;
}
impl<T> PaintedLink<T> {
fn fmt_args(
&self,
fmt: &dyn Fn(&Painted<T>, &mut fmt::Formatter) -> fmt::Result,
f: &mut fmt::Formatter,
_args: fmt::Arguments<'_>,
) -> fmt::Result {
if !self.painted.enabled() {
return fmt(&self.painted, f);
}
write!(f, "\x1B]8;;{}\x1B\\", self.link)?;
fmt(&self.painted, f)?;
write!(f, "\x1B]8;;\x1B\\")
}
}
impl_fmt_traits!(<T> PaintedLink<T> => self.painted (Painted<T>));
impl<T> HyperlinkExt for T {
fn link(&self, url: impl ToString) -> PaintedLink<&Self> {
PaintedLink { painted: Painted::new(self), link: url.to_string() }
}
}
/// Experimental support for hyperlinking.
impl<T> Painted<T> {
/// Create a painted hyperlink with a target URL of `url`.
///
/// See [`hyperlink`] for details.
///
/// # Example
///
/// ```rust
/// use yansi::Paint;
/// use yansi::hyperlink::HyperlinkExt;
///
/// println!("See {}.", "our docs".green().link("https://docs.rs/yansi"));
/// ```
pub fn link(&self, url: impl ToString) -> PaintedLink<&Self> {
PaintedLink { painted: Painted::new(self), link: url.to_string() }
}
}
impl<T> PaintedLink<T> {
#[inline(always)]
const fn apply(mut self, a: crate::style::Application) -> Self {
self.painted.style = self.painted.style.apply(a);
self
}
properties!([pub const] constructor(Self) -> Self);
}
+373
View File
@@ -0,0 +1,373 @@
//! A dead simple ANSI terminal color painting library.
//!
//! # Features
//!
//! Why *y*et another *ANSI* terminal coloring library? Here are some reasons:
//!
//! * This library makes simple things _simple_: `use` [`Paint`] and go!
//! * Zero dependencies by default. It really is simple.
//! * Zero allocations except as needed by opt-in [wrapping](#wrapping).
//! * [Automatic Windows support] for the vast majority (95%+) of Windows
//! users.
//! * [Featureful `no_std`], no-`alloc`, support with `default-features =
//! false`.
//! * [`Style` constructors are `const`]: store styles statically, even with
//! dynamic conditions!
//! * _Any_ type implementing a formatting trait can be styled, not just
//! strings.
//! * Styling can be [enabled] and [disabled] globally and [dynamically], on
//! the fly.
//! * A `Style` can be predicated on arbitrary [conditions](#per-style).
//! * Formatting specifiers like `{:x}` and `{:08b}` are supported and
//! preserved!
//! * [Built-in (optional) conditions] for [TTY detection] and [common
//! environment variables].
//! * Arbitrary items can be [_masked_] for selective disabling.
//! * Styling can [_wrap_] to preserve styling across resets.
//! * Styling can [_linger_] beyond a single value.
//! * Experimental support for [hyperlinking] is included.
//! * The name `yansi` is pretty cool 😎.
//!
//! All that said, `yansi` borrows API ideas from older libraries as well as
//! implementation details from [`ansi_term`].
//!
//! [`ansi_term`]: https://crates.io/crates/ansi_term
//! [`colored`]: https://crates.io/crates/colored
//! [`term_painter`]: https://crates.io/crates/term-painter
//! [_masked_]: #masking
//! [_wrap_]: #wrapping
//! [_linger_]: #lingering
//! [enabled]: crate::enable
//! [disabled]: crate::disable
//! [dynamically]: crate::whenever
//! [enabled conditionally]: Condition
//! [TTY detection]: Condition#impl-Condition-1
//! [common environment variables]: Condition#impl-Condition-2
//! [Automatic Windows support]: #windows
//! [Built-in (optional) conditions]: Condition#built-in-conditions
//! [`Style` constructors are `const`]: #uniform-const-builders
//! [hyperlinking]: hyperlink
//! [Featureful `no_std`]: #crate-features
//!
//! # Usage
//!
//! The [`Paint`] trait is implemented for every type. Import it and call
//! chainable builder methods:
//!
//! ```rust
//! use yansi::Paint;
//!
//! println!("Testing, {}, {}, {}!",
//! "Ready".bold(),
//! "Set".yellow().italic(),
//! "STOP".white().on_red().bright().underline().bold());
//! ```
//!
//! `>` Testing,
//! <b>Ready</b>,
//! <span style="color: yellow;"><i><b>Set</b></i></span>,
//! <span style="color: white; background: red;"><u><b>STOP</b></u></span>!
//!
//! The methods return a [`Painted`] type which consists of a [`Style`] and a
//! reference to the receiver. Displaying a [`Painted`] (via `print!()`,
//! `format!()`, etc) results in emitting ANSI escape codes that effectuate the
//! style.
//!
//! ## Uniform `const` Builders
//!
//! All builder methods are uniformly available for [`Style`], [`Color`], and
//! [`Painted`], which means you can chain calls across library types. All
//! methods are `const`, allowing creations of `const` or `static` [`Style`]s. A
//! `Style` can be directly applied to values with [`.paint()`](Paint::paint()),
//! from [`Paint::paint()`], available for every type:
//!
//! ```rust
//! use yansi::{Paint, Style, Color::*};
//!
//! // `const` constructors allow static `Style`s for easy reuse
//! static ALERT: Style = White.bright().underline().italic().on_red();
//!
//! println!("Testing, {}, {}, {}!",
//! "Ready".bold(),
//! "Set".yellow().bold(),
//! "STOP".paint(ALERT));
//! ```
//!
//! `>` Testing,
//! <b>Ready</b>,
//! <span style="color: yellow;"><b>Set</b></span>,
//! <span style="color: white; background: red;"><u><em>STOP</em></u></span>!
//!
//! ## Conditional Styling
//!
//! ### Globally
//!
//! Styling is enabled by default but can be enabled and disabled globally via
//! [`enable()`] and [`disable()`]. When styling is disabled, no ANSI escape
//! codes are emitted, and [_masked_] values are omitted entirely.
//!
//! Global styling can also be dynamically enabled and disabled using
//! [`whenever()`] with an arbitrary [`Condition`]: a function that returns
//! `true` or `false`. This condition is evaluated each time a [`Painted`] item
//! is displayed. The associated styling is enabled, and mask values emitted,
//! exactly when and only when the condition returns `true`.
//!
//! ### Per-`Style`
//!
//! A specific `Style` can itself be conditionally applied by using
//! [`.whenever()`](Style::whenever()):
//!
//! ```rust
//! # #[cfg(feature = "detect-tty")] {
//! use yansi::{Paint, Style, Color::*, Condition};
//!
//! static WARNING: Style = Black.bold().on_yellow().whenever(Condition::STDERR_IS_TTY);
//!
//! eprintln!("{}", "Bees can sting!".paint(WARNING));
//! # }
//! ```
//!
//! With the above, if `stderr` is a TTY, then:
//! `>` <span style="background: yellow; color: black;"><b>Bees can sting!</b></span>
//!
//! If it is not a TTY, styling is not emitted:
//! `>` Bees can sting!
//!
//! See [`Condition`] for a list of built-in conditions which require enabling
//! crate features.
//!
//! # Quirks
//!
//! As a convenience, `yansi` implements several "quirks", applicable via
//! [`Quirk`] and the respective methods, that modify if and how styling is
//! presented to the terminal. These quirks do not correspond to any ANSI
//! styling sequences.
//!
//! ## Masking
//!
//! Items can be arbitrarily _masked_ with the [`mask()`](Paint::mask()) builder
//! method. Masked values are not emitted when styling is disabled, globally or
//! for a given style. This allows selective output based on whether styling is
//! enabled.
//!
//! One use for this feature is to print certain characters only when styling is
//! enabled. For instance, you might wish to emit the 🎨 emoji when coloring is
//! enabled but not otherwise. This can be accomplished by masking the emoji:
//!
//! ```rust
//! use yansi::Paint;
//!
//! println!("I like colors!{}", " 🎨".mask());
//! ```
//!
//! When styling is enabled, this prints: `>` I like colors! 🎨
//!
//! With styling disabled, this prints: `>` I like colors!
//!
//! ## Wrapping
//!
//! **Note:** _Either the `std` or `alloc` feature is required for wrapping.
//! `std` is enabled by default. See [crate features](#crate-features)._
//!
//! Styling can _wrap_ via [`Quirk::Wrap`] or the equivalent
//! [`wrap()`](Painted::wrap()) constructor. A wrapping style modifies any
//! styling resets emitted by the internal value so that they correspond to the
//! wrapping style. In other words, the "reset" style of the wrapped item is
//! modified to be the style being `.wrap()`d.
//!
//! Wrapping is useful in situations where opaque and arbitrary values must be
//! styled consistently irrespective of any existing styling. For example, a
//! generic logger might want to style messages based on log levels
//! consistently, even when those messages may already include styling. Wrapping
//! exists to enable such consistent styling:
//!
//! ```rust
//! use yansi::Paint;
//!
//! // Imagine that `inner` is opaque and we don't know it's styling.
//! let inner = format!("{} and {}", "Stop".red(), "Go".green());
//!
//! // We can use `wrap` to ensure anything in `inner` not styled is blue.
//! println!("Hey! {}", inner.blue().wrap());
//! ```
//!
//! Thanks to wrapping, this prints:
//! `>` Hey! <span style="color: blue">
//! <span style="color: red">Stop</span> and
//! <span style="color: green">Go</span>
//! </span>
//!
//! Without wrapping, the reset after `"Stop".red()` would not be overwritten:
//! `>` Hey! <span style="color: red">Stop</span> and <span style="color: green">Go</span>
//!
//! Wrapping incurs a performance cost due to an extra allocation and
//! replacement if the wrapped item has styling applied to it. Otherwise, it
//! does not allocate nor incur a meaningful performance cost.
//!
//! ## Lingering
//!
//! Styling can _linger_ beyond a single value via [`Quirk::Linger`] or the
//! equivalent [`linger()`](Painted::linger()) constructor. A lingering style
//! does not reset itself after being applied. In other words, the style lingers
//! on beyond the value it's applied to, until something else resets the
//! respective styling.
//!
//! The complement to lingering is force resetting via [`Quirk::Resetting`] or
//! the equivalent [`resetting()`](Painted::resetting()) constructor. Force
//! resetting, as the name implies, forces a reset suffix to be emitted after
//! the value, irrespective of any lingering applied. It can be used as a way to
//! finalize a lingering style.
//!
//! Lingering itself is useful in situations where a given style is to be
//! repeated across multiple values, or when style is intended to persist even
//! across values that are not styled with `yansi`. It also allows avoiding
//! unnecessarily repeated ANSI code sequences. The examples below illustrate
//! some scenarios in which lingering is useful:
//!
//! ```rust
//! use yansi::Paint;
//!
//! println!("Hello! {} {} things with {} {}?",
//! "How".magenta().underline().linger(),
//! "are".italic().linger(),
//! "you".on_yellow(), // doesn't linger, so all styling is reset here
//! "today".blue());
//! ```
//!
//! `>` Hello!
//! <span style="color: magenta;">
//! <u>How <i>are things with <span style="background: yellow;">you</span></i></u>
//! </span>
//! <span style="color: blue;">today</span>?
//!
//! ```rust
//! use yansi::Paint;
//!
//! println!("Hello! {} {} things with {} {}?",
//! "How".magenta().underline().linger(),
//! "are".italic(), // doesn't linger, so all styling is reset here
//! "you".on_yellow().linger(),
//! "today".blue()); // doesn't linger; styling is reset
//! ```
//!
//! `>` Hello!
//! <span style="color: magenta;">
//! <u>How <i>are</i></u>
//! </span>
//! things with
//! <span style="background: yellow;">
//! you
//! <span style="color: blue;">today</span></span>?
//!
//! ```rust
//! use yansi::Paint;
//!
//! println!("{} B {} {} {} F",
//! "A".red().linger(),
//! "C".underline().linger(),
//! "D", // doesn't linger, but no styling applied, thus no reset
//! "E".resetting()); // explicitly reset
//! ```
//!
//! `>` <span style="color: red;"> A B <u>C D E</u> </span> F
//!
//! ## Brightening
//!
//! Most pimrary colors are available in regular and _bright_ variants, e.g.,
//! [`Color::Red`] and [`Color::BrightRed`]. The [`Quirk::Bright`] and
//! [`Quirk::OnBright`] quirks, typically applied via
//! [`.bright()`](Painted::bright()) and [`.on_bright()`](Painted::on_bright()),
//! provide an alternative, convenient mechanism to select the bright variant of
//! the selected foreground or background color, respectively. The quirk
//! provides no additional colors and is equivalent to selecting the bright
//! variants directly.
//!
//! ```rust
//! use yansi::Paint;
//!
//! // These are all equivalent.
//! print!("{}", "Regular".red());
//! print!("{}", "Bright".bright_red());
//! print!("{}", "Bright".bright().red());
//! print!("{}", "Bright".red().bright());
//!
//! # static STYLE: yansi::Style = yansi::Color::Green.bold();
//! // The `bright` quirk lets use choose the bright variants of _any_ color,
//! // even when the color or style is unknown at the call site.
//! print!("{}", "Normal".paint(STYLE));
//! print!("{}", "Bright".paint(STYLE).bright());
//! ```
//!
//! `>` <span style="color: red;">Regular</span>
//! <span style="color: hotpink;">Bright</span>
//! <span style="color: hotpink;">Bright</span>
//! <span style="color: hotpink;">Bright</span>
//! <span style="color: green;"><b>Normal</b></span>
//! <span style="color: greenyellow;"><b>Bright</b></span>
//!
//! The `bright()` quirk can be applied before or after a color is selected
//! while having the same effect.
//!
//! # Windows
//!
//! Styling is supported and enabled automatically on Windows beginning with
//! the Windows 10 Anniversary Update, or about [96% of all Windows machines
//! worldwide](https://gs.statcounter.com/os-version-market-share/windows/desktop/worldwide),
//! and likely closer to 100% of developer machines (e.g., 99% of visitors to
//! [rocket.rs](https://rocket.rs) on Windows are on Windows 10+).
//!
//! Yansi enables styling support on Windows by querying the Windows API on the
//! first attempt to color. If support is available, it is enabled. If support
//! is not available, styling is disabled and no styling sequences are emitted.
//!
//! # Crate Features
//!
//! | Feature | Default? | Also Enables | Notes |
//! |--------------|----------|--------------|----------------------------------|
//! | `std` | **Y** | `alloc` | Use `std` library. |
//! | `alloc` | **Y** | | Use `alloc`. Enables [wrapping]. |
//! | `detect-tty` | N | `std` | See [optional conditions]. |
//! | `detect-env` | N | `std` | See [optional conditions]. |
//! | `hyperlink` | N | `std` | Enables [hyperlinking] support. |
//!
//! With `default-features = false`, this crate is `#[no_std]`.
//!
//! Without any features enabled, all functionality except [wrapping] is
//! available. To recover wrapping _with_ `#[no_std]`, set `default-features =
//! false` and enable the `alloc` feature, which requires `alloc` support.
//!
//! [optional conditions]: Condition#built-in-conditions
//! [wrapping]: #wrapping
#![doc(html_logo_url = "https://raw.githubusercontent.com/SergioBenitez/yansi/master/.github/yansi-logo.png")]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "_nightly", feature(doc_cfg))]
#![deny(missing_docs)]
// FIXME: Remove once `clear()` and `Quirk::Clear` are removed.
#![allow(useless_deprecated, deprecated)]
#[cfg(all(not(feature = "std"), feature = "alloc"))]
extern crate alloc;
#[macro_use]
mod macros;
mod windows;
mod attr_quirk;
mod style;
mod color;
mod paint;
mod global;
mod condition;
mod set;
#[cfg(feature = "hyperlink")]
#[cfg_attr(feature = "_nightly", doc(cfg(feature = "hyperlink")))]
pub mod hyperlink;
pub use paint::{Painted, Paint};
pub use attr_quirk::{Attribute, Quirk};
pub use style::Style;
pub use color::Color;
pub use condition::Condition;
pub use global::{enable, whenever, disable, is_enabled};
+376
View File
@@ -0,0 +1,376 @@
macro_rules! set_enum {
($T:ident { $($v:ident),+ $(,)? }) => {
impl $T {
pub(crate) const fn bit_mask(self) -> u16 {
1 << self as u16
}
pub(crate) const fn from_bit_mask(value: u16) -> Option<Self> {
$(if (value == $T::$v.bit_mask()) { return Some($T::$v); })+
None
}
}
impl crate::set::Set<$T> {
#[must_use]
pub const fn insert(mut self, value: $T) -> Self {
self.1 |= value.bit_mask();
self
}
}
impl crate::set::SetMember for $T {
const MAX_VALUE: u8 = { $($T::$v as u8);+ };
fn bit_mask(self) -> u16 { <$T>::bit_mask(self) }
fn from_bit_mask(v: u16) -> Option<Self> { <$T>::from_bit_mask(v) }
}
};
}
macro_rules! constructor {
(
[$($q:tt)*] $r:ty, $R:ty, $p:ident,
$(#[$pattr:meta])* $prop:ident => $V:path $([$($a:ident : $T:ty),+])?
) => {
/// Returns `self` with the
#[doc = concat!("[`", stringify!($p), "()`](Self::", stringify!($p), "())")]
/// set to
#[doc = concat!("[`", stringify!($V), "`].")]
///
/// # Example
///
/// ```rust
#[doc = concat!(
"# let value = yansi::Painted::new(0);",
$($("\n# let ", stringify!($a), " = 0;"),+)?
)]
#[doc = concat!(
"println!(\"{}\", value.", stringify!($prop), "(", $(stringify!($($a),+),)? "));"
)]
/// ```
#[inline]
$(#[$pattr])*
$($q)* fn $prop(self: $r $($(,$a: $T)+)?) -> $R {
let v = $V $(($($a),*))?;
self.apply(crate::style::Application::$p(v))
}
};
([$($q:tt)*] $(#[$attr:meta])* $r:ty, $R:ty, $kind:ident ($A:ty)) => {
$(#[$attr])*
#[inline]
$($q)* fn $kind(self: $r, value: $A) -> $R {
self.apply(crate::style::Application::$kind(value))
}
};
}
macro_rules! signature {
(
[$($q:tt)*] $r:ty, $R:ty, $p:ident,
$(#[$pattr:meta])* $prop:ident => $V:path $([$($a:ident : $T:ty),+])?
) => {
/// Returns `self` with the
#[doc = concat!("[`", stringify!($p), "()`](Self::", stringify!($p), "())")]
/// set to
#[doc = concat!("[`", stringify!($V), "`].")]
///
/// # Example
///
/// ```rust
#[doc = concat!(
"# let value = yansi::Painted::new(0);",
$($("\n# let ", stringify!($a), " = 0;"),+)?
)]
#[doc = concat!(
"println!(\"{}\", value.", stringify!($prop), "(", $(stringify!($($a),+),)? "));"
)]
/// ```
$(#[$pattr])*
$($q)* fn $prop(self: $r $($(,$a: $T)+)?) -> $R;
};
([$($q:tt)*] $(#[$attr:meta])* $r:ty, $R:ty, $kind:ident ($A:ty)) => {
$(#[$attr])*
$($q)* fn $kind(self: $r, value: $A) -> $R;
};
}
macro_rules! define_property {
([$d:tt] $(#[$attr:meta])* $kind:ident ($A:ty) {
$($(#[$pattr:meta])* $prop:ident => $V:path $([$($a:tt)*])?),* $(,)?
}) => {
macro_rules! $kind {
($d ([$d ($qual:tt)*])? $cont:ident ($r:ty) -> $R:ty) => (
$cont!([$d ($d ($qual)*)?] $(#[$attr])* $r, $R, $kind($A));
$(
$cont!(
[$d ($d ($qual)*)?]
$r, $R, $kind, $(#[$pattr])* $prop => $V $([$($a)*] )?
);
)*
)
}
};
($(#[$attr:meta])* $kind:ident ($A:ty)) => {
define_property!([$] $(#[$attr])* $kind ($A) {});
};
($($t:tt)*) => { define_property!([$] $($t)*); }
}
// Check that every variant of a property is covered.
macro_rules! check_property_exhaustiveness {
($A:ident $({ $($(#[$pattr:meta])* $p:ident => $V:path $([ $($a:tt)* ])?),* $(,)? })? ) => {
const _: () = {$(
use crate::*;
fn _check() {
#[allow(unreachable_code)]
match { let _v: $A = todo!(); _v } {
$($V { .. } => { },)*
}
}
)?};
}
}
macro_rules! define_properties {
($($(#[$attr:meta])* $kind:ident ($A:ident) $({ $($t:tt)* })?),* $(,)?) => {
$(define_property!($(#[$attr])* $kind($A) $({ $($t)* })?);)*
$(check_property_exhaustiveness!($A $({ $($t)* })?);)*
}
}
macro_rules! properties {
($([$($qual:tt)*])? $cont:ident ($r:ty) -> $R:ty) => (
fg!($([$($qual)*])? $cont ($r) -> $R);
bg!($([$($qual)*])? $cont ($r) -> $R);
attr!($([$($qual)*])? $cont ($r) -> $R);
quirk!($([$($qual)*])? $cont ($r) -> $R);
whenever!($([$($qual)*])? $cont ($r) -> $R);
)
}
define_properties! {
/// Returns a styled value derived from `self` with the foreground set to
/// `value`.
///
/// This method should be used rarely. Instead, prefer to use color-specific
/// builder methods like [`red()`](Self::red()) and
/// [`green()`](Self::green()), which have the same functionality but are
/// pithier.
///
/// # Example
///
/// Set foreground color to white using `fg()`:
///
/// ```rust
/// use yansi::{Paint, Color};
///
/// # let painted = ();
/// painted.fg(Color::White);
/// ```
///
/// Set foreground color to white using [`white()`](Self::white()).
///
/// ```rust
/// use yansi::Paint;
///
/// # let painted = ();
/// painted.white();
/// ```
fg(Color) {
primary => Color::Primary,
fixed => Color::Fixed[color: u8],
rgb => Color::Rgb[r: u8, g: u8, b: u8],
black => Color::Black,
red => Color::Red,
green => Color::Green,
yellow => Color::Yellow,
blue => Color::Blue,
magenta => Color::Magenta,
cyan => Color::Cyan,
white => Color::White,
bright_black => Color::BrightBlack,
bright_red => Color::BrightRed,
bright_green => Color::BrightGreen,
bright_yellow => Color::BrightYellow,
bright_blue => Color::BrightBlue,
bright_magenta => Color::BrightMagenta,
bright_cyan => Color::BrightCyan,
bright_white => Color::BrightWhite,
},
/// Returns a styled value derived from `self` with the background set to
/// `value`.
///
/// This method should be used rarely. Instead, prefer to use color-specific
/// builder methods like [`on_red()`](Self::on_red()) and
/// [`on_green()`](Self::on_green()), which have the same functionality but
/// are pithier.
///
/// # Example
///
/// Set background color to red using `fg()`:
///
/// ```rust
/// use yansi::{Paint, Color};
///
/// # let painted = ();
/// painted.bg(Color::Red);
/// ```
///
/// Set background color to red using [`on_red()`](Self::on_red()).
///
/// ```rust
/// use yansi::Paint;
///
/// # let painted = ();
/// painted.on_red();
/// ```
bg(Color) {
on_primary => Color::Primary,
on_fixed => Color::Fixed[color: u8],
on_rgb => Color::Rgb[r: u8, g: u8, b: u8],
on_black => Color::Black,
on_red => Color::Red,
on_green => Color::Green,
on_yellow => Color::Yellow,
on_blue => Color::Blue,
on_magenta => Color::Magenta,
on_cyan => Color::Cyan,
on_white => Color::White,
on_bright_black => Color::BrightBlack,
on_bright_red => Color::BrightRed,
on_bright_green => Color::BrightGreen,
on_bright_yellow => Color::BrightYellow,
on_bright_blue => Color::BrightBlue,
on_bright_magenta => Color::BrightMagenta,
on_bright_cyan => Color::BrightCyan,
on_bright_white => Color::BrightWhite,
},
/// Enables the styling [`Attribute`] `value`.
///
/// This method should be used rarely. Instead, prefer to use
/// attribute-specific builder methods like [`bold()`](Self::bold()) and
/// [`underline()`](Self::underline()), which have the same functionality
/// but are pithier.
///
/// # Example
///
/// Make text bold using `attr()`:
///
/// ```rust
/// use yansi::{Paint, Attribute};
///
/// # let painted = ();
/// painted.attr(Attribute::Bold);
/// ```
///
/// Make text bold using using [`bold()`](Self::bold()).
///
/// ```rust
/// use yansi::Paint;
///
/// # let painted = ();
/// painted.bold();
/// ```
attr(Attribute) {
bold => Attribute::Bold,
dim => Attribute::Dim,
italic => Attribute::Italic,
underline => Attribute::Underline,
blink => Attribute::Blink,
rapid_blink => Attribute::RapidBlink,
invert => Attribute::Invert,
conceal => Attribute::Conceal,
strike => Attribute::Strike,
},
/// Enables the `yansi` [`Quirk`] `value`.
///
/// This method should be used rarely. Instead, prefer to use quirk-specific
/// builder methods like [`mask()`](Self::mask()) and
/// [`wrap()`](Self::wrap()), which have the same functionality but are
/// pithier.
///
/// # Example
///
/// Enable wrapping using `.quirk()`:
///
/// ```rust
/// use yansi::{Paint, Quirk};
///
/// # let painted = ();
/// painted.quirk(Quirk::Wrap);
/// ```
///
/// Enable wrapping using [`wrap()`](Self::wrap()).
///
/// ```rust
/// use yansi::Paint;
///
/// # let painted = ();
/// painted.wrap();
/// ```
quirk(Quirk) {
mask => Quirk::Mask,
wrap => Quirk::Wrap,
linger => Quirk::Linger,
#[deprecated(
since = "1.0.1",
note = "renamed to `resetting()` due to conflicts with `Vec::clear()`.\n\
The `clear()` method will be removed in a future release."
)]
clear => Quirk::Clear,
resetting => Quirk::Resetting,
bright => Quirk::Bright,
on_bright => Quirk::OnBright,
},
/// Conditionally enable styling based on whether the [`Condition`] `value`
/// applies. Replaces any previous condition.
///
/// See the [crate level docs](crate#per-style) for more details.
///
/// # Example
///
/// Enable styling `painted` only when both `stdout` and `stderr` are TTYs:
///
/// ```rust
/// # #[cfg(feature = "detect-tty")] {
/// use yansi::{Paint, Condition};
///
/// # let painted = ();
/// painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);
/// # }
/// ```
whenever(Condition),
}
macro_rules! impl_fmt_trait {
($F:path, $f:literal <$G:ident> $T:ty => $s:ident.$v:ident ($V:ty)) => {
impl<$G: $F> $F for $T {
fn fmt(&$s, f: &mut core::fmt::Formatter) -> core::fmt::Result {
$s.fmt_args(&<$V>::fmt, f, format_args!($f, $s.$v))
}
}
};
}
macro_rules! impl_fmt_traits {
($($t:tt)*) => {
impl_fmt_trait!(core::fmt::Display, "{}" $($t)*);
impl_fmt_trait!(core::fmt::Debug, "{:?}" $($t)*);
impl_fmt_trait!(core::fmt::Octal, "{:o}" $($t)*);
impl_fmt_trait!(core::fmt::LowerHex, "{:x}" $($t)*);
impl_fmt_trait!(core::fmt::UpperHex, "{:X}" $($t)*);
impl_fmt_trait!(core::fmt::Pointer, "{:p}" $($t)*);
impl_fmt_trait!(core::fmt::Binary, "{:b}" $($t)*);
impl_fmt_trait!(core::fmt::LowerExp, "{:e}" $($t)*);
impl_fmt_trait!(core::fmt::UpperExp, "{:E}" $($t)*);
};
}
+270
View File
@@ -0,0 +1,270 @@
use core::fmt;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::{string::{String, ToString}, borrow::Cow};
#[cfg(feature = "std")]
use std::borrow::Cow;
use crate::{Color, Attribute, Quirk, Style, Condition};
/// An arbitrary value with a [`Style`] applied to it.
///
/// A `Painted` can be directly formatted. This results in the internal
/// [`value`](Self::value) being formatted as specified and ANSI code styling
/// sequences corresponding to [`style`](Self::style) being prefixed and
/// suffixed as necessary. Both the global and local [`Condition`] affects
/// whether styling sequences are actually emitted: both must evaluated to true.
/// Otherwise, no styling sequences are emitted.
///
/// ```rust
/// use yansi::{Paint, Condition};
///
/// println!("Hello, {}!", "world".red().underline().blink());
/// // > Hello, world! # world is red, underlined, and blinking
///
/// let v = format!("{}", "world".red().underline().blink());
/// assert_eq!(v, "\u{1b}[4;5;31mworld\u{1b}[0m");
/// println!("{}", v); // > world # world is red, underlined, and blinking
///
/// let v = format!("{}", "world".red().underline().blink().whenever(Condition::NEVER));
/// assert_eq!(v, "world");
/// ```
#[derive(Copy, Clone)]
pub struct Painted<T> {
/// The value to be styled.
pub value: T,
/// The style to apply.
pub style: Style,
}
/// A trait to apply styling to any value. Implemented for all types.
///
/// Because this trait is implemented for all types, you can use its methods on
/// any type. With the exception of one constructor method, [`Paint::new()`],
/// all methods are called with method syntax:
///
/// ```rust
/// use yansi::Paint;
///
/// "hello".green(); // calls `Paint::<&'static str>::green()`.
/// "hello".strike(); // calls `Paint::<&'static str>::strike()`.
/// 1.on_red(); // calls `Paint::<i32>::red()`.
/// 1.blink(); // calls `Paint::<i32>::blink()`.
/// ```
///
/// ### Chaining
///
/// All methods return a [`Painted`] whose methods are exactly those of `Paint`.
/// This means you can chain `Paint` method calls:
///
/// ```rust
/// use yansi::Paint;
///
/// "hello".green().strike(); // calls `Paint::green()` then `Painted::strike()`.
/// 1.on_red().blink(); // calls `Paint::red()` + `Painted::blink()`.
/// ```
///
/// ### Borrow vs. Owned Receiver
///
/// The returned [`Painted`] type contains a borrow to the receiver:
///
/// ```rust
/// use yansi::{Paint, Painted};
///
/// let v: Painted<&i32> = 1.red();
/// ```
///
/// This is nearly always what you want. In the exceedingly rare case that you
/// _do_ want `Painted` to own its value, use [`Paint::new()`] or the equivalent
/// [`Painted::new()`]:
///
/// ```rust
/// use yansi::{Paint, Painted};
///
/// let v: Painted<i32> = Paint::new(1);
/// let v: Painted<i32> = Painted::new(1);
/// ```
///
/// ### Further Details
///
/// See the [crate level docs](crate#usage) for more details and examples.
pub trait Paint {
/// Create a new [`Painted`] with a default [`Style`].
///
/// # Example
///
/// ```rust
/// use yansi::Paint;
///
/// let painted = Paint::new("hello");
/// assert_eq!(painted.style, yansi::Style::new());
/// ```
#[inline(always)]
fn new(self) -> Painted<Self> where Self: Sized {
Painted::new(self)
}
#[doc(hidden)]
#[inline(always)]
fn apply(&self, a: crate::style::Application) -> Painted<&Self> {
Painted::new(self).apply(a)
}
/// Apply a style wholesale to `self`. Any previous style is replaced.
///
/// # Example
///
/// ```rust
/// use yansi::{Paint, Style, Color::*};
///
/// static DEBUG: Style = Black.bold().on_yellow();
///
/// let painted = "hello".paint(DEBUG);
/// ```
#[inline(always)]
fn paint<S: Into<Style>>(&self, style: S) -> Painted<&Self> {
Painted { value: self, style: style.into() }
}
properties!(signature(&Self) -> Painted<&Self>);
}
#[allow(rustdoc::broken_intra_doc_links)]
impl<T: ?Sized> Paint for T {
properties!(constructor(&Self) -> Painted<&Self>);
}
impl<T> Painted<T> {
/// Create a new [`Painted`] with a default [`Style`].
///
/// # Example
///
/// ```rust
/// use yansi::Painted;
///
/// let painted = Painted::new("hello");
/// assert_eq!(painted.style, yansi::Style::new());
/// ```
#[inline(always)]
pub const fn new(value: T) -> Painted<T> {
Painted { value, style: Style::new() }
}
#[inline(always)]
const fn apply(mut self, a: crate::style::Application) -> Self {
self.style = self.style.apply(a);
self
}
#[inline]
pub(crate) fn enabled(&self) -> bool {
crate::is_enabled() && self.style.condition.map_or(true, |c| c())
}
properties!([pub const] constructor(Self) -> Self);
}
impl<T> Painted<T> {
pub(crate) fn color_fmt_value(
&self,
fmt: &dyn Fn(&T, &mut fmt::Formatter) -> fmt::Result,
f: &mut fmt::Formatter,
) -> fmt::Result {
self.style.fmt_prefix(f)?;
fmt(&self.value, f)?;
self.style.fmt_suffix(f)
}
#[cfg(feature = "alloc")]
pub(crate) fn reset_fmt_args(
&self,
fmt: &dyn Fn(&T, &mut fmt::Formatter) -> fmt::Result,
f: &mut fmt::Formatter,
args: &fmt::Arguments<'_>,
) -> fmt::Result {
// A tiny state machine to find escape sequences.
enum State { Searching, Open, }
let mut state = State::Searching;
let escape = |c: char| {
match state {
State::Searching if c == '\x1B' => { state = State::Open; true }
State::Open if c == 'm' => { state = State::Searching; true }
State::Searching => false,
State::Open => true,
}
};
// Only replace when the string contains styling.
let string = args.as_str()
.map(|string| Cow::Borrowed(string))
.unwrap_or_else(|| Cow::Owned(args.to_string()));
if string.contains('\x1B') {
f.write_str(&string.replace(escape, ""))
} else {
fmt(&self.value, f)
}
}
#[cfg(feature = "alloc")]
pub(crate) fn color_wrap_fmt_args(
&self,
fmt: &dyn Fn(&T, &mut fmt::Formatter) -> fmt::Result,
f: &mut fmt::Formatter,
args: &fmt::Arguments<'_>,
) -> fmt::Result {
// Only replace when the string contains styling.
let string = args.as_str()
.map(|string| Cow::Borrowed(string))
.unwrap_or_else(|| Cow::Owned(args.to_string()));
if !string.contains('\x1B') {
return self.color_fmt_value(fmt, f);
}
// Compute the prefix for the style with a reset in front.
let mut prefix = String::new();
prefix.push_str("\x1B[0m");
self.style.fmt_prefix(&mut prefix)?;
// Write out formatted string, replacing resets with computed prefix.
self.style.fmt_prefix(f)?;
write!(f, "{}", string.replace("\x1B[0m", &prefix))?;
self.style.fmt_suffix(f)
}
pub(crate) fn fmt_args(
&self,
fmt: &dyn Fn(&T, &mut fmt::Formatter) -> fmt::Result,
f: &mut fmt::Formatter,
_args: fmt::Arguments<'_>,
) -> fmt::Result {
let enabled = self.enabled();
let masked = self.style.quirks.contains(Quirk::Mask);
#[cfg(not(feature = "alloc"))]
match (enabled, masked) {
(true, _) => self.color_fmt_value(fmt, f),
(false, false) => fmt(&self.value, f),
(false, true) => Ok(()),
}
#[cfg(feature = "alloc")]
match (enabled, masked, self.style.quirks.contains(Quirk::Wrap)) {
(true, _, true) => self.color_wrap_fmt_args(fmt, f, &_args),
(true, _, false) => self.color_fmt_value(fmt, f),
(false, false, true) => self.reset_fmt_args(fmt, f, &_args),
(false, false, false) => fmt(&self.value, f),
(false, true, _) => Ok(()),
}
}
}
impl_fmt_traits!(<T> Painted<T> => self.value (T));
impl<T> From<Painted<T>> for Style {
fn from(painted: Painted<T>) -> Self {
painted.style
}
}
+93
View File
@@ -0,0 +1,93 @@
use core::fmt;
use core::marker::PhantomData;
pub struct Set<T>(PhantomData<T>, pub(crate) u16);
pub trait SetMember: Copy + fmt::Debug {
const MAX_VALUE: u8;
fn bit_mask(self) -> u16;
fn from_bit_mask(value: u16) -> Option<Self>;
}
impl<T: SetMember> Set<T> {
pub const EMPTY: Self = Set(PhantomData, 0);
pub fn contains(self, value: T) -> bool {
(value.bit_mask() & self.1) == value.bit_mask()
}
pub const fn iter(self) -> Iter<T> {
Iter { index: 0, set: self }
}
}
pub struct Iter<T> {
index: u8,
set: Set<T>,
}
impl<T: SetMember> Iterator for Iter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
while self.index <= T::MAX_VALUE {
let mask: u16 = 1 << self.index;
self.index += 1;
if let Some(v) = T::from_bit_mask(mask) {
if self.set.contains(v) {
return Some(v);
}
}
}
None
}
}
impl<T: SetMember> Default for Set<T> {
fn default() -> Self {
Set::EMPTY
}
}
impl<T: SetMember> fmt::Debug for Set<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
impl<T> Copy for Set<T> { }
impl<T> Clone for Set<T> {
fn clone(&self) -> Self {
Self(self.0, self.1)
}
}
impl<T> PartialEq for Set<T> {
fn eq(&self, other: &Self) -> bool {
self.1 == other.1
}
}
impl<T> Eq for Set<T> { }
impl<T> PartialOrd for Set<T> {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
self.1.partial_cmp(&other.1)
}
}
impl<T> Ord for Set<T> {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.1.cmp(&other.1)
}
}
impl<T> core::hash::Hash for Set<T> {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.1.hash(state);
}
}
+390
View File
@@ -0,0 +1,390 @@
use core::fmt::{self, Write};
use crate::color::{Color, Variant};
use crate::attr_quirk::{Attribute, Quirk};
use crate::condition::Condition;
use crate::set::Set;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::{string::String, borrow::Cow};
#[cfg(feature = "std")]
use std::borrow::Cow;
/// A set of styling options.
///
/// ## Equivalence and Ordering
///
/// Only a style's `foreground`, `background`, and set of `attributes` are
/// considered when testing for equivalence or producing an ordering via
/// `PartialEq` or `Eq`, and `PartialOrd` or `Ord`. A style's quirks and
/// conditions are ignored.
#[derive(Default, Debug, Copy, Clone)]
pub struct Style {
/// The foreground color. Defaults to `None`.
///
/// ```rust
/// use yansi::{Style, Color};
///
/// assert_eq!(Style::new().foreground, None);
/// assert_eq!(Style::new().green().foreground, Some(Color::Green));
/// ```
pub foreground: Option<Color>,
/// The background color. Defaults to `None`.
///
/// ```rust
/// use yansi::{Style, Color};
///
/// assert_eq!(Style::new().background, None);
/// assert_eq!(Style::new().on_red().background, Some(Color::Red));
/// ```
pub background: Option<Color>,
pub(crate) attributes: Set<Attribute>,
pub(crate) quirks: Set<Quirk>,
/// The condition.
///
/// To check a style's condition directly, use [`Style::enabled()`]:
///
/// ```rust
/// use yansi::{Style, Condition};
///
/// let style = Style::new().whenever(Condition::ALWAYS);
/// assert!(style.enabled());
///
/// let style = Style::new().whenever(Condition::NEVER);
/// assert!(!style.enabled());
/// ```
pub condition: Option<Condition>,
}
struct AnsiSplicer<'a> {
f: &'a mut dyn fmt::Write,
splice: bool,
}
#[derive(Debug)]
#[allow(non_camel_case_types)]
pub enum Application {
fg(Color),
bg(Color),
attr(Attribute),
quirk(Quirk),
whenever(Condition),
}
impl Style {
const DEFAULT: Style = Style {
foreground: None,
background: None,
attributes: Set::EMPTY,
quirks: Set::EMPTY,
condition: None,
};
/// Returns a new style with no foreground or background, no attributes
/// or quirks, and [`Condition::DEFAULT`].
///
/// This is the default returned by [`Default::default()`].
///
/// # Example
///
/// ```rust
/// use yansi::Style;
///
/// assert_eq!(Style::new(), Style::default());
/// ```
#[inline]
pub const fn new() -> Style {
Style::DEFAULT
}
#[inline(always)]
pub(crate) const fn apply(mut self, a: Application) -> Style {
match a {
Application::fg(color) => self.foreground = Some(color),
Application::bg(color) => self.background = Some(color),
Application::whenever(cond) => self.condition = Some(cond),
Application::attr(attr) => self.attributes = self.attributes.insert(attr),
Application::quirk(quirk) => self.quirks = self.quirks.insert(quirk),
}
self
}
/// Returns `true` if this style is enabled, based on
/// [`condition`](Paint.condition).
///
/// **Note:** _For a style to be effected, both this method **and**
/// [`yansi::is_enabled()`](crate::is_enabled) must return `true`._
///
/// When there is no condition set, this method always returns `true`. When
/// a condition has been set, this evaluates the condition and returns the
/// result.
///
/// # Example
///
/// ```rust
/// use yansi::{Style, Condition};
///
/// let style = Style::new().whenever(Condition::ALWAYS);
/// assert!(style.enabled());
///
/// let style = Style::new().whenever(Condition::NEVER);
/// assert!(!style.enabled());
/// ```
pub fn enabled(&self) -> bool {
self.condition.map_or(true, |c| c())
}
/// Writes the ANSI code prefix for the currently set styles.
///
/// This method is intended to be used inside of [`fmt::Display`] and
/// [`fmt::Debug`] implementations for custom or specialized use-cases. Most
/// users should use [`Painted`] for all painting needs.
///
/// This method writes the ANSI code prefix irrespective of whether painting
/// is currently enabled or disabled. To write the prefix only if painting
/// is enabled, condition a call to this method on [`is_enabled()`].
///
/// [`fmt::Display`]: fmt::Display
/// [`fmt::Debug`]: fmt::Debug
/// [`Painted`]: crate::Painted
/// [`is_enabled()`]: crate::is_enabled()
///
/// # Example
///
/// ```rust
/// use core::fmt;
/// use yansi::Style;
///
/// struct CustomItem {
/// item: u32,
/// style: Style
/// }
///
/// impl fmt::Display for CustomItem {
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// self.style.fmt_prefix(f)?;
/// write!(f, "number: {}", self.item)?;
/// self.style.fmt_suffix(f)
/// }
/// }
/// ```
pub fn fmt_prefix(&self, f: &mut dyn fmt::Write) -> fmt::Result {
// Give a sequence-free string when no styles are applied.
if self == &Style::DEFAULT {
return Ok(());
}
let brighten = |color: Option<Color>, bright: bool| match (color, bright) {
(Some(color), true) => Some(color.to_bright()),
_ => color
};
let mut f = AnsiSplicer { f, splice: false };
f.write_str("\x1B[")?;
for attr in self.attributes.iter() {
f.splice()?;
attr.fmt(&mut f)?;
}
if let Some(color) = brighten(self.background, self.quirks.contains(Quirk::OnBright)) {
f.splice()?;
color.fmt(&mut f, Variant::Bg)?;
}
if let Some(color) = brighten(self.foreground, self.quirks.contains(Quirk::Bright)) {
f.splice()?;
color.fmt(&mut f, Variant::Fg)?;
}
// All of the sequences end with an `m`.
f.write_char('m')
}
/// Returns the ANSI code sequence prefix for the style as a string.
///
/// This returns a string with the exact same sequence written by
/// [`fmt_prefix()`](Self::fmt_prefix()). See that method for details.
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "_nightly", doc(cfg(feature = "alloc")))]
pub fn prefix(&self) -> Cow<'static, str> {
let mut prefix = String::new();
let _ = self.fmt_prefix(&mut prefix);
prefix.into()
}
/// Writes the ANSI code sequence suffix for the style.
///
/// This method is intended to be used inside of [`fmt::Display`] and
/// [`fmt::Debug`] implementations for custom or specialized use-cases. Most
/// users should use [`Painted`] for all painting needs.
///
/// This method writes the ANSI code suffix irrespective of whether painting
/// is currently enabled or disabled. To write the suffix only if painting
/// is enabled, condition a call to this method on [`is_enabled()`].
///
/// [`fmt::Display`]: fmt::Display
/// [`fmt::Debug`]: fmt::Debug
/// [`Painted`]: crate::Painted
/// [`is_enabled()`]: crate::is_enabled()
///
/// # Example
///
/// ```rust
/// use core::fmt;
/// use yansi::Style;
///
/// struct CustomItem {
/// item: u32,
/// style: Style
/// }
///
/// impl fmt::Display for CustomItem {
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// self.style.fmt_prefix(f)?;
/// write!(f, "number: {}", self.item)?;
/// self.style.fmt_suffix(f)
/// }
/// }
/// ```
pub fn fmt_suffix(&self, f: &mut dyn fmt::Write) -> fmt::Result {
if !self.quirks.contains(Quirk::Resetting) && !self.quirks.contains(Quirk::Clear) {
if self.quirks.contains(Quirk::Linger) || self == &Style::DEFAULT {
return Ok(());
}
}
f.write_str("\x1B[0m")
}
/// Returns the ANSI code sequence suffix for the style as a string.
///
/// This returns a string with the exact same sequence written by
/// [`fmt_suffix()`](Self::fmt_suffix()). See that method for details.
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "_nightly", doc(cfg(feature = "alloc")))]
pub fn suffix(&self) -> Cow<'static, str> {
if !self.quirks.contains(Quirk::Resetting) && !self.quirks.contains(Quirk::Clear) {
if self.quirks.contains(Quirk::Linger) || self == &Style::DEFAULT {
return Cow::from("");
}
}
Cow::from("\x1B[0m")
}
properties!([pub const] constructor(Self) -> Self);
}
impl AnsiSplicer<'_> {
fn splice(&mut self) -> fmt::Result {
if self.splice { self.f.write_char(';')?; }
self.splice = true;
Ok(())
}
}
impl fmt::Write for AnsiSplicer<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.f.write_str(s)
}
}
impl PartialEq for Style {
fn eq(&self, other: &Self) -> bool {
let Style {
foreground: fg_a,
background: bg_a,
attributes: attrs_a,
quirks: _,
condition: _,
} = self;
let Style {
foreground: fg_b,
background: bg_b,
attributes: attrs_b,
quirks: _,
condition: _,
} = other;
fg_a == fg_b && bg_a == bg_b && attrs_a == attrs_b
}
}
impl Eq for Style { }
impl core::hash::Hash for Style {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
let Style { foreground, background, attributes, quirks: _, condition: _, } = self;
foreground.hash(state);
background.hash(state);
attributes.hash(state);
}
}
impl PartialOrd for Style {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
let Style {
foreground: fg_a,
background: bg_a,
attributes: attrs_a,
quirks: _,
condition: _,
} = self;
let Style {
foreground: fg_b,
background: bg_b,
attributes: attrs_b,
quirks: _,
condition: _,
} = other;
match fg_a.partial_cmp(&fg_b) {
Some(core::cmp::Ordering::Equal) => {}
ord => return ord,
}
match bg_a.partial_cmp(&bg_b) {
Some(core::cmp::Ordering::Equal) => {}
ord => return ord,
}
attrs_a.partial_cmp(&attrs_b)
}
}
impl Ord for Style {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
let Style {
foreground: fg_a,
background: bg_a,
attributes: attrs_a,
quirks: _,
condition: _,
} = self;
let Style {
foreground: fg_b,
background: bg_b,
attributes: attrs_b,
quirks: _,
condition: _,
} = other;
match fg_a.cmp(&fg_b) {
core::cmp::Ordering::Equal => {}
ord => return ord,
}
match bg_a.cmp(&bg_b) {
core::cmp::Ordering::Equal => {}
ord => return ord,
}
attrs_a.cmp(&attrs_b)
}
}
+121
View File
@@ -0,0 +1,121 @@
#[cfg(windows)]
#[allow(non_camel_case_types, non_snake_case)]
mod windows_console {
use core::ffi::c_void;
type c_ulong = u32;
type c_int = i32;
type wchar_t = u16;
type DWORD = c_ulong;
type LPDWORD = *mut DWORD;
type HANDLE = *mut c_void;
type BOOL = c_int;
type LPCWSTR = *const WCHAR;
type WCHAR = wchar_t;
type LPSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES;
type LPVOID = *mut c_void;
#[repr(C)]
pub struct SECURITY_ATTRIBUTES {
pub nLength: DWORD,
pub lpSecurityDescriptor: LPVOID,
pub bInheritHandle: BOOL,
}
const ENABLE_VIRTUAL_TERMINAL_PROCESSING: DWORD = 0x0004;
const INVALID_HANDLE_VALUE: HANDLE = -1isize as HANDLE;
const FALSE: BOOL = 0;
const TRUE: BOOL = 1;
const GENERIC_READ: DWORD = 0x80000000;
const GENERIC_WRITE: DWORD = 0x40000000;
const FILE_SHARE_READ: DWORD = 0x00000001;
const FILE_SHARE_WRITE: DWORD = 0x00000002;
const OPEN_EXISTING: DWORD = 3;
// This is the win32 console API, taken from the 'winapi' crate.
extern "system" {
fn CreateFileW(
lpFileName: LPCWSTR,
dwDesiredAccess: DWORD,
dwShareMode: DWORD,
lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
dwCreationDisposition: DWORD,
dwFlagsAndAttributes: DWORD,
hTemplateFile: HANDLE
) -> HANDLE;
fn GetLastError() -> DWORD;
fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
fn SetConsoleMode(hConsoleHandle: HANDLE, dwMode: DWORD) -> BOOL;
}
fn get_output_handle() -> Result<HANDLE, DWORD> {
// This is "CONOUT$\0" UTF-16 encoded.
const CONOUT: &[u16] = &[0x43, 0x4F, 0x4E, 0x4F, 0x55, 0x54, 0x24, 0x00];
let raw_handle = unsafe {
CreateFileW(
CONOUT.as_ptr(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
core::ptr::null_mut(),
OPEN_EXISTING,
0,
core::ptr::null_mut(),
)
};
if raw_handle == INVALID_HANDLE_VALUE {
return Err(6);
}
Ok(raw_handle)
}
unsafe fn enable_vt(handle: HANDLE) -> Result<(), DWORD> {
let mut dw_mode: DWORD = 0;
if GetConsoleMode(handle, &mut dw_mode) == FALSE {
return Err(GetLastError());
}
dw_mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
match SetConsoleMode(handle, dw_mode) {
result if result == TRUE => Ok(()),
_ => Err(GetLastError())
}
}
unsafe fn enable_ansi_colors_raw() -> Result<bool, DWORD> {
enable_vt(get_output_handle()?)?;
Ok(true)
}
#[inline(always)]
pub fn enable() -> bool {
unsafe { enable_ansi_colors_raw().unwrap_or(false) }
}
// Try to enable colors on Windows, and try to do it at most once.
pub fn cache_enable() -> bool {
use crate::condition::CachedBool;
static ENABLED: CachedBool = CachedBool::new();
ENABLED.get_or_init(enable)
}
}
#[cfg(not(windows))]
mod windows_console {
#[inline(always)]
#[allow(dead_code)]
pub fn enable() -> bool { true }
#[inline(always)]
pub fn cache_enable() -> bool { true }
}
// pub use self::windows_console::enable;
pub use self::windows_console::cache_enable;
+239
View File
@@ -0,0 +1,239 @@
use yansi::{Paint, Style, Condition, Color::*};
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
macro_rules! assert_renders {
($($input:expr => $expected:expr,)*) => {
let _lock = LOCK.lock().expect("FAIL FAST - LOCK POISONED");
yansi::enable();
$(
let (input, expected) = ($input.to_string(), $expected.to_string());
if input != expected {
panic!("\nexpected: {:?} {}\nactual: {:?} {}\n\
global, condition = {}, {}\n\
input = {}\nstyle = {:#?}\n",
expected, expected, input, input,
yansi::is_enabled(), $input.style.enabled(),
stringify!($input), $input.style);
}
)*
yansi::whenever(Condition::DEFAULT);
};
}
macro_rules! assert_disabled_renders {
($($input:expr => $expected:expr,)*) => {
let _lock = LOCK.lock().expect("FAIL FAST - LOCK POISONED");
$(
yansi::disable();
let (actual, expected) = ($input.to_string(), $expected.to_string());
yansi::enable();
assert_eq!(actual, expected);
let local = $input.whenever(yansi::Condition::NEVER);
let (actual, expected) = (local.to_string(), $expected.to_string());
assert_eq!(actual, expected);
)*
};
}
#[test]
fn colors_enabled() {
assert_renders! {
Paint::new("text/plain") => "text/plain",
Paint::red("hi") => "\x1B[31mhi\x1B[0m",
Paint::black("hi") => "\x1B[30mhi\x1B[0m",
Paint::yellow("hi").bold() => "\x1B[1;33mhi\x1B[0m",
Paint::new("hi").fg(Yellow).bold() => "\x1B[1;33mhi\x1B[0m",
Paint::blue("hi").underline() => "\x1B[4;34mhi\x1B[0m",
Paint::green("hi").bold().underline() => "\x1B[1;4;32mhi\x1B[0m",
Paint::green("hi").underline().bold() => "\x1B[1;4;32mhi\x1B[0m",
Paint::magenta("hi").bg(White) => "\x1B[47;35mhi\x1B[0m",
Paint::red("hi").bg(Blue).fg(Yellow) => "\x1B[44;33mhi\x1B[0m",
Paint::cyan("hi").bg(Blue).fg(Yellow) => "\x1B[44;33mhi\x1B[0m",
Paint::cyan("hi").bold().bg(White) => "\x1B[1;47;36mhi\x1B[0m",
Paint::cyan("hi").underline().bg(White) => "\x1B[4;47;36mhi\x1B[0m",
Paint::cyan("hi").bold().underline().bg(White) => "\x1B[1;4;47;36mhi\x1B[0m",
Paint::cyan("hi").underline().bold().bg(White) => "\x1B[1;4;47;36mhi\x1B[0m",
Paint::new("hi").fixed(100) => "\x1B[38;5;100mhi\x1B[0m",
Paint::new("hi").fixed(100).bg(Magenta) => "\x1B[45;38;5;100mhi\x1B[0m",
Paint::new("hi").fixed(100).bg(Fixed(200)) => "\x1B[48;5;200;38;5;100mhi\x1B[0m",
Paint::new("hi").rgb(70, 130, 180) => "\x1B[38;2;70;130;180mhi\x1B[0m",
Paint::new("hi").rgb(70, 130, 180).bg(Blue) => "\x1B[44;38;2;70;130;180mhi\x1B[0m",
Paint::blue("hi").bg(Rgb(70, 130, 180)) => "\x1B[48;2;70;130;180;34mhi\x1B[0m",
Paint::new("hi").rgb(70, 130, 180).bg(Rgb(5,10,15)) =>
"\x1B[48;2;5;10;15;38;2;70;130;180mhi\x1B[0m",
Paint::new("hi").bold() => "\x1B[1mhi\x1B[0m",
Paint::new("hi").underline() => "\x1B[4mhi\x1B[0m",
Paint::new("hi").bold().underline() => "\x1B[1;4mhi\x1B[0m",
Paint::new("hi").dim() => "\x1B[2mhi\x1B[0m",
Paint::new("hi").italic() => "\x1B[3mhi\x1B[0m",
Paint::new("hi").blink() => "\x1B[5mhi\x1B[0m",
Paint::new("hi").invert() => "\x1B[7mhi\x1B[0m",
Paint::new("hi").conceal() => "\x1B[8mhi\x1B[0m",
Paint::new("hi").strike() => "\x1B[9mhi\x1B[0m",
}
}
#[test]
fn colors_disabled() {
assert_disabled_renders! {
Paint::new("text/plain") => "text/plain",
Paint::red("hi") => "hi",
Paint::black("hi") => "hi",
Paint::yellow("hi").bold() => "hi",
Paint::new("hi").fg(Yellow).bold() => "hi",
Paint::blue("hi").underline() => "hi",
Paint::green("hi").bold().underline() => "hi",
Paint::green("hi").underline().bold() => "hi",
Paint::magenta("hi").bg(White) => "hi",
Paint::red("hi").bg(Blue).fg(Yellow) => "hi",
Paint::cyan("hi").bg(Blue).fg(Yellow) => "hi",
Paint::cyan("hi").bold().bg(White) => "hi",
Paint::cyan("hi").underline().bg(White) => "hi",
Paint::cyan("hi").bold().underline().bg(White) => "hi",
Paint::cyan("hi").underline().bold().bg(White) => "hi",
Paint::new("hi").fixed(100) => "hi",
Paint::new("hi").fixed(100).bg(Magenta) => "hi",
Paint::new("hi").fixed(100).bg(Fixed(200)) => "hi",
Paint::new("hi").rgb(70, 130, 180) => "hi",
Paint::new("hi").rgb(70, 130, 180).bg(Blue) => "hi",
Paint::blue("hi").bg(Rgb(70, 130, 180)) => "hi",
Paint::blue("hi").bg(Rgb(70, 130, 180)).wrap() => "hi",
Paint::new("hi").rgb(70, 130, 180).bg(Rgb(5,10,15)) => "hi",
Paint::new("hi").bold() => "hi",
Paint::new("hi").underline() => "hi",
Paint::new("hi").bold().underline() => "hi",
Paint::new("hi").dim() => "hi",
Paint::new("hi").italic() => "hi",
Paint::new("hi").blink() => "hi",
Paint::new("hi").invert() => "hi",
Paint::new("hi").conceal() => "hi",
Paint::new("hi").strike() => "hi",
Paint::new("hi").strike().wrap() => "hi",
}
}
#[test]
fn masked_when_disabled() {
assert_disabled_renders! {
Paint::mask("text/plain") => "",
Paint::mask("text/plain").mask() => "",
Paint::new("text/plain").mask() => "",
Paint::new("text/plain").mask() => "",
Paint::red("hi").mask() => "",
Paint::black("hi").mask() => "",
Paint::yellow("hi").bold().mask() => "",
Paint::cyan("hi").bg(Blue).fg(Yellow).mask() => "",
Paint::cyan("hi").underline().bold().bg(White).mask() => "",
}
}
#[test]
fn masked_when_enabled() {
assert_renders! {
Paint::mask("text/plain") => "text/plain",
Paint::mask("text/plain").mask() => "text/plain",
Paint::black("hi").mask() => "\x1B[30mhi\x1B[0m",
Paint::yellow("hi").bold().mask() => "\x1B[1;33mhi\x1B[0m",
Paint::new("hi").fg(Yellow).bold().mask() => "\x1B[1;33mhi\x1B[0m",
Paint::cyan("hi").underline().bg(White).mask() => "\x1B[4;47;36mhi\x1B[0m",
Paint::cyan("hi").bold().underline().bg(White).mask() => "\x1B[1;4;47;36mhi\x1B[0m",
Paint::new("hi").rgb(70, 130, 180).mask() => "\x1B[38;2;70;130;180mhi\x1B[0m",
Paint::new("hi").underline().mask() => "\x1B[4mhi\x1B[0m",
Paint::new("hi").bold().underline().mask() => "\x1B[1;4mhi\x1B[0m",
Paint::new("hi").conceal().mask() => "\x1B[8mhi\x1B[0m",
}
}
#[test]
#[cfg(feature = "alloc")]
fn wrapping() {
let inner = || format!("{} b {}", Paint::red("a"), Paint::green("c"));
let inner2 = || format!("0 {} 1", Paint::magenta(&inner()).wrap());
assert_renders! {
Paint::new("text/plain").wrap() => "text/plain",
Paint::new(&inner()).wrap() => &inner(),
Paint::new(&inner()).wrap() =>
"\u{1b}[31ma\u{1b}[0m b \u{1b}[32mc\u{1b}[0m",
Paint::new(&inner()).fg(Blue).wrap() =>
"\u{1b}[34m\u{1b}[31ma\u{1b}[0m\u{1b}[34m b \
\u{1b}[32mc\u{1b}[0m\u{1b}[34m\u{1b}[0m",
Paint::new(&inner2()).wrap() => &inner2(),
Paint::new(&inner2()).wrap() =>
"0 \u{1b}[35m\u{1b}[31ma\u{1b}[0m\u{1b}[35m b \
\u{1b}[32mc\u{1b}[0m\u{1b}[35m\u{1b}[0m 1",
Paint::new(&inner2()).fg(Blue).wrap() =>
"\u{1b}[34m0 \u{1b}[35m\u{1b}[31ma\u{1b}[0m\u{1b}[34m\u{1b}[35m b \
\u{1b}[32mc\u{1b}[0m\u{1b}[34m\u{1b}[35m\u{1b}[0m\u{1b}[34m 1\u{1b}[0m",
}
}
#[test]
fn lingering() {
let _lock = LOCK.lock().expect("FAIL FAST - LOCK POISONED");
yansi::enable();
assert_eq! {
format!("Hello! {} {} things with {} {}?",
"How".magenta().underline().linger(),
"are".italic(),
"you".on_yellow().linger(),
"today".blue()),
"Hello! \u{1b}[4;35mHow \u{1b}[3mare\u{1b}[0m things with \
\u{1b}[43myou \u{1b}[34mtoday\u{1b}[0m?",
};
assert_eq! {
format!("Hi! {} {} things with {} {}?",
"How".magenta().underline().linger(),
"are".italic().linger(),
"you".on_yellow().linger(),
"today".blue()),
"Hi! \u{1b}[4;35mHow \u{1b}[3mare things with \u{1b}[43myou \
\u{1b}[34mtoday\u{1b}[0m?"
};
assert_eq! {
format!("{} B {} {} {} F",
"A".red().linger(),
"C".underline().linger(),
"D", // doesn't linger, but no styling applied, thus no reset
"E".resetting()), // explicitly reset
"\u{1b}[31mA B \u{1b}[4mC D E\u{1b}[0m F"
};
assert_eq! {
format!("{} B {} {} {} F",
"A".red().linger(),
"C".underline().linger(),
"D", // doesn't linger, but no styling applied, thus no reset
"E".clear()), // explicitly reset
"\u{1b}[31mA B \u{1b}[4mC D E\u{1b}[0m F"
};
yansi::whenever(Condition::DEFAULT);
}
#[test]
fn hash_eq() {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
fn hash<T: Hash>(t: &T) -> u64 {
let mut s = DefaultHasher::new();
t.hash(&mut s);
s.finish()
}
let a = Style::default();
let b = Style::default().mask();
let c = Style::new();
assert_eq!(a, b);
assert_eq!(b, c);
assert_eq!(hash(&a), hash(&b));
assert_eq!(hash(&a), hash(&c));
}