build(ariadne): vendor clap
This commit was merged in pull request #30.
This commit is contained in:
1 parent
e6af135702
commit
8855b6d379
681 files changed
+400416
No files matched your search
@@ -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":"a2fa18e6cba8bb38b8c8c8d8dabffd050ffe3abaa9812d8a7a625011abab3e05","Cargo.lock":"290fd05071687876767eba6f3ecf6ddc67dc7c90a2c381b331462805eba4da70","Cargo.toml":"43f306d58209afac8fd535b305716d668fa334e2c27195c1dc6e46eab88bccfc","Cargo.toml.orig":"9a4b126ab4b8f69b202ba2ef1eb72d2dc8f4fbafe64876ae9b678f5b57b0fb18","LICENSE-APACHE":"c6596eb7be8581c18be736c846fb9173b69eccf6ef94c5135893ec56bd92ba08","LICENSE-MIT":"6efb0476a1cc085077ed49357026d8c173bf33017278ef440f222fb9cbcb66e6","README.md":"7e90b134ad15dc4368d2a27efeb8db9d155dcd0886b72a032ffb367616255807","examples/dump-stream.rs":"6dbd8fca846ac8addd43ae941fa1220a7c31862896ac2ae4971afe792480523d","examples/query-stream.rs":"3796dec1ffe79cc49d088086eb27214764e8e0cff0370d60150aeecdadd47d30","src/_macros.rs":"04590ef86f86bb67fb11580ab101caffde4d36da84652537da20424b72c8729a","src/adapter/mod.rs":"baf4237ea0b18df63609e49d93572ca27c2202a4cbec0220adb5a7e815c7d8ed","src/adapter/strip.rs":"642375f9dc5836eb5aa6eba7be849a84786d22764d470672bf1f646061254c1c","src/adapter/wincon.rs":"88607742fb7bbfb85e122a8dcc3188ef7c15ef332063af3a8939701dad05b90a","src/auto.rs":"73b39540ac20e609ecbd32aff057a0cb1ec806374360b87e611ff83579b5582c","src/buffer.rs":"597cc2a109a49f0a48888c7d882058d0ec4b771da34348d4da384ba056c6ea1c","src/fmt.rs":"cc11b005c4559843bd908a57958a13c8d0922fae6aff5261f3583c90e60da73c","src/lib.rs":"abe525407298c0767ba1e5678863e89cdc3024258107a9ea829b5abd48c9a56e","src/stream.rs":"82565c3aa4c493e75a90a64bb6022ab9b5a5212806ac9a0548c7d2d34d5dace3","src/strip.rs":"0268bdc9155fc91bd7e92337c5e3ba96999780b46fab311b00922c7a3047233c","src/wincon.rs":"16afb01d151c3992bb3ee50871723f1e1f1f6b34d3f161d4a8dc6fd27db4cb1c"},"package":"824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "3048fe7820055a6c995170d822e725c62b3d63e1"
|
||||
},
|
||||
"path_in_vcs": "crates/anstream"
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
###############################################################################
|
||||
# @generated
|
||||
# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To
|
||||
# regenerate this file, run the following:
|
||||
#
|
||||
# bazel run @@//third_party:vendor_crates
|
||||
###############################################################################
|
||||
|
||||
load("@rules_rust//cargo:defs.bzl", "cargo_toml_env_vars")
|
||||
load("@rules_rust//rust:defs.bzl", "rust_library")
|
||||
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
cargo_toml_env_vars(
|
||||
name = "cargo_toml_env_vars",
|
||||
src = "Cargo.toml",
|
||||
)
|
||||
|
||||
rust_library(
|
||||
name = "anstream",
|
||||
srcs = glob(
|
||||
include = ["**/*.rs"],
|
||||
allow_empty = False,
|
||||
),
|
||||
compile_data = glob(
|
||||
include = ["**"],
|
||||
allow_empty = True,
|
||||
exclude = [
|
||||
"**/* *",
|
||||
".tmp_git_root/**/*",
|
||||
"BUILD",
|
||||
"BUILD.bazel",
|
||||
"WORKSPACE",
|
||||
"WORKSPACE.bazel",
|
||||
],
|
||||
),
|
||||
crate_features = [
|
||||
"auto",
|
||||
"default",
|
||||
"wincon",
|
||||
],
|
||||
crate_root = "src/lib.rs",
|
||||
edition = "2021",
|
||||
rustc_env_files = [
|
||||
":cargo_toml_env_vars",
|
||||
],
|
||||
rustc_flags = [
|
||||
"--cap-lints=allow",
|
||||
],
|
||||
tags = [
|
||||
"cargo-bazel",
|
||||
"crate-name=anstream",
|
||||
"manual",
|
||||
"noclippy",
|
||||
"norustfmt",
|
||||
],
|
||||
target_compatible_with = select({
|
||||
"@rules_rust//rust/platform:aarch64-apple-darwin": [],
|
||||
"@rules_rust//rust/platform:aarch64-apple-ios": [],
|
||||
"@rules_rust//rust/platform:aarch64-apple-ios-macabi": [],
|
||||
"@rules_rust//rust/platform:aarch64-apple-ios-sim": [],
|
||||
"@rules_rust//rust/platform:aarch64-linux-android": [],
|
||||
"@rules_rust//rust/platform:aarch64-pc-windows-msvc": [],
|
||||
"@rules_rust//rust/platform:aarch64-unknown-fuchsia": [],
|
||||
"@rules_rust//rust/platform:aarch64-unknown-linux-gnu": [],
|
||||
"@rules_rust//rust/platform:aarch64-unknown-nixos-gnu": [],
|
||||
"@rules_rust//rust/platform:aarch64-unknown-none": [],
|
||||
"@rules_rust//rust/platform:aarch64-unknown-nto-qnx710": [],
|
||||
"@rules_rust//rust/platform:aarch64-unknown-uefi": [],
|
||||
"@rules_rust//rust/platform:arm-unknown-linux-gnueabi": [],
|
||||
"@rules_rust//rust/platform:arm-unknown-linux-musleabi": [],
|
||||
"@rules_rust//rust/platform:armv7-linux-androideabi": [],
|
||||
"@rules_rust//rust/platform:armv7-unknown-linux-gnueabi": [],
|
||||
"@rules_rust//rust/platform:i686-apple-darwin": [],
|
||||
"@rules_rust//rust/platform:i686-linux-android": [],
|
||||
"@rules_rust//rust/platform:i686-pc-windows-msvc": [],
|
||||
"@rules_rust//rust/platform:i686-unknown-freebsd": [],
|
||||
"@rules_rust//rust/platform:i686-unknown-linux-gnu": [],
|
||||
"@rules_rust//rust/platform:loongarch64-unknown-linux-gnu": [],
|
||||
"@rules_rust//rust/platform:mips-unknown-linux-gnu": [],
|
||||
"@rules_rust//rust/platform:powerpc-unknown-linux-gnu": [],
|
||||
"@rules_rust//rust/platform:riscv32imac-unknown-none-elf": [],
|
||||
"@rules_rust//rust/platform:riscv32imc-unknown-none-elf": [],
|
||||
"@rules_rust//rust/platform:riscv64gc-unknown-linux-gnu": [],
|
||||
"@rules_rust//rust/platform:riscv64gc-unknown-none-elf": [],
|
||||
"@rules_rust//rust/platform:s390x-unknown-linux-gnu": [],
|
||||
"@rules_rust//rust/platform:sparc64-unknown-linux-gnu": [],
|
||||
"@rules_rust//rust/platform:sparc64-unknown-netbsd": [],
|
||||
"@rules_rust//rust/platform:sparc64-unknown-openbsd": [],
|
||||
"@rules_rust//rust/platform:thumbv6m-none-eabi": [],
|
||||
"@rules_rust//rust/platform:thumbv7em-none-eabi": [],
|
||||
"@rules_rust//rust/platform:thumbv7em-none-eabihf": [],
|
||||
"@rules_rust//rust/platform:thumbv7m-none-eabi": [],
|
||||
"@rules_rust//rust/platform:thumbv8m.main-none-eabi": [],
|
||||
"@rules_rust//rust/platform:thumbv8m.main-none-eabihf": [],
|
||||
"@rules_rust//rust/platform:wasm32-unknown-emscripten": [],
|
||||
"@rules_rust//rust/platform:wasm32-unknown-unknown": [],
|
||||
"@rules_rust//rust/platform:wasm32-wasip1": [],
|
||||
"@rules_rust//rust/platform:wasm32-wasip1-threads": [],
|
||||
"@rules_rust//rust/platform:wasm32-wasip2": [],
|
||||
"@rules_rust//rust/platform:x86_64-apple-darwin": [],
|
||||
"@rules_rust//rust/platform:x86_64-apple-ios": [],
|
||||
"@rules_rust//rust/platform:x86_64-apple-ios-macabi": [],
|
||||
"@rules_rust//rust/platform:x86_64-linux-android": [],
|
||||
"@rules_rust//rust/platform:x86_64-pc-windows-msvc": [],
|
||||
"@rules_rust//rust/platform:x86_64-unknown-freebsd": [],
|
||||
"@rules_rust//rust/platform:x86_64-unknown-fuchsia": [],
|
||||
"@rules_rust//rust/platform:x86_64-unknown-linux-gnu": [],
|
||||
"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu": [],
|
||||
"@rules_rust//rust/platform:x86_64-unknown-none": [],
|
||||
"@rules_rust//rust/platform:x86_64-unknown-uefi": [],
|
||||
"//conditions:default": ["@platforms//:incompatible"],
|
||||
}),
|
||||
version = "1.0.0",
|
||||
deps = [
|
||||
"//third_party/crates/anstyle-1.0.14:anstyle",
|
||||
"//third_party/crates/anstyle-parse-1.0.0:anstyle_parse",
|
||||
"//third_party/crates/anstyle-query-1.1.5:anstyle_query",
|
||||
"//third_party/crates/colorchoice-1.0.5:colorchoice",
|
||||
"//third_party/crates/is_terminal_polyfill-1.70.2:is_terminal_polyfill",
|
||||
"//third_party/crates/utf8parse-0.2.2:utf8parse",
|
||||
] + select({
|
||||
"@rules_rust//rust/platform:aarch64-pc-windows-msvc": [
|
||||
"//third_party/crates/anstyle-wincon-3.0.11:anstyle_wincon", # aarch64-pc-windows-msvc
|
||||
],
|
||||
"@rules_rust//rust/platform:i686-pc-windows-msvc": [
|
||||
"//third_party/crates/anstyle-wincon-3.0.11:anstyle_wincon", # i686-pc-windows-msvc
|
||||
],
|
||||
"@rules_rust//rust/platform:x86_64-pc-windows-msvc": [
|
||||
"//third_party/crates/anstyle-wincon-3.0.11:anstyle_wincon", # x86_64-pc-windows-msvc
|
||||
],
|
||||
"//conditions:default": [],
|
||||
}),
|
||||
)
|
||||
+709
@@ -0,0 +1,709 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"anstyle-parse",
|
||||
"anstyle-query",
|
||||
"anstyle-wincon",
|
||||
"colorchoice",
|
||||
"divan",
|
||||
"is_terminal_polyfill",
|
||||
"lexopt",
|
||||
"owo-colors",
|
||||
"proptest",
|
||||
"strip-ansi-escapes",
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-parse"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
|
||||
dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-query"
|
||||
version = "1.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2"
|
||||
dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-wincon"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
|
||||
dependencies = [
|
||||
"bit-vec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-vec"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9"
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.3.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fb690e81c7840c0d7aade59f242ea3b41b9bc27bcd5997890e7702ae4b32e487"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.3.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ed2e96bc16d8d740f6f48d663eddf4b8a0983e79210fd55479b7bcd0a69860e"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
"terminal_size",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b"
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
|
||||
|
||||
[[package]]
|
||||
name = "condtype"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baf0a07a401f374238ab8e2f11a104d2851bf9ce711ec69804834de8af45c7af"
|
||||
|
||||
[[package]]
|
||||
name = "divan"
|
||||
version = "0.1.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccc40f214f0d9e897cfc72e2edfa5c225d3252f758c537f11ac0a80371c073a6"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"clap",
|
||||
"condtype",
|
||||
"divan-macros",
|
||||
"libc",
|
||||
"regex-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "divan-macros"
|
||||
version = "0.1.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7bdb5411188f7f878a17964798c1264b6b0a9f915bd39b20bf99193c923e1b4e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "1.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2"
|
||||
dependencies = [
|
||||
"hermit-abi 0.3.9",
|
||||
"libc",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is-terminal"
|
||||
version = "0.4.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
|
||||
dependencies = [
|
||||
"hermit-abi 0.5.2",
|
||||
"libc",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.48.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2736dd548daf35f50d261bbad35a83890bb9b461797f15de528485fbf206ab15"
|
||||
dependencies = [
|
||||
"is-terminal",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||
|
||||
[[package]]
|
||||
name = "lexopt"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9fa0e2a1fcbe2f6be6c42e342259976206b383122fc152e872795338b5a3f3a7"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.177"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.3.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
version = "1.56.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8aab899efe6ce4fe821f6dda30c02d7041c79f147598ab4b60197f181e12d001"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "owo-colors"
|
||||
version = "4.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "caff54706df99d2a78a5a4e3455ff45448d81ef1bb63c22cd14052ca0e993a3f"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.103"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proptest"
|
||||
version = "1.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6fcdab19deb5195a31cf7726a210015ff1496ba1464fd42cb4f537b8b01b471f"
|
||||
dependencies = [
|
||||
"bit-set",
|
||||
"bit-vec",
|
||||
"bitflags 2.9.4",
|
||||
"lazy_static",
|
||||
"num-traits",
|
||||
"rand",
|
||||
"rand_chacha",
|
||||
"rand_xorshift",
|
||||
"regex-syntax",
|
||||
"rusty-fork",
|
||||
"tempfile",
|
||||
"unarray",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.41"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_xorshift"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
|
||||
dependencies = [
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-lite"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "943f41321c63ef1c92fd763bfe054d2668f7f225a5c29f0105903dc2fc04ba30"
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001"
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.37.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "519165d378b97752ca44bbe15047d5d3409e875f39327546b42ac81d7e18c1b6"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"errno",
|
||||
"io-lifetimes",
|
||||
"libc",
|
||||
"linux-raw-sys 0.3.8",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e"
|
||||
dependencies = [
|
||||
"bitflags 2.9.4",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.11.0",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusty-fork"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb3dcc6e454c328bb824492db107ab7c0ae8fcffe4ad210136ef014458c1bc4f"
|
||||
dependencies = [
|
||||
"fnv",
|
||||
"quick-error",
|
||||
"tempfile",
|
||||
"wait-timeout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strip-ansi-escapes"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a8f8038e7e7969abb3f1b7c2a811225e9296da208539e0f79c5251d6cac0025"
|
||||
dependencies = [
|
||||
"vte",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.23.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom",
|
||||
"once_cell",
|
||||
"rustix 1.1.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "terminal_size"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e6bf6f19e9f8ed8d4048dc22981458ebcf406d67e94cd422e5ecd73d63b3237"
|
||||
dependencies = [
|
||||
"rustix 0.37.28",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unarray"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "vte"
|
||||
version = "0.14.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "231fdcd7ef3037e8330d8e17e61011a2c244126acc0a982f4040ac3f9f0bc077"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wait-timeout"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.14.4+wasi-0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "88a5f4a424faf49c3c2c344f166f0662341d470ea185e939657aaff130f0ec4a"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.48.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
|
||||
dependencies = [
|
||||
"windows-targets 0.48.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
|
||||
dependencies = [
|
||||
"windows-targets 0.53.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm 0.48.5",
|
||||
"windows_aarch64_msvc 0.48.5",
|
||||
"windows_i686_gnu 0.48.5",
|
||||
"windows_i686_msvc 0.48.5",
|
||||
"windows_x86_64_gnu 0.48.5",
|
||||
"windows_x86_64_gnullvm 0.48.5",
|
||||
"windows_x86_64_msvc 0.48.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.53.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
"windows_aarch64_gnullvm 0.53.1",
|
||||
"windows_aarch64_msvc 0.53.1",
|
||||
"windows_i686_gnu 0.53.1",
|
||||
"windows_i686_gnullvm",
|
||||
"windows_i686_msvc 0.53.1",
|
||||
"windows_x86_64_gnu 0.53.1",
|
||||
"windows_x86_64_gnullvm 0.53.1",
|
||||
"windows_x86_64_msvc 0.53.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.45.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c573471f125075647d03df72e026074b7203790d41351cd6edc96f46bcccd36"
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
# 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.66.0"
|
||||
name = "anstream"
|
||||
version = "1.0.0"
|
||||
build = false
|
||||
include = [
|
||||
"build.rs",
|
||||
"src/**/*",
|
||||
"Cargo.toml",
|
||||
"Cargo.lock",
|
||||
"LICENSE*",
|
||||
"README.md",
|
||||
"examples/**/*",
|
||||
]
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "IO stream adapters for writing colored text that will gracefully degrade according to your terminal's capabilities."
|
||||
readme = "README.md"
|
||||
keywords = [
|
||||
"ansi",
|
||||
"terminal",
|
||||
"color",
|
||||
"strip",
|
||||
"wincon",
|
||||
]
|
||||
categories = ["command-line-interface"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/rust-cli/anstyle.git"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = [
|
||||
"--cfg",
|
||||
"docsrs",
|
||||
"--generate-link-to-definition",
|
||||
]
|
||||
|
||||
[[package.metadata.release.pre-release-replacements]]
|
||||
file = "CHANGELOG.md"
|
||||
search = "Unreleased"
|
||||
replace = "{{version}}"
|
||||
min = 1
|
||||
|
||||
[[package.metadata.release.pre-release-replacements]]
|
||||
file = "CHANGELOG.md"
|
||||
search = '\.\.\.HEAD'
|
||||
replace = "...{{tag_name}}"
|
||||
exactly = 1
|
||||
|
||||
[[package.metadata.release.pre-release-replacements]]
|
||||
file = "CHANGELOG.md"
|
||||
search = "ReleaseDate"
|
||||
replace = "{{date}}"
|
||||
min = 1
|
||||
|
||||
[[package.metadata.release.pre-release-replacements]]
|
||||
file = "CHANGELOG.md"
|
||||
search = "<!-- next-header -->"
|
||||
replace = """
|
||||
<!-- next-header -->
|
||||
## [Unreleased] - ReleaseDate
|
||||
"""
|
||||
exactly = 1
|
||||
|
||||
[[package.metadata.release.pre-release-replacements]]
|
||||
file = "CHANGELOG.md"
|
||||
search = "<!-- next-url -->"
|
||||
replace = """
|
||||
<!-- next-url -->
|
||||
[Unreleased]: https://github.com/rust-cli/anstyle/compare/{{tag_name}}...HEAD"""
|
||||
exactly = 1
|
||||
|
||||
[features]
|
||||
auto = ["dep:anstyle-query"]
|
||||
default = [
|
||||
"auto",
|
||||
"wincon",
|
||||
]
|
||||
test = []
|
||||
wincon = ["dep:anstyle-wincon"]
|
||||
|
||||
[lib]
|
||||
name = "anstream"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[example]]
|
||||
name = "dump-stream"
|
||||
path = "examples/dump-stream.rs"
|
||||
required-features = ["auto"]
|
||||
|
||||
[[example]]
|
||||
name = "query-stream"
|
||||
path = "examples/query-stream.rs"
|
||||
required-features = ["auto"]
|
||||
|
||||
[dependencies.anstyle]
|
||||
version = "1.0.0"
|
||||
|
||||
[dependencies.anstyle-parse]
|
||||
version = "1.0.0"
|
||||
|
||||
[dependencies.anstyle-query]
|
||||
version = "1.0.0"
|
||||
optional = true
|
||||
|
||||
[dependencies.colorchoice]
|
||||
version = "1.0.0"
|
||||
|
||||
[dependencies.is_terminal_polyfill]
|
||||
version = "1.48"
|
||||
|
||||
[dependencies.utf8parse]
|
||||
version = "0.2.2"
|
||||
|
||||
[dev-dependencies.divan]
|
||||
version = "0.1.16"
|
||||
|
||||
[dev-dependencies.lexopt]
|
||||
version = "0.3.1"
|
||||
|
||||
[dev-dependencies.owo-colors]
|
||||
version = "4.0.0"
|
||||
|
||||
[dev-dependencies.proptest]
|
||||
version = "1.7.0"
|
||||
|
||||
[dev-dependencies.strip-ansi-escapes]
|
||||
version = "0.2.1"
|
||||
|
||||
[target."cfg(windows)".dependencies.anstyle-wincon]
|
||||
version = "3.0.5"
|
||||
optional = true
|
||||
|
||||
[lints.clippy]
|
||||
bool_assert_comparison = "allow"
|
||||
branches_sharing_code = "allow"
|
||||
checked_conversions = "warn"
|
||||
collapsible_else_if = "allow"
|
||||
create_dir = "warn"
|
||||
dbg_macro = "warn"
|
||||
debug_assert_with_mut_call = "warn"
|
||||
doc_markdown = "warn"
|
||||
empty_enums = "warn"
|
||||
enum_glob_use = "warn"
|
||||
expl_impl_clone_on_copy = "warn"
|
||||
explicit_deref_methods = "warn"
|
||||
explicit_into_iter_loop = "warn"
|
||||
fallible_impl_from = "warn"
|
||||
filter_map_next = "warn"
|
||||
flat_map_option = "warn"
|
||||
float_cmp_const = "warn"
|
||||
fn_params_excessive_bools = "warn"
|
||||
from_iter_instead_of_collect = "warn"
|
||||
if_same_then_else = "allow"
|
||||
implicit_clone = "warn"
|
||||
imprecise_flops = "warn"
|
||||
inconsistent_struct_constructor = "warn"
|
||||
inefficient_to_string = "warn"
|
||||
infinite_loop = "warn"
|
||||
invalid_upcast_comparisons = "warn"
|
||||
large_digit_groups = "warn"
|
||||
large_stack_arrays = "warn"
|
||||
large_types_passed_by_value = "warn"
|
||||
let_and_return = "allow"
|
||||
linkedlist = "warn"
|
||||
lossy_float_literal = "warn"
|
||||
macro_use_imports = "warn"
|
||||
mem_forget = "warn"
|
||||
mutex_integer = "warn"
|
||||
needless_continue = "allow"
|
||||
needless_for_each = "warn"
|
||||
negative_feature_names = "warn"
|
||||
path_buf_push_overwrite = "warn"
|
||||
ptr_as_ptr = "warn"
|
||||
rc_mutex = "warn"
|
||||
redundant_feature_names = "warn"
|
||||
ref_option_ref = "warn"
|
||||
rest_pat_in_fully_bound_structs = "warn"
|
||||
result_large_err = "allow"
|
||||
same_functions_in_if_condition = "warn"
|
||||
self_named_module_files = "warn"
|
||||
semicolon_if_nothing_returned = "warn"
|
||||
str_to_string = "warn"
|
||||
string_add = "warn"
|
||||
string_add_assign = "warn"
|
||||
string_lit_as_bytes = "warn"
|
||||
todo = "warn"
|
||||
trait_duplication_in_bounds = "warn"
|
||||
uninlined_format_args = "warn"
|
||||
verbose_file_reads = "warn"
|
||||
wildcard_imports = "warn"
|
||||
zero_sized_map_values = "warn"
|
||||
|
||||
[lints.rust]
|
||||
unnameable_types = "warn"
|
||||
unreachable_pub = "warn"
|
||||
unsafe_op_in_unsafe_fn = "warn"
|
||||
unused_lifetimes = "warn"
|
||||
unused_macro_rules = "warn"
|
||||
unused_qualifications = "warn"
|
||||
|
||||
[lints.rust.rust_2018_idioms]
|
||||
level = "warn"
|
||||
priority = -1
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
[package]
|
||||
name = "anstream"
|
||||
version = "1.0.0"
|
||||
description = "IO stream adapters for writing colored text that will gracefully degrade according to your terminal's capabilities."
|
||||
categories = ["command-line-interface"]
|
||||
keywords = ["ansi", "terminal", "color", "strip", "wincon"]
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
include.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs", "--generate-link-to-definition"]
|
||||
|
||||
[package.metadata.release]
|
||||
pre-release-replacements = [
|
||||
{file="CHANGELOG.md", search="Unreleased", replace="{{version}}", min=1},
|
||||
{file="CHANGELOG.md", search="\\.\\.\\.HEAD", replace="...{{tag_name}}", exactly=1},
|
||||
{file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}", min=1},
|
||||
{file="CHANGELOG.md", search="<!-- next-header -->", replace="<!-- next-header -->\n## [Unreleased] - ReleaseDate\n", exactly=1},
|
||||
{file="CHANGELOG.md", search="<!-- next-url -->", replace="<!-- next-url -->\n[Unreleased]: https://github.com/rust-cli/anstyle/compare/{{tag_name}}...HEAD", exactly=1},
|
||||
]
|
||||
|
||||
[features]
|
||||
default = ["auto", "wincon"]
|
||||
auto = ["dep:anstyle-query"]
|
||||
wincon = ["dep:anstyle-wincon"]
|
||||
# Enable in `dev-dependencies` to make sure output is captured for tests
|
||||
test = []
|
||||
|
||||
[dependencies]
|
||||
anstyle = { version = "1.0.0", path = "../anstyle" }
|
||||
anstyle-parse = { version = "1.0.0", path = "../anstyle-parse" }
|
||||
colorchoice = { version = "1.0.0", path = "../colorchoice" }
|
||||
anstyle-query = { version = "1.0.0", path = "../anstyle-query", optional = true }
|
||||
utf8parse = "0.2.2"
|
||||
is_terminal_polyfill = "1.48"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
anstyle-wincon = { version = "3.0.5", path = "../anstyle-wincon", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
divan = "0.1.16"
|
||||
lexopt = "0.3.1"
|
||||
owo-colors = "4.0.0"
|
||||
proptest = "1.7.0"
|
||||
strip-ansi-escapes = "0.2.1"
|
||||
|
||||
[[example]]
|
||||
name = "dump-stream"
|
||||
required-features = ["auto"]
|
||||
|
||||
[[example]]
|
||||
name = "query-stream"
|
||||
required-features = ["auto"]
|
||||
|
||||
[[bench]]
|
||||
name = "strip"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "wincon"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "stream"
|
||||
harness = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
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 {yyyy} {name of copyright owner}
|
||||
|
||||
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
@@ -0,0 +1,19 @@
|
||||
Copyright (c) Individual contributors
|
||||
|
||||
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.
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
# anstream
|
||||
|
||||
> A simple cross platform library for writing colored text to a terminal.
|
||||
|
||||
*A portmanteau of "ansi stream"*
|
||||
|
||||
[][Documentation]
|
||||

|
||||
[](https://crates.io/crates/anstream)
|
||||
|
||||
Specialized `stdout` and `stderr` that accept ANSI escape codes and adapt them
|
||||
based on the terminal's capabilities.
|
||||
|
||||
`anstream::adapter::strip_str` may also be of interest on its own for low
|
||||
overhead stripping of ANSI escape codes.
|
||||
|
||||
## License
|
||||
|
||||
Licensed under either of
|
||||
|
||||
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or <https://www.apache.org/licenses/LICENSE-2.0>)
|
||||
* MIT license ([LICENSE-MIT](LICENSE-MIT) or <https://opensource.org/license/mit>)
|
||||
|
||||
at your option.
|
||||
|
||||
## [Contribute](../../CONTRIBUTING.md)
|
||||
|
||||
Unless you explicitly state otherwise, any contribution intentionally
|
||||
submitted for inclusion in the work by you, as defined in the Apache-2.0
|
||||
license, shall be dual-licensed as above, without any additional terms or
|
||||
conditions.
|
||||
|
||||
[Crates.io]: https://crates.io/crates/anstream
|
||||
[Documentation]: https://docs.rs/anstream
|
||||
@@ -0,0 +1,130 @@
|
||||
//! Write colored text, adapting to the terminals capabilities
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
fn main() -> Result<(), lexopt::Error> {
|
||||
let args = Args::parse()?;
|
||||
let stdout = anstream::stdout();
|
||||
let mut stdout = stdout.lock();
|
||||
|
||||
for fixed in 0..16 {
|
||||
let color = anstyle::Ansi256Color(fixed)
|
||||
.into_ansi()
|
||||
.expect("within 4-bit color range");
|
||||
let style = style(color, args.layer, args.effects);
|
||||
let _ = print_number(&mut stdout, fixed, style);
|
||||
if fixed == 7 || fixed == 15 {
|
||||
let _ = writeln!(&mut stdout);
|
||||
}
|
||||
}
|
||||
|
||||
for fixed in 16..232 {
|
||||
let col = (fixed - 16) % 36;
|
||||
if col == 0 {
|
||||
let _ = writeln!(stdout);
|
||||
}
|
||||
let color = anstyle::Ansi256Color(fixed);
|
||||
let style = style(color, args.layer, args.effects);
|
||||
let _ = print_number(&mut stdout, fixed, style);
|
||||
}
|
||||
|
||||
let _ = writeln!(stdout);
|
||||
let _ = writeln!(stdout);
|
||||
for fixed in 232..=255 {
|
||||
let color = anstyle::Ansi256Color(fixed);
|
||||
let style = style(color, args.layer, args.effects);
|
||||
let _ = print_number(&mut stdout, fixed, style);
|
||||
}
|
||||
|
||||
let _ = writeln!(stdout);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn style(
|
||||
color: impl Into<anstyle::Color>,
|
||||
layer: Layer,
|
||||
effects: anstyle::Effects,
|
||||
) -> anstyle::Style {
|
||||
let color = color.into();
|
||||
(match layer {
|
||||
Layer::Fg => anstyle::Style::new().fg_color(Some(color)),
|
||||
Layer::Bg => anstyle::Style::new().bg_color(Some(color)),
|
||||
Layer::Underline => anstyle::Style::new().underline_color(Some(color)),
|
||||
}) | effects
|
||||
}
|
||||
|
||||
fn print_number(stdout: &mut impl Write, fixed: u8, style: anstyle::Style) -> std::io::Result<()> {
|
||||
write!(stdout, "{style}{fixed:>3X}{style:#}",)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Args {
|
||||
effects: anstyle::Effects,
|
||||
layer: Layer,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Default)]
|
||||
enum Layer {
|
||||
#[default]
|
||||
Fg,
|
||||
Bg,
|
||||
Underline,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
fn parse() -> Result<Self, lexopt::Error> {
|
||||
use lexopt::prelude::*;
|
||||
|
||||
let mut res = Args::default();
|
||||
|
||||
let mut args = lexopt::Parser::from_env();
|
||||
while let Some(arg) = args.next()? {
|
||||
match arg {
|
||||
Long("layer") => {
|
||||
res.layer = args.value()?.parse_with(|s| match s {
|
||||
"fg" => Ok(Layer::Fg),
|
||||
"bg" => Ok(Layer::Bg),
|
||||
"underline" => Ok(Layer::Underline),
|
||||
_ => Err("expected values fg, bg, underline"),
|
||||
})?;
|
||||
}
|
||||
Long("effect") => {
|
||||
const EFFECTS: [(&str, anstyle::Effects); 12] = [
|
||||
("bold", anstyle::Effects::BOLD),
|
||||
("dimmed", anstyle::Effects::DIMMED),
|
||||
("italic", anstyle::Effects::ITALIC),
|
||||
("underline", anstyle::Effects::UNDERLINE),
|
||||
("double_underline", anstyle::Effects::DOUBLE_UNDERLINE),
|
||||
("curly_underline", anstyle::Effects::CURLY_UNDERLINE),
|
||||
("dotted_underline", anstyle::Effects::DOTTED_UNDERLINE),
|
||||
("dashed_underline", anstyle::Effects::DASHED_UNDERLINE),
|
||||
("blink", anstyle::Effects::BLINK),
|
||||
("invert", anstyle::Effects::INVERT),
|
||||
("hidden", anstyle::Effects::HIDDEN),
|
||||
("strikethrough", anstyle::Effects::STRIKETHROUGH),
|
||||
];
|
||||
let effect = args.value()?.parse_with(|s| {
|
||||
EFFECTS
|
||||
.into_iter()
|
||||
.find(|(name, _)| *name == s)
|
||||
.map(|(_, effect)| effect)
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"expected one of {}",
|
||||
EFFECTS
|
||||
.into_iter()
|
||||
.map(|(n, _)| n)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
)
|
||||
})
|
||||
})?;
|
||||
res.effects = res.effects.insert(effect);
|
||||
}
|
||||
_ => return Err(arg.unexpected()),
|
||||
}
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! Report a terminal's capabilities
|
||||
|
||||
fn main() {
|
||||
println!("stdout:");
|
||||
println!(
|
||||
" choice: {:?}",
|
||||
anstream::AutoStream::choice(&std::io::stdout())
|
||||
);
|
||||
println!(
|
||||
" choice: {:?}",
|
||||
anstream::AutoStream::auto(std::io::stdout()).current_choice()
|
||||
);
|
||||
println!("stderr:");
|
||||
println!(
|
||||
" choice: {:?}",
|
||||
anstream::AutoStream::choice(&std::io::stderr())
|
||||
);
|
||||
println!(
|
||||
" choice: {:?}",
|
||||
anstream::AutoStream::auto(std::io::stderr()).current_choice()
|
||||
);
|
||||
}
|
||||
+364
@@ -0,0 +1,364 @@
|
||||
/// Prints to [`stdout`][crate::stdout].
|
||||
///
|
||||
/// Equivalent to the [`println!`] macro except that a newline is not printed at
|
||||
/// the end of the message.
|
||||
///
|
||||
/// Note that stdout is frequently line-buffered by default so it may be
|
||||
/// necessary to use [`std::io::Write::flush()`] to ensure the output is emitted
|
||||
/// immediately.
|
||||
///
|
||||
/// **NOTE:** The `print!` macro will lock the standard output on each call. If you call
|
||||
/// `print!` within a hot loop, this behavior may be the bottleneck of the loop.
|
||||
/// To avoid this, lock stdout with [`AutoStream::lock`][crate::AutoStream::lock]:
|
||||
/// ```
|
||||
/// # #[cfg(feature = "auto")] {
|
||||
/// use std::io::Write as _;
|
||||
///
|
||||
/// let mut lock = anstream::stdout().lock();
|
||||
/// write!(lock, "hello world").unwrap();
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// Use `print!` only for the primary output of your program. Use
|
||||
/// [`eprint!`] instead to print error and progress messages.
|
||||
///
|
||||
/// **NOTE:** Not all `print!` calls will be captured in tests like [`std::print!`]
|
||||
/// - Capturing will automatically be activated in test binaries
|
||||
/// - Otherwise, only when the `test` feature is enabled
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if writing to `stdout` fails for any reason **except** broken pipe.
|
||||
///
|
||||
/// Writing to non-blocking stdout can cause an error, which will lead
|
||||
/// this macro to panic.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # #[cfg(feature = "auto")] {
|
||||
/// use std::io::Write as _;
|
||||
/// use anstream::print;
|
||||
/// use anstream::stdout;
|
||||
///
|
||||
/// print!("this ");
|
||||
/// print!("will ");
|
||||
/// print!("be ");
|
||||
/// print!("on ");
|
||||
/// print!("the ");
|
||||
/// print!("same ");
|
||||
/// print!("line ");
|
||||
///
|
||||
/// stdout().flush().unwrap();
|
||||
///
|
||||
/// print!("this string has a newline, why not choose println! instead?\n");
|
||||
///
|
||||
/// stdout().flush().unwrap();
|
||||
/// # }
|
||||
/// ```
|
||||
#[cfg(feature = "auto")]
|
||||
#[macro_export]
|
||||
macro_rules! print {
|
||||
($($arg:tt)*) => {{
|
||||
if cfg!(test) || $crate::_macros::FEATURE_TEST_ACTIVATED {
|
||||
let target_stream = std::io::stdout();
|
||||
let buffer = $crate::_macros::to_adapted_string(&format_args!($($arg)*), &target_stream);
|
||||
::std::print!("{}", buffer)
|
||||
} else {
|
||||
use std::io::Write as _;
|
||||
|
||||
let mut stream = $crate::stdout();
|
||||
match ::std::write!(&mut stream, $($arg)*) {
|
||||
Err(e) if e.kind() != ::std::io::ErrorKind::BrokenPipe => {
|
||||
::std::panic!("failed printing to stdout: {e}");
|
||||
}
|
||||
Err(_) | Ok(_) => {}
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
/// Prints to [`stdout`][crate::stdout], with a newline.
|
||||
///
|
||||
/// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
|
||||
/// (no additional CARRIAGE RETURN (`\r`/`U+000D`)).
|
||||
///
|
||||
/// This macro uses the same syntax as [`format!`], but writes to the standard output instead.
|
||||
/// See [`std::fmt`] for more information.
|
||||
///
|
||||
/// **NOTE:** The `println!` macro will lock the standard output on each call. If you call
|
||||
/// `println!` within a hot loop, this behavior may be the bottleneck of the loop.
|
||||
/// To avoid this, lock stdout with [`AutoStream::lock`][crate::AutoStream::lock]:
|
||||
/// ```
|
||||
/// # #[cfg(feature = "auto")] {
|
||||
/// use std::io::Write as _;
|
||||
///
|
||||
/// let mut lock = anstream::stdout().lock();
|
||||
/// writeln!(lock, "hello world").unwrap();
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// Use `println!` only for the primary output of your program. Use
|
||||
/// [`eprintln!`] instead to print error and progress messages.
|
||||
///
|
||||
/// **NOTE:** Not all `println!` calls will be captured in tests like [`std::println!`]
|
||||
/// - Capturing will automatically be activated in test binaries
|
||||
/// - Otherwise, only when the `test` feature is enabled
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if writing to `stdout` fails for any reason **except** broken pipe.
|
||||
///
|
||||
/// Writing to non-blocking stdout can cause an error, which will lead
|
||||
/// this macro to panic.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # #[cfg(feature = "auto")] {
|
||||
/// use anstream::println;
|
||||
///
|
||||
/// println!(); // prints just a newline
|
||||
/// println!("hello there!");
|
||||
/// println!("format {} arguments", "some");
|
||||
/// let local_variable = "some";
|
||||
/// println!("format {local_variable} arguments");
|
||||
/// # }
|
||||
/// ```
|
||||
#[cfg(feature = "auto")]
|
||||
#[macro_export]
|
||||
macro_rules! println {
|
||||
() => {
|
||||
$crate::print!("\n")
|
||||
};
|
||||
($($arg:tt)*) => {{
|
||||
if cfg!(test) || $crate::_macros::FEATURE_TEST_ACTIVATED {
|
||||
let target_stream = std::io::stdout();
|
||||
let buffer = $crate::_macros::to_adapted_string(&format_args!($($arg)*), &target_stream);
|
||||
::std::println!("{}", buffer)
|
||||
} else {
|
||||
use std::io::Write as _;
|
||||
|
||||
let mut stream = $crate::stdout();
|
||||
match ::std::writeln!(&mut stream, $($arg)*) {
|
||||
Err(e) if e.kind() != ::std::io::ErrorKind::BrokenPipe => {
|
||||
::std::panic!("failed printing to stdout: {e}");
|
||||
}
|
||||
Err(_) | Ok(_) => {}
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
/// Prints to [`stderr`][crate::stderr].
|
||||
///
|
||||
/// Equivalent to the [`print!`] macro, except that output goes to
|
||||
/// `stderr` instead of `stdout`. See [`print!`] for
|
||||
/// example usage.
|
||||
///
|
||||
/// Use `eprint!` only for error and progress messages. Use `print!`
|
||||
/// instead for the primary output of your program.
|
||||
///
|
||||
/// **NOTE:** Not all `eprint!` calls will be captured in tests like [`std::eprint!`]
|
||||
/// - Capturing will automatically be activated in test binaries
|
||||
/// - Otherwise, only when the `test` feature is enabled
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if writing to `stderr` fails for any reason **except** broken pipe.
|
||||
///
|
||||
/// Writing to non-blocking stdout can cause an error, which will lead
|
||||
/// this macro to panic.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # #[cfg(feature = "auto")] {
|
||||
/// use anstream::eprint;
|
||||
///
|
||||
/// eprint!("Error: Could not complete task");
|
||||
/// # }
|
||||
/// ```
|
||||
#[cfg(feature = "auto")]
|
||||
#[macro_export]
|
||||
macro_rules! eprint {
|
||||
($($arg:tt)*) => {{
|
||||
if cfg!(test) || $crate::_macros::FEATURE_TEST_ACTIVATED {
|
||||
let target_stream = std::io::stderr();
|
||||
let buffer = $crate::_macros::to_adapted_string(&format_args!($($arg)*), &target_stream);
|
||||
::std::eprint!("{}", buffer)
|
||||
} else {
|
||||
use std::io::Write as _;
|
||||
|
||||
let mut stream = $crate::stderr();
|
||||
match ::std::write!(&mut stream, $($arg)*) {
|
||||
Err(e) if e.kind() != ::std::io::ErrorKind::BrokenPipe => {
|
||||
::std::panic!("failed printing to stderr: {e}");
|
||||
}
|
||||
Err(_) | Ok(_) => {}
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
/// Prints to [`stderr`][crate::stderr], with a newline.
|
||||
///
|
||||
/// Equivalent to the [`println!`] macro, except that output goes to
|
||||
/// `stderr` instead of `stdout`. See [`println!`] for
|
||||
/// example usage.
|
||||
///
|
||||
/// Use `eprintln!` only for error and progress messages. Use `println!`
|
||||
/// instead for the primary output of your program.
|
||||
///
|
||||
/// **NOTE:** Not all `eprintln!` calls will be captured in tests like [`std::eprintln!`]
|
||||
/// - Capturing will automatically be activated in test binaries
|
||||
/// - Otherwise, only when the `test` feature is enabled
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if writing to `stderr` fails for any reason **except** broken pipe.
|
||||
///
|
||||
/// Writing to non-blocking stdout can cause an error, which will lead
|
||||
/// this macro to panic.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # #[cfg(feature = "auto")] {
|
||||
/// use anstream::eprintln;
|
||||
///
|
||||
/// eprintln!("Error: Could not complete task");
|
||||
/// # }
|
||||
/// ```
|
||||
#[cfg(feature = "auto")]
|
||||
#[macro_export]
|
||||
macro_rules! eprintln {
|
||||
() => {
|
||||
$crate::eprint!("\n")
|
||||
};
|
||||
($($arg:tt)*) => {{
|
||||
if cfg!(test) || $crate::_macros::FEATURE_TEST_ACTIVATED {
|
||||
let target_stream = std::io::stderr();
|
||||
let buffer = $crate::_macros::to_adapted_string(&format_args!($($arg)*), &target_stream);
|
||||
::std::eprintln!("{}", buffer)
|
||||
} else {
|
||||
use std::io::Write as _;
|
||||
|
||||
let mut stream = $crate::stderr();
|
||||
match ::std::writeln!(&mut stream, $($arg)*) {
|
||||
Err(e) if e.kind() != ::std::io::ErrorKind::BrokenPipe => {
|
||||
::std::panic!("failed printing to stderr: {e}");
|
||||
}
|
||||
Err(_) | Ok(_) => {}
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
/// Panics the current thread.
|
||||
///
|
||||
/// This allows a program to terminate immediately and provide feedback
|
||||
/// to the caller of the program.
|
||||
///
|
||||
/// This macro is the perfect way to assert conditions in example code and in
|
||||
/// tests. `panic!` is closely tied with the `unwrap` method of both
|
||||
/// [`Option`][ounwrap] and [`Result`][runwrap] enums. Both implementations call
|
||||
/// `panic!` when they are set to [`None`] or [`Err`] variants.
|
||||
///
|
||||
/// When using `panic!()` you can specify a string payload, that is built using
|
||||
/// the [`format!`] syntax. That payload is used when injecting the panic into
|
||||
/// the calling Rust thread, causing the thread to panic entirely.
|
||||
///
|
||||
/// The behavior of the default `std` hook, i.e. the code that runs directly
|
||||
/// after the panic is invoked, is to print the message payload to
|
||||
/// `stderr` along with the file/line/column information of the `panic!()`
|
||||
/// call. You can override the panic hook using [`std::panic::set_hook()`].
|
||||
/// Inside the hook a panic can be accessed as a `&dyn Any + Send`,
|
||||
/// which contains either a `&str` or `String` for regular `panic!()` invocations.
|
||||
/// To panic with a value of another other type, [`panic_any`] can be used.
|
||||
///
|
||||
/// See also the macro [`compile_error!`], for raising errors during compilation.
|
||||
///
|
||||
/// # When to use `panic!` vs `Result`
|
||||
///
|
||||
/// The Rust language provides two complementary systems for constructing /
|
||||
/// representing, reporting, propagating, reacting to, and discarding errors. These
|
||||
/// responsibilities are collectively known as "error handling." `panic!` and
|
||||
/// `Result` are similar in that they are each the primary interface of their
|
||||
/// respective error handling systems; however, the meaning these interfaces attach
|
||||
/// to their errors and the responsibilities they fulfill within their respective
|
||||
/// error handling systems differ.
|
||||
///
|
||||
/// The `panic!` macro is used to construct errors that represent a bug that has
|
||||
/// been detected in your program. With `panic!` you provide a message that
|
||||
/// describes the bug and the language then constructs an error with that message,
|
||||
/// reports it, and propagates it for you.
|
||||
///
|
||||
/// `Result` on the other hand is used to wrap other types that represent either
|
||||
/// the successful result of some computation, `Ok(T)`, or error types that
|
||||
/// represent an anticipated runtime failure mode of that computation, `Err(E)`.
|
||||
/// `Result` is used alongside user defined types which represent the various
|
||||
/// anticipated runtime failure modes that the associated computation could
|
||||
/// encounter. `Result` must be propagated manually, often with the help of the
|
||||
/// `?` operator and `Try` trait, and they must be reported manually, often with
|
||||
/// the help of the `Error` trait.
|
||||
///
|
||||
/// For more detailed information about error handling check out the [book] or the
|
||||
/// [`std::result`] module docs.
|
||||
///
|
||||
/// [ounwrap]: Option::unwrap
|
||||
/// [runwrap]: Result::unwrap
|
||||
/// [`std::panic::set_hook()`]: ../std/panic/fn.set_hook.html
|
||||
/// [`panic_any`]: ../std/panic/fn.panic_any.html
|
||||
/// [`Box`]: ../std/boxed/struct.Box.html
|
||||
/// [`format!`]: ../std/macro.format.html
|
||||
/// [book]: ../book/ch09-00-error-handling.html
|
||||
/// [`std::result`]: ../std/result/index.html
|
||||
///
|
||||
/// # Current implementation
|
||||
///
|
||||
/// If the main thread panics it will terminate all your threads and end your
|
||||
/// program with code `101`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```should_panic
|
||||
/// # #![allow(unreachable_code)]
|
||||
/// use anstream::panic;
|
||||
/// panic!();
|
||||
/// panic!("this is a terrible mistake!");
|
||||
/// panic!("this is a {} {message}", "fancy", message = "message");
|
||||
/// ```
|
||||
#[cfg(feature = "auto")]
|
||||
#[macro_export]
|
||||
macro_rules! panic {
|
||||
() => {
|
||||
::std::panic!()
|
||||
};
|
||||
($($arg:tt)*) => {{
|
||||
let target_stream = std::io::stderr();
|
||||
let buffer = $crate::_macros::to_adapted_string(&format_args!($($arg)*), &target_stream);
|
||||
::std::panic!("{}", buffer)
|
||||
}};
|
||||
}
|
||||
|
||||
#[cfg(feature = "auto")]
|
||||
pub const FEATURE_TEST_ACTIVATED: bool = cfg!(feature = "test");
|
||||
|
||||
#[cfg(feature = "auto")]
|
||||
pub fn to_adapted_string(
|
||||
display: &dyn std::fmt::Display,
|
||||
stream: &impl crate::stream::RawStream,
|
||||
) -> String {
|
||||
use std::io::Write as _;
|
||||
|
||||
let choice = crate::AutoStream::choice(stream);
|
||||
let buffer = Vec::new();
|
||||
let mut stream = crate::AutoStream::new(buffer, choice);
|
||||
// Ignore errors rather than panic
|
||||
let _ = ::std::write!(&mut stream, "{display}");
|
||||
let buffer = stream.into_inner();
|
||||
// Should be UTF-8 but not wanting to panic
|
||||
let buffer = String::from_utf8_lossy(&buffer).into_owned();
|
||||
buffer
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! Gracefully degrade styled output
|
||||
|
||||
mod strip;
|
||||
mod wincon;
|
||||
|
||||
pub use strip::strip_bytes;
|
||||
pub use strip::strip_str;
|
||||
pub use strip::StripBytes;
|
||||
pub use strip::StripBytesIter;
|
||||
pub use strip::StripStr;
|
||||
pub use strip::StripStrIter;
|
||||
pub use strip::StrippedBytes;
|
||||
pub use strip::StrippedStr;
|
||||
pub use wincon::WinconBytes;
|
||||
pub use wincon::WinconBytesIter;
|
||||
@@ -0,0 +1,511 @@
|
||||
use anstyle_parse::state::state_change;
|
||||
use anstyle_parse::state::Action;
|
||||
use anstyle_parse::state::State;
|
||||
|
||||
/// Strip ANSI escapes from a `&str`, returning the printable content
|
||||
///
|
||||
/// This can be used to take output from a program that includes escape sequences and write it
|
||||
/// somewhere that does not easily support them, such as a log file.
|
||||
///
|
||||
/// For non-contiguous data, see [`StripStr`].
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use std::io::Write as _;
|
||||
///
|
||||
/// let styled_text = "\x1b[32mfoo\x1b[m bar";
|
||||
/// let plain_str = anstream::adapter::strip_str(&styled_text).to_string();
|
||||
/// assert_eq!(plain_str, "foo bar");
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn strip_str(data: &str) -> StrippedStr<'_> {
|
||||
StrippedStr::new(data)
|
||||
}
|
||||
|
||||
/// See [`strip_str`]
|
||||
#[derive(Default, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StrippedStr<'s> {
|
||||
bytes: &'s [u8],
|
||||
state: State,
|
||||
}
|
||||
|
||||
impl<'s> StrippedStr<'s> {
|
||||
#[inline]
|
||||
fn new(data: &'s str) -> Self {
|
||||
Self {
|
||||
bytes: data.as_bytes(),
|
||||
state: State::Ground,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a [`String`] of the printable content
|
||||
#[inline]
|
||||
#[allow(clippy::inherent_to_string_shadow_display)] // Single-allocation implementation
|
||||
pub fn to_string(&self) -> String {
|
||||
use std::fmt::Write as _;
|
||||
let mut stripped = String::with_capacity(self.bytes.len());
|
||||
let _ = write!(&mut stripped, "{self}");
|
||||
stripped
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for StrippedStr<'_> {
|
||||
/// **Note:** this does *not* exhaust the [`Iterator`]
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let iter = Self {
|
||||
bytes: self.bytes,
|
||||
state: self.state,
|
||||
};
|
||||
for printable in iter {
|
||||
printable.fmt(f)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s> Iterator for StrippedStr<'s> {
|
||||
type Item = &'s str;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
next_str(&mut self.bytes, &mut self.state)
|
||||
}
|
||||
}
|
||||
|
||||
/// Incrementally strip non-contiguous data
|
||||
#[derive(Default, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StripStr {
|
||||
state: State,
|
||||
}
|
||||
|
||||
impl StripStr {
|
||||
/// Initial state
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Strip the next segment of data
|
||||
pub fn strip_next<'s>(&'s mut self, data: &'s str) -> StripStrIter<'s> {
|
||||
StripStrIter {
|
||||
bytes: data.as_bytes(),
|
||||
state: &mut self.state,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`StripStr`]
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct StripStrIter<'s> {
|
||||
bytes: &'s [u8],
|
||||
state: &'s mut State,
|
||||
}
|
||||
|
||||
impl<'s> Iterator for StripStrIter<'s> {
|
||||
type Item = &'s str;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
next_str(&mut self.bytes, self.state)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn next_str<'s>(bytes: &mut &'s [u8], state: &mut State) -> Option<&'s str> {
|
||||
let offset = bytes.iter().copied().position(|b| {
|
||||
let (next_state, action) = state_change(*state, b);
|
||||
if next_state != State::Anywhere {
|
||||
*state = next_state;
|
||||
}
|
||||
is_printable_bytes(action, b)
|
||||
});
|
||||
let (_, next) = bytes.split_at(offset.unwrap_or(bytes.len()));
|
||||
*bytes = next;
|
||||
*state = State::Ground;
|
||||
|
||||
let offset = bytes.iter().copied().position(|b| {
|
||||
let (_next_state, action) = state_change(State::Ground, b);
|
||||
!(is_printable_bytes(action, b) || is_utf8_continuation(b))
|
||||
});
|
||||
let (printable, next) = bytes.split_at(offset.unwrap_or(bytes.len()));
|
||||
*bytes = next;
|
||||
if printable.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let printable = unsafe {
|
||||
from_utf8_unchecked(
|
||||
printable,
|
||||
"`bytes` was validated as UTF-8, the parser preserves UTF-8 continuations",
|
||||
)
|
||||
};
|
||||
Some(printable)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn from_utf8_unchecked<'b>(bytes: &'b [u8], safety_justification: &'static str) -> &'b str {
|
||||
unsafe {
|
||||
if cfg!(debug_assertions) {
|
||||
// Catch problems more quickly when testing
|
||||
std::str::from_utf8(bytes).expect(safety_justification)
|
||||
} else {
|
||||
std::str::from_utf8_unchecked(bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_utf8_continuation(b: u8) -> bool {
|
||||
matches!(b, 0x80..=0xbf)
|
||||
}
|
||||
|
||||
/// Strip ANSI escapes from bytes, returning the printable content
|
||||
///
|
||||
/// This can be used to take output from a program that includes escape sequences and write it
|
||||
/// somewhere that does not easily support them, such as a log file.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use std::io::Write as _;
|
||||
///
|
||||
/// let styled_text = "\x1b[32mfoo\x1b[m bar";
|
||||
/// let plain_str = anstream::adapter::strip_bytes(styled_text.as_bytes()).into_vec();
|
||||
/// assert_eq!(plain_str.as_slice(), &b"foo bar"[..]);
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn strip_bytes(data: &[u8]) -> StrippedBytes<'_> {
|
||||
StrippedBytes::new(data)
|
||||
}
|
||||
|
||||
/// See [`strip_bytes`]
|
||||
#[derive(Default, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StrippedBytes<'s> {
|
||||
bytes: &'s [u8],
|
||||
state: State,
|
||||
utf8parser: Utf8Parser,
|
||||
}
|
||||
|
||||
impl<'s> StrippedBytes<'s> {
|
||||
/// See [`strip_bytes`]
|
||||
#[inline]
|
||||
pub fn new(bytes: &'s [u8]) -> Self {
|
||||
Self {
|
||||
bytes,
|
||||
state: State::Ground,
|
||||
utf8parser: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip the next slice of bytes
|
||||
///
|
||||
/// Used when the content is in several non-contiguous slices
|
||||
///
|
||||
/// # Panic
|
||||
///
|
||||
/// May panic if it is not exhausted / empty
|
||||
#[inline]
|
||||
pub fn extend(&mut self, bytes: &'s [u8]) {
|
||||
debug_assert!(
|
||||
self.is_empty(),
|
||||
"current bytes must be processed to ensure we end at the right state"
|
||||
);
|
||||
self.bytes = bytes;
|
||||
}
|
||||
|
||||
/// Report the bytes has been exhausted
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.bytes.is_empty()
|
||||
}
|
||||
|
||||
/// Create a [`Vec`] of the printable content
|
||||
#[inline]
|
||||
pub fn into_vec(self) -> Vec<u8> {
|
||||
let mut stripped = Vec::with_capacity(self.bytes.len());
|
||||
for printable in self {
|
||||
stripped.extend(printable);
|
||||
}
|
||||
stripped
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s> Iterator for StrippedBytes<'s> {
|
||||
type Item = &'s [u8];
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
next_bytes(&mut self.bytes, &mut self.state, &mut self.utf8parser)
|
||||
}
|
||||
}
|
||||
|
||||
/// Incrementally strip non-contiguous data
|
||||
#[derive(Default, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StripBytes {
|
||||
state: State,
|
||||
utf8parser: Utf8Parser,
|
||||
}
|
||||
|
||||
impl StripBytes {
|
||||
/// Initial state
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Strip the next segment of data
|
||||
pub fn strip_next<'s>(&'s mut self, bytes: &'s [u8]) -> StripBytesIter<'s> {
|
||||
StripBytesIter {
|
||||
bytes,
|
||||
state: &mut self.state,
|
||||
utf8parser: &mut self.utf8parser,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`StripBytes`]
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct StripBytesIter<'s> {
|
||||
bytes: &'s [u8],
|
||||
state: &'s mut State,
|
||||
utf8parser: &'s mut Utf8Parser,
|
||||
}
|
||||
|
||||
impl<'s> Iterator for StripBytesIter<'s> {
|
||||
type Item = &'s [u8];
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
next_bytes(&mut self.bytes, self.state, self.utf8parser)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn next_bytes<'s>(
|
||||
bytes: &mut &'s [u8],
|
||||
state: &mut State,
|
||||
utf8parser: &mut Utf8Parser,
|
||||
) -> Option<&'s [u8]> {
|
||||
let offset = bytes.iter().copied().position(|b| {
|
||||
if *state == State::Utf8 {
|
||||
true
|
||||
} else {
|
||||
let (next_state, action) = state_change(*state, b);
|
||||
if next_state != State::Anywhere {
|
||||
*state = next_state;
|
||||
}
|
||||
is_printable_bytes(action, b)
|
||||
}
|
||||
});
|
||||
let (_, next) = bytes.split_at(offset.unwrap_or(bytes.len()));
|
||||
*bytes = next;
|
||||
|
||||
let offset = bytes.iter().copied().position(|b| {
|
||||
if *state == State::Utf8 {
|
||||
if utf8parser.add(b) {
|
||||
*state = State::Ground;
|
||||
}
|
||||
false
|
||||
} else {
|
||||
let (next_state, action) = state_change(State::Ground, b);
|
||||
if next_state != State::Anywhere {
|
||||
*state = next_state;
|
||||
}
|
||||
if *state == State::Utf8 {
|
||||
utf8parser.add(b);
|
||||
false
|
||||
} else {
|
||||
!is_printable_bytes(action, b)
|
||||
}
|
||||
}
|
||||
});
|
||||
let (printable, next) = bytes.split_at(offset.unwrap_or(bytes.len()));
|
||||
*bytes = next;
|
||||
if printable.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(printable)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Utf8Parser {
|
||||
utf8_parser: utf8parse::Parser,
|
||||
}
|
||||
|
||||
impl Utf8Parser {
|
||||
fn add(&mut self, byte: u8) -> bool {
|
||||
let mut b = false;
|
||||
let mut receiver = VtUtf8Receiver(&mut b);
|
||||
self.utf8_parser.advance(&mut receiver, byte);
|
||||
b
|
||||
}
|
||||
}
|
||||
|
||||
struct VtUtf8Receiver<'a>(&'a mut bool);
|
||||
|
||||
impl utf8parse::Receiver for VtUtf8Receiver<'_> {
|
||||
fn codepoint(&mut self, _: char) {
|
||||
*self.0 = true;
|
||||
}
|
||||
|
||||
fn invalid_sequence(&mut self) {
|
||||
*self.0 = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_printable_bytes(action: Action, byte: u8) -> bool {
|
||||
// VT320 considered 0x7f to be `Print`able but we expect to be working in UTF-8 systems and not
|
||||
// ISO Latin-1, making it DEL and non-printable
|
||||
const DEL: u8 = 0x7f;
|
||||
|
||||
// Continuations aren't included as they may also be control codes, requiring more context
|
||||
(action == Action::Print && byte != DEL)
|
||||
|| action == Action::BeginUtf8
|
||||
|| (action == Action::Execute && byte.is_ascii_whitespace())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use proptest::prelude::*;
|
||||
|
||||
/// Model based off full parser
|
||||
fn parser_strip(bytes: &[u8]) -> String {
|
||||
#[derive(Default)]
|
||||
struct Strip(String);
|
||||
impl Strip {
|
||||
fn with_capacity(capacity: usize) -> Self {
|
||||
Self(String::with_capacity(capacity))
|
||||
}
|
||||
}
|
||||
impl anstyle_parse::Perform for Strip {
|
||||
fn print(&mut self, c: char) {
|
||||
self.0.push(c);
|
||||
}
|
||||
|
||||
fn execute(&mut self, byte: u8) {
|
||||
if byte.is_ascii_whitespace() {
|
||||
self.0.push(byte as char);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut stripped = Strip::with_capacity(bytes.len());
|
||||
let mut parser = anstyle_parse::Parser::<anstyle_parse::DefaultCharAccumulator>::new();
|
||||
for byte in bytes {
|
||||
parser.advance(&mut stripped, *byte);
|
||||
}
|
||||
stripped.0
|
||||
}
|
||||
|
||||
/// Model verifying incremental parsing
|
||||
fn strip_char(mut s: &str) -> String {
|
||||
let mut result = String::new();
|
||||
let mut state = StripStr::new();
|
||||
while !s.is_empty() {
|
||||
let mut indices = s.char_indices();
|
||||
indices.next(); // current
|
||||
let offset = indices.next().map(|(i, _)| i).unwrap_or_else(|| s.len());
|
||||
let (current, remainder) = s.split_at(offset);
|
||||
for printable in state.strip_next(current) {
|
||||
result.push_str(printable);
|
||||
}
|
||||
s = remainder;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Model verifying incremental parsing
|
||||
fn strip_byte(s: &[u8]) -> Vec<u8> {
|
||||
let mut result = Vec::new();
|
||||
let mut state = StripBytes::default();
|
||||
for start in 0..s.len() {
|
||||
let current = &s[start..=start];
|
||||
for printable in state.strip_next(current) {
|
||||
result.extend(printable);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_bytes_multibyte() {
|
||||
let bytes = [240, 145, 141, 139];
|
||||
let expected = parser_strip(&bytes);
|
||||
let actual = String::from_utf8(strip_bytes(&bytes).into_vec()).unwrap();
|
||||
assert_eq!(expected, actual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_byte_multibyte() {
|
||||
let bytes = [240, 145, 141, 139];
|
||||
let expected = parser_strip(&bytes);
|
||||
let actual = String::from_utf8(strip_byte(&bytes).clone()).unwrap();
|
||||
assert_eq!(expected, actual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_str_del() {
|
||||
let input = std::str::from_utf8(&[0x7f]).unwrap();
|
||||
let expected = "";
|
||||
let actual = strip_str(input).to_string();
|
||||
assert_eq!(expected, actual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_byte_del() {
|
||||
let bytes = [0x7f];
|
||||
let expected = "";
|
||||
let actual = String::from_utf8(strip_byte(&bytes).clone()).unwrap();
|
||||
assert_eq!(expected, actual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_str_handles_broken_sequence() {
|
||||
// valid utf8: \xc3\xb6 then \x1b then \xf0\x9f\x98\x80
|
||||
let s = "ö\x1b😀hello😀goodbye";
|
||||
let mut it = strip_str(s);
|
||||
assert_eq!("ö", it.next().unwrap());
|
||||
assert_eq!("ello😀goodbye", it.next().unwrap());
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn strip_str_no_escapes(s in "\\PC*") {
|
||||
let expected = parser_strip(s.as_bytes());
|
||||
let actual = strip_str(&s).to_string();
|
||||
assert_eq!(expected, actual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn strip_char_no_escapes(s in "\\PC*") {
|
||||
let expected = parser_strip(s.as_bytes());
|
||||
let actual = strip_char(&s);
|
||||
assert_eq!(expected, actual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn strip_bytes_no_escapes(s in "\\PC*") {
|
||||
dbg!(&s);
|
||||
dbg!(s.as_bytes());
|
||||
let expected = parser_strip(s.as_bytes());
|
||||
let actual = String::from_utf8(strip_bytes(s.as_bytes()).into_vec()).unwrap();
|
||||
assert_eq!(expected, actual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn strip_byte_no_escapes(s in "\\PC*") {
|
||||
dbg!(&s);
|
||||
dbg!(s.as_bytes());
|
||||
let expected = parser_strip(s.as_bytes());
|
||||
let actual = String::from_utf8(strip_byte(s.as_bytes()).clone()).unwrap();
|
||||
assert_eq!(expected, actual);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
/// Incrementally convert to wincon calls for non-contiguous data
|
||||
#[derive(Default, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct WinconBytes {
|
||||
parser: anstyle_parse::Parser,
|
||||
capture: WinconCapture,
|
||||
}
|
||||
|
||||
impl WinconBytes {
|
||||
/// Initial state
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Strip the next segment of data
|
||||
pub fn extract_next<'s>(&'s mut self, bytes: &'s [u8]) -> WinconBytesIter<'s> {
|
||||
self.capture.reset();
|
||||
self.capture.printable.reserve(bytes.len());
|
||||
WinconBytesIter {
|
||||
bytes,
|
||||
parser: &mut self.parser,
|
||||
capture: &mut self.capture,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`WinconBytes`]
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct WinconBytesIter<'s> {
|
||||
bytes: &'s [u8],
|
||||
parser: &'s mut anstyle_parse::Parser,
|
||||
capture: &'s mut WinconCapture,
|
||||
}
|
||||
|
||||
impl Iterator for WinconBytesIter<'_> {
|
||||
type Item = (anstyle::Style, String);
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
next_bytes(&mut self.bytes, self.parser, self.capture)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn next_bytes(
|
||||
bytes: &mut &[u8],
|
||||
parser: &mut anstyle_parse::Parser,
|
||||
capture: &mut WinconCapture,
|
||||
) -> Option<(anstyle::Style, String)> {
|
||||
capture.reset();
|
||||
while capture.ready.is_none() {
|
||||
let byte = if let Some((byte, remainder)) = (*bytes).split_first() {
|
||||
*bytes = remainder;
|
||||
*byte
|
||||
} else {
|
||||
break;
|
||||
};
|
||||
parser.advance(capture, byte);
|
||||
}
|
||||
if capture.printable.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let style = capture.ready.unwrap_or(capture.style);
|
||||
Some((style, std::mem::take(&mut capture.printable)))
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Debug, PartialEq, Eq)]
|
||||
struct WinconCapture {
|
||||
style: anstyle::Style,
|
||||
printable: String,
|
||||
ready: Option<anstyle::Style>,
|
||||
}
|
||||
|
||||
impl WinconCapture {
|
||||
fn reset(&mut self) {
|
||||
self.ready = None;
|
||||
}
|
||||
}
|
||||
|
||||
impl anstyle_parse::Perform for WinconCapture {
|
||||
/// Draw a character to the screen and update states.
|
||||
fn print(&mut self, c: char) {
|
||||
self.printable.push(c);
|
||||
}
|
||||
|
||||
/// Execute a C0 or C1 control function.
|
||||
fn execute(&mut self, byte: u8) {
|
||||
if byte.is_ascii_whitespace() {
|
||||
self.printable.push(byte as char);
|
||||
}
|
||||
}
|
||||
|
||||
fn csi_dispatch(
|
||||
&mut self,
|
||||
params: &anstyle_parse::Params,
|
||||
_intermediates: &[u8],
|
||||
ignore: bool,
|
||||
action: u8,
|
||||
) {
|
||||
if ignore {
|
||||
return;
|
||||
}
|
||||
if action != b'm' {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut style = self.style;
|
||||
// param/value differences are dependent on the escape code
|
||||
let mut state = CsiState::Normal;
|
||||
let mut r = None;
|
||||
let mut g = None;
|
||||
let mut color_target = ColorTarget::Fg;
|
||||
for param in params {
|
||||
for value in param {
|
||||
match (state, *value) {
|
||||
(CsiState::Normal, 0) => {
|
||||
style = anstyle::Style::default();
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 1) => {
|
||||
style = style.bold();
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 2) => {
|
||||
style = style.dimmed();
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 3) => {
|
||||
style = style.italic();
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 4) => {
|
||||
style = style.underline();
|
||||
state = CsiState::Underline;
|
||||
}
|
||||
(CsiState::Normal, 21) => {
|
||||
style |= anstyle::Effects::DOUBLE_UNDERLINE;
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 7) => {
|
||||
style = style.invert();
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 8) => {
|
||||
style = style.hidden();
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 9) => {
|
||||
style = style.strikethrough();
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 30..=37) => {
|
||||
let color = to_ansi_color(value - 30).expect("within 4-bit range");
|
||||
style = style.fg_color(Some(color.into()));
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 38) => {
|
||||
color_target = ColorTarget::Fg;
|
||||
state = CsiState::PrepareCustomColor;
|
||||
}
|
||||
(CsiState::Normal, 39) => {
|
||||
style = style.fg_color(None);
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 40..=47) => {
|
||||
let color = to_ansi_color(value - 40).expect("within 4-bit range");
|
||||
style = style.bg_color(Some(color.into()));
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 48) => {
|
||||
color_target = ColorTarget::Bg;
|
||||
state = CsiState::PrepareCustomColor;
|
||||
}
|
||||
(CsiState::Normal, 49) => {
|
||||
style = style.bg_color(None);
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 58) => {
|
||||
color_target = ColorTarget::Underline;
|
||||
state = CsiState::PrepareCustomColor;
|
||||
}
|
||||
(CsiState::Normal, 90..=97) => {
|
||||
let color = to_ansi_color(value - 90)
|
||||
.expect("within 4-bit range")
|
||||
.bright(true);
|
||||
style = style.fg_color(Some(color.into()));
|
||||
break;
|
||||
}
|
||||
(CsiState::Normal, 100..=107) => {
|
||||
let color = to_ansi_color(value - 100)
|
||||
.expect("within 4-bit range")
|
||||
.bright(true);
|
||||
style = style.bg_color(Some(color.into()));
|
||||
break;
|
||||
}
|
||||
(CsiState::PrepareCustomColor, 5) => {
|
||||
state = CsiState::Ansi256;
|
||||
}
|
||||
(CsiState::PrepareCustomColor, 2) => {
|
||||
state = CsiState::Rgb;
|
||||
r = None;
|
||||
g = None;
|
||||
}
|
||||
(CsiState::Ansi256, n) => {
|
||||
let color = anstyle::Ansi256Color(n as u8);
|
||||
style = match color_target {
|
||||
ColorTarget::Fg => style.fg_color(Some(color.into())),
|
||||
ColorTarget::Bg => style.bg_color(Some(color.into())),
|
||||
ColorTarget::Underline => style.underline_color(Some(color.into())),
|
||||
};
|
||||
break;
|
||||
}
|
||||
(CsiState::Rgb, b) => match (r, g) {
|
||||
(None, _) => {
|
||||
r = Some(b);
|
||||
}
|
||||
(Some(_), None) => {
|
||||
g = Some(b);
|
||||
}
|
||||
(Some(r), Some(g)) => {
|
||||
let color = anstyle::RgbColor(r as u8, g as u8, b as u8);
|
||||
style = match color_target {
|
||||
ColorTarget::Fg => style.fg_color(Some(color.into())),
|
||||
ColorTarget::Bg => style.bg_color(Some(color.into())),
|
||||
ColorTarget::Underline => style.underline_color(Some(color.into())),
|
||||
};
|
||||
break;
|
||||
}
|
||||
},
|
||||
(CsiState::Underline, 0) => {
|
||||
style =
|
||||
style.effects(style.get_effects().remove(anstyle::Effects::UNDERLINE));
|
||||
}
|
||||
(CsiState::Underline, 1) => {
|
||||
// underline already set
|
||||
}
|
||||
(CsiState::Underline, 2) => {
|
||||
style = style
|
||||
.effects(style.get_effects().remove(anstyle::Effects::UNDERLINE))
|
||||
| anstyle::Effects::DOUBLE_UNDERLINE;
|
||||
}
|
||||
(CsiState::Underline, 3) => {
|
||||
style = style
|
||||
.effects(style.get_effects().remove(anstyle::Effects::UNDERLINE))
|
||||
| anstyle::Effects::CURLY_UNDERLINE;
|
||||
}
|
||||
(CsiState::Underline, 4) => {
|
||||
style = style
|
||||
.effects(style.get_effects().remove(anstyle::Effects::UNDERLINE))
|
||||
| anstyle::Effects::DOTTED_UNDERLINE;
|
||||
}
|
||||
(CsiState::Underline, 5) => {
|
||||
style = style
|
||||
.effects(style.get_effects().remove(anstyle::Effects::UNDERLINE))
|
||||
| anstyle::Effects::DASHED_UNDERLINE;
|
||||
}
|
||||
_ => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if style != self.style && !self.printable.is_empty() {
|
||||
self.ready = Some(self.style);
|
||||
}
|
||||
self.style = style;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
enum CsiState {
|
||||
Normal,
|
||||
PrepareCustomColor,
|
||||
Ansi256,
|
||||
Rgb,
|
||||
Underline,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
enum ColorTarget {
|
||||
Fg,
|
||||
Bg,
|
||||
Underline,
|
||||
}
|
||||
|
||||
fn to_ansi_color(digit: u16) -> Option<anstyle::AnsiColor> {
|
||||
match digit {
|
||||
0 => Some(anstyle::AnsiColor::Black),
|
||||
1 => Some(anstyle::AnsiColor::Red),
|
||||
2 => Some(anstyle::AnsiColor::Green),
|
||||
3 => Some(anstyle::AnsiColor::Yellow),
|
||||
4 => Some(anstyle::AnsiColor::Blue),
|
||||
5 => Some(anstyle::AnsiColor::Magenta),
|
||||
6 => Some(anstyle::AnsiColor::Cyan),
|
||||
7 => Some(anstyle::AnsiColor::White),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use proptest::prelude::*;
|
||||
|
||||
#[track_caller]
|
||||
fn verify(input: &str, expected: Vec<(anstyle::Style, &str)>) {
|
||||
let expected = expected
|
||||
.into_iter()
|
||||
.map(|(style, value)| (style, value.to_owned()))
|
||||
.collect::<Vec<_>>();
|
||||
let mut state = WinconBytes::new();
|
||||
let actual = state.extract_next(input.as_bytes()).collect::<Vec<_>>();
|
||||
assert_eq!(expected, actual, "{input:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start() {
|
||||
let green_on_red = anstyle::AnsiColor::Green.on(anstyle::AnsiColor::Red);
|
||||
let input = format!("{green_on_red}Hello{green_on_red:#} world!");
|
||||
let expected = vec![
|
||||
(green_on_red, "Hello"),
|
||||
(anstyle::Style::default(), " world!"),
|
||||
];
|
||||
verify(&input, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn middle() {
|
||||
let green_on_red = anstyle::AnsiColor::Green.on(anstyle::AnsiColor::Red);
|
||||
let input = format!("Hello {green_on_red}world{green_on_red:#}!");
|
||||
let expected = vec![
|
||||
(anstyle::Style::default(), "Hello "),
|
||||
(green_on_red, "world"),
|
||||
(anstyle::Style::default(), "!"),
|
||||
];
|
||||
verify(&input, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end() {
|
||||
let green_on_red = anstyle::AnsiColor::Green.on(anstyle::AnsiColor::Red);
|
||||
let input = format!("Hello {green_on_red}world!{green_on_red:#}");
|
||||
let expected = vec![
|
||||
(anstyle::Style::default(), "Hello "),
|
||||
(green_on_red, "world!"),
|
||||
];
|
||||
verify(&input, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ansi256_colors() {
|
||||
let ansi_11 = anstyle::Ansi256Color(11).on_default();
|
||||
// termcolor only supports "brights" via these
|
||||
let input = format!("Hello {ansi_11}world{ansi_11:#}!");
|
||||
let expected = vec![
|
||||
(anstyle::Style::default(), "Hello "),
|
||||
(ansi_11, "world"),
|
||||
(anstyle::Style::default(), "!"),
|
||||
];
|
||||
verify(&input, expected);
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn wincon_no_escapes(s in "\\PC*") {
|
||||
let expected = if s.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
vec![(anstyle::Style::default(), s.clone())]
|
||||
};
|
||||
let mut state = WinconBytes::new();
|
||||
let actual = state.extract_next(s.as_bytes()).collect::<Vec<_>>();
|
||||
assert_eq!(expected, actual);
|
||||
}
|
||||
}
|
||||
}
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
use crate::stream::AsLockedWrite;
|
||||
use crate::stream::RawStream;
|
||||
use crate::ColorChoice;
|
||||
use crate::StripStream;
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
use crate::WinconStream;
|
||||
|
||||
/// [`std::io::Write`] that adapts ANSI escape codes to the underlying `Write`s capabilities
|
||||
///
|
||||
/// This includes
|
||||
/// - Stripping colors for non-terminals
|
||||
/// - Respecting env variables like [NO_COLOR](https://no-color.org/) or [CLICOLOR](https://bixense.com/clicolors/)
|
||||
/// - *(windows)* Falling back to the wincon API where [ENABLE_VIRTUAL_TERMINAL_PROCESSING](https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#output-sequences) is unsupported
|
||||
///
|
||||
/// You can customize auto-detection by calling into
|
||||
/// [anstyle_query](https://docs.rs/anstyle-query/latest/anstyle_query/)
|
||||
/// to get a [`ColorChoice`] and then calling [`AutoStream::new(stream, choice)`].
|
||||
#[derive(Debug)]
|
||||
pub struct AutoStream<S: RawStream> {
|
||||
inner: StreamInner<S>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum StreamInner<S: RawStream> {
|
||||
PassThrough(S),
|
||||
Strip(StripStream<S>),
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
Wincon(WinconStream<S>),
|
||||
}
|
||||
|
||||
impl<S> AutoStream<S>
|
||||
where
|
||||
S: RawStream,
|
||||
{
|
||||
/// Runtime control over styling behavior
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// # #[cfg(feature = "auto")] {
|
||||
/// # use std::io::IsTerminal as _;
|
||||
/// // Like `AutoStream::choice` but without `NO_COLOR`, `CLICOLOR_FORCE`, `CI`
|
||||
/// fn choice(raw: &dyn anstream::stream::RawStream) -> anstream::ColorChoice {
|
||||
/// let choice = anstream::ColorChoice::global();
|
||||
/// if choice == anstream::ColorChoice::Auto {
|
||||
/// if raw.is_terminal() && anstyle_query::term_supports_color() {
|
||||
/// anstream::ColorChoice::Always
|
||||
/// } else {
|
||||
/// anstream::ColorChoice::Never
|
||||
/// }
|
||||
/// } else {
|
||||
/// choice
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let stream = std::io::stdout();
|
||||
/// let choice = choice(&stream);
|
||||
/// let auto = anstream::AutoStream::new(stream, choice);
|
||||
/// # }
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn new(raw: S, choice: ColorChoice) -> Self {
|
||||
match choice {
|
||||
#[cfg(feature = "auto")]
|
||||
ColorChoice::Auto => Self::auto(raw),
|
||||
#[cfg(not(feature = "auto"))]
|
||||
ColorChoice::Auto => Self::never(raw),
|
||||
ColorChoice::AlwaysAnsi => Self::always_ansi(raw),
|
||||
ColorChoice::Always => Self::always(raw),
|
||||
ColorChoice::Never => Self::never(raw),
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto-adapt for the stream's capabilities
|
||||
#[cfg(feature = "auto")]
|
||||
#[inline]
|
||||
pub fn auto(raw: S) -> Self {
|
||||
let choice = Self::choice(&raw);
|
||||
debug_assert_ne!(choice, ColorChoice::Auto);
|
||||
Self::new(raw, choice)
|
||||
}
|
||||
|
||||
/// Report the desired choice for the given stream
|
||||
#[cfg(feature = "auto")]
|
||||
pub fn choice(raw: &S) -> ColorChoice {
|
||||
choice(raw)
|
||||
}
|
||||
|
||||
/// Force ANSI escape codes to be passed through as-is, no matter what the inner `Write`
|
||||
/// supports.
|
||||
#[inline]
|
||||
pub fn always_ansi(raw: S) -> Self {
|
||||
#[cfg(feature = "auto")]
|
||||
{
|
||||
if raw.is_terminal() {
|
||||
let _ = anstyle_query::windows::enable_ansi_colors();
|
||||
}
|
||||
}
|
||||
Self::always_ansi_(raw)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn always_ansi_(raw: S) -> Self {
|
||||
let inner = StreamInner::PassThrough(raw);
|
||||
AutoStream { inner }
|
||||
}
|
||||
|
||||
/// Force color, no matter what the inner `Write` supports.
|
||||
#[inline]
|
||||
pub fn always(raw: S) -> Self {
|
||||
if cfg!(windows) {
|
||||
#[cfg(feature = "auto")]
|
||||
let use_wincon = raw.is_terminal()
|
||||
&& !anstyle_query::windows::enable_ansi_colors().unwrap_or(true)
|
||||
&& !anstyle_query::term_supports_ansi_color();
|
||||
#[cfg(not(feature = "auto"))]
|
||||
let use_wincon = true;
|
||||
if use_wincon {
|
||||
Self::wincon(raw).unwrap_or_else(|raw| Self::always_ansi_(raw))
|
||||
} else {
|
||||
Self::always_ansi_(raw)
|
||||
}
|
||||
} else {
|
||||
Self::always_ansi(raw)
|
||||
}
|
||||
}
|
||||
|
||||
/// Only pass printable data to the inner `Write`.
|
||||
#[inline]
|
||||
pub fn never(raw: S) -> Self {
|
||||
let inner = StreamInner::Strip(StripStream::new(raw));
|
||||
AutoStream { inner }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn wincon(raw: S) -> Result<Self, S> {
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
{
|
||||
Ok(Self {
|
||||
inner: StreamInner::Wincon(WinconStream::new(raw)),
|
||||
})
|
||||
}
|
||||
#[cfg(not(all(windows, feature = "wincon")))]
|
||||
{
|
||||
Err(raw)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the wrapped [`RawStream`]
|
||||
#[inline]
|
||||
pub fn into_inner(self) -> S {
|
||||
match self.inner {
|
||||
StreamInner::PassThrough(w) => w,
|
||||
StreamInner::Strip(w) => w.into_inner(),
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
StreamInner::Wincon(w) => w.into_inner(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the wrapped [`RawStream`]
|
||||
#[inline]
|
||||
pub fn as_inner(&self) -> &S {
|
||||
match &self.inner {
|
||||
StreamInner::PassThrough(w) => w,
|
||||
StreamInner::Strip(w) => w.as_inner(),
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
StreamInner::Wincon(w) => w.as_inner(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if the descriptor/handle refers to a terminal/tty.
|
||||
#[inline]
|
||||
pub fn is_terminal(&self) -> bool {
|
||||
match &self.inner {
|
||||
StreamInner::PassThrough(w) => w.is_terminal(),
|
||||
StreamInner::Strip(w) => w.is_terminal(),
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
StreamInner::Wincon(_) => true, // its only ever a terminal
|
||||
}
|
||||
}
|
||||
|
||||
/// Prefer [`AutoStream::choice`]
|
||||
///
|
||||
/// This doesn't report what is requested but what is currently active.
|
||||
#[inline]
|
||||
#[cfg(feature = "auto")]
|
||||
pub fn current_choice(&self) -> ColorChoice {
|
||||
match &self.inner {
|
||||
StreamInner::PassThrough(_) => ColorChoice::AlwaysAnsi,
|
||||
StreamInner::Strip(_) => ColorChoice::Never,
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
StreamInner::Wincon(_) => ColorChoice::Always,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "auto")]
|
||||
fn choice(raw: &dyn RawStream) -> ColorChoice {
|
||||
let choice = ColorChoice::global();
|
||||
match choice {
|
||||
ColorChoice::Auto => {
|
||||
let clicolor = anstyle_query::clicolor();
|
||||
let clicolor_enabled = clicolor.unwrap_or(false);
|
||||
let clicolor_disabled = !clicolor.unwrap_or(true);
|
||||
if anstyle_query::no_color() {
|
||||
ColorChoice::Never
|
||||
} else if anstyle_query::clicolor_force() {
|
||||
ColorChoice::Always
|
||||
} else if clicolor_disabled {
|
||||
ColorChoice::Never
|
||||
} else if raw.is_terminal()
|
||||
&& (anstyle_query::term_supports_color()
|
||||
|| clicolor_enabled
|
||||
|| anstyle_query::is_ci())
|
||||
{
|
||||
ColorChoice::Always
|
||||
} else {
|
||||
ColorChoice::Never
|
||||
}
|
||||
}
|
||||
ColorChoice::AlwaysAnsi | ColorChoice::Always | ColorChoice::Never => choice,
|
||||
}
|
||||
}
|
||||
|
||||
impl AutoStream<std::io::Stdout> {
|
||||
/// Get exclusive access to the `AutoStream`
|
||||
///
|
||||
/// Why?
|
||||
/// - Faster performance when writing in a loop
|
||||
/// - Avoid other threads interleaving output with the current thread
|
||||
#[inline]
|
||||
pub fn lock(self) -> AutoStream<std::io::StdoutLock<'static>> {
|
||||
let inner = match self.inner {
|
||||
StreamInner::PassThrough(w) => StreamInner::PassThrough(w.lock()),
|
||||
StreamInner::Strip(w) => StreamInner::Strip(w.lock()),
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
StreamInner::Wincon(w) => StreamInner::Wincon(w.lock()),
|
||||
};
|
||||
AutoStream { inner }
|
||||
}
|
||||
}
|
||||
|
||||
impl AutoStream<std::io::Stderr> {
|
||||
/// Get exclusive access to the `AutoStream`
|
||||
///
|
||||
/// Why?
|
||||
/// - Faster performance when writing in a loop
|
||||
/// - Avoid other threads interleaving output with the current thread
|
||||
#[inline]
|
||||
pub fn lock(self) -> AutoStream<std::io::StderrLock<'static>> {
|
||||
let inner = match self.inner {
|
||||
StreamInner::PassThrough(w) => StreamInner::PassThrough(w.lock()),
|
||||
StreamInner::Strip(w) => StreamInner::Strip(w.lock()),
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
StreamInner::Wincon(w) => StreamInner::Wincon(w.lock()),
|
||||
};
|
||||
AutoStream { inner }
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> std::io::Write for AutoStream<S>
|
||||
where
|
||||
S: RawStream + AsLockedWrite,
|
||||
{
|
||||
// Must forward all calls to ensure locking happens appropriately
|
||||
#[inline]
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
match &mut self.inner {
|
||||
StreamInner::PassThrough(w) => w.as_locked_write().write(buf),
|
||||
StreamInner::Strip(w) => w.write(buf),
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
StreamInner::Wincon(w) => w.write(buf),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result<usize> {
|
||||
match &mut self.inner {
|
||||
StreamInner::PassThrough(w) => w.as_locked_write().write_vectored(bufs),
|
||||
StreamInner::Strip(w) => w.write_vectored(bufs),
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
StreamInner::Wincon(w) => w.write_vectored(bufs),
|
||||
}
|
||||
}
|
||||
// is_write_vectored: nightly only
|
||||
#[inline]
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
match &mut self.inner {
|
||||
StreamInner::PassThrough(w) => w.as_locked_write().flush(),
|
||||
StreamInner::Strip(w) => w.flush(),
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
StreamInner::Wincon(w) => w.flush(),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
|
||||
match &mut self.inner {
|
||||
StreamInner::PassThrough(w) => w.as_locked_write().write_all(buf),
|
||||
StreamInner::Strip(w) => w.write_all(buf),
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
StreamInner::Wincon(w) => w.write_all(buf),
|
||||
}
|
||||
}
|
||||
// write_all_vectored: nightly only
|
||||
#[inline]
|
||||
fn write_fmt(&mut self, args: std::fmt::Arguments<'_>) -> std::io::Result<()> {
|
||||
match &mut self.inner {
|
||||
StreamInner::PassThrough(w) => w.as_locked_write().write_fmt(args),
|
||||
StreamInner::Strip(w) => w.write_fmt(args),
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
StreamInner::Wincon(w) => w.write_fmt(args),
|
||||
}
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
#![allow(deprecated)]
|
||||
|
||||
/// In-memory [`RawStream`][crate::stream::RawStream]
|
||||
#[derive(Clone, Default, Debug, PartialEq, Eq)]
|
||||
#[deprecated(since = "0.6.2", note = "Use Vec")]
|
||||
#[doc(hidden)]
|
||||
pub struct Buffer(Vec<u8>);
|
||||
|
||||
impl Buffer {
|
||||
#[inline]
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn with_capacity(capacity: usize) -> Self {
|
||||
Self(Vec::with_capacity(capacity))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn as_bytes(&self) -> &[u8] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for Buffer {
|
||||
#[inline]
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
self.as_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Write for Buffer {
|
||||
#[inline]
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.extend(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
impl anstyle_wincon::WinconStream for Buffer {
|
||||
fn write_colored(
|
||||
&mut self,
|
||||
fg: Option<anstyle::AnsiColor>,
|
||||
bg: Option<anstyle::AnsiColor>,
|
||||
data: &[u8],
|
||||
) -> std::io::Result<usize> {
|
||||
self.0.write_colored(fg, bg, data)
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/// A shim which allows a [`std::io::Write`] to be implemented in terms of a [`std::fmt::Write`]
|
||||
///
|
||||
/// This saves off I/O errors. instead of discarding them
|
||||
pub(crate) struct Adapter<W>
|
||||
where
|
||||
W: FnMut(&[u8]) -> std::io::Result<()>,
|
||||
{
|
||||
writer: W,
|
||||
error: std::io::Result<()>,
|
||||
}
|
||||
|
||||
impl<W> Adapter<W>
|
||||
where
|
||||
W: FnMut(&[u8]) -> std::io::Result<()>,
|
||||
{
|
||||
pub(crate) fn new(writer: W) -> Self {
|
||||
Adapter {
|
||||
writer,
|
||||
error: Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_fmt(mut self, fmt: std::fmt::Arguments<'_>) -> std::io::Result<()> {
|
||||
match std::fmt::write(&mut self, fmt) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(..) => {
|
||||
// check if the error came from the underlying `Write` or not
|
||||
if self.error.is_err() {
|
||||
self.error
|
||||
} else {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
"formatter error",
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W> std::fmt::Write for Adapter<W>
|
||||
where
|
||||
W: FnMut(&[u8]) -> std::io::Result<()>,
|
||||
{
|
||||
fn write_str(&mut self, s: &str) -> std::fmt::Result {
|
||||
match (self.writer)(s.as_bytes()) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
self.error = Err(e);
|
||||
Err(std::fmt::Error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
//! **Auto-adapting [`stdout`] / [`stderr`] streams**
|
||||
//!
|
||||
//! *A portmanteau of "ansi stream"*
|
||||
//!
|
||||
//! [`AutoStream`] always accepts [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code),
|
||||
//! [adapting to the user's terminal's capabilities][AutoStream].
|
||||
//!
|
||||
//! Benefits
|
||||
//! - Allows the caller to not be concerned with the terminal's capabilities
|
||||
//! - Semver safe way of passing styled text between crates as ANSI escape codes offer more
|
||||
//! compatibility than most crate APIs.
|
||||
//!
|
||||
//! Available styling crates:
|
||||
//! - [anstyle](https://docs.rs/anstyle) for minimal runtime styling, designed to go in public APIs
|
||||
//! - [owo-colors](https://docs.rs/owo-colors) for feature-rich runtime styling
|
||||
//! - [color-print](https://docs.rs/color-print) for feature-rich compile-time styling
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "auto")] {
|
||||
//! use anstream::println;
|
||||
//! use owo_colors::OwoColorize as _;
|
||||
//!
|
||||
//! // Foreground colors
|
||||
//! println!("My number is {:#x}!", 10.green());
|
||||
//! // Background colors
|
||||
//! println!("My number is not {}!", 4.on_red());
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! And this will correctly handle piping to a file, etc
|
||||
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
#![warn(missing_docs)]
|
||||
#![warn(clippy::print_stderr)]
|
||||
#![warn(clippy::print_stdout)]
|
||||
|
||||
pub mod adapter;
|
||||
pub mod stream;
|
||||
#[doc(hidden)]
|
||||
#[macro_use]
|
||||
pub mod _macros;
|
||||
|
||||
mod auto;
|
||||
mod buffer;
|
||||
mod fmt;
|
||||
mod strip;
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
mod wincon;
|
||||
|
||||
pub use auto::AutoStream;
|
||||
pub use strip::StripStream;
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
pub use wincon::WinconStream;
|
||||
|
||||
#[allow(deprecated)]
|
||||
pub use buffer::Buffer;
|
||||
|
||||
/// An adaptive wrapper around the global standard output stream of the current process
|
||||
pub type Stdout = AutoStream<std::io::Stdout>;
|
||||
/// An adaptive wrapper around the global standard error stream of the current process
|
||||
pub type Stderr = AutoStream<std::io::Stderr>;
|
||||
|
||||
/// Create an ANSI escape code compatible stdout
|
||||
///
|
||||
/// **Note:** Call [`AutoStream::lock`] in loops to avoid the performance hit of acquiring/releasing
|
||||
/// from the implicit locking in each [`std::io::Write`] call
|
||||
#[cfg(feature = "auto")]
|
||||
pub fn stdout() -> Stdout {
|
||||
let stdout = std::io::stdout();
|
||||
AutoStream::auto(stdout)
|
||||
}
|
||||
|
||||
/// Create an ANSI escape code compatible stderr
|
||||
///
|
||||
/// **Note:** Call [`AutoStream::lock`] in loops to avoid the performance hit of acquiring/releasing
|
||||
/// from the implicit locking in each [`std::io::Write`] call
|
||||
#[cfg(feature = "auto")]
|
||||
pub fn stderr() -> Stderr {
|
||||
let stderr = std::io::stderr();
|
||||
AutoStream::auto(stderr)
|
||||
}
|
||||
|
||||
/// Selection for overriding color output
|
||||
pub use colorchoice::ColorChoice;
|
||||
|
||||
#[doc = include_str!("../README.md")]
|
||||
#[cfg(doctest)]
|
||||
pub struct ReadmeDoctests;
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
//! Higher-level traits to describe writeable streams
|
||||
|
||||
/// Required functionality for underlying [`std::io::Write`] for adaptation
|
||||
#[cfg(not(all(windows, feature = "wincon")))]
|
||||
pub trait RawStream: std::io::Write + IsTerminal + private::Sealed {}
|
||||
|
||||
/// Required functionality for underlying [`std::io::Write`] for adaptation
|
||||
#[cfg(all(windows, feature = "wincon"))]
|
||||
pub trait RawStream:
|
||||
std::io::Write + IsTerminal + anstyle_wincon::WinconStream + private::Sealed
|
||||
{
|
||||
}
|
||||
|
||||
impl<T: RawStream + ?Sized> RawStream for &mut T {}
|
||||
impl<T: RawStream + ?Sized> RawStream for Box<T> {}
|
||||
|
||||
impl RawStream for std::io::Stdout {}
|
||||
|
||||
impl RawStream for std::io::StdoutLock<'_> {}
|
||||
|
||||
impl RawStream for std::io::Stderr {}
|
||||
|
||||
impl RawStream for std::io::StderrLock<'_> {}
|
||||
|
||||
impl RawStream for dyn std::io::Write {}
|
||||
impl RawStream for dyn std::io::Write + Send {}
|
||||
impl RawStream for dyn std::io::Write + Send + Sync {}
|
||||
|
||||
impl RawStream for Vec<u8> {}
|
||||
|
||||
impl RawStream for std::fs::File {}
|
||||
|
||||
#[allow(deprecated)]
|
||||
impl RawStream for crate::Buffer {}
|
||||
|
||||
/// Trait to determine if a descriptor/handle refers to a terminal/tty.
|
||||
pub trait IsTerminal: private::Sealed {
|
||||
/// Returns `true` if the descriptor/handle refers to a terminal/tty.
|
||||
fn is_terminal(&self) -> bool;
|
||||
}
|
||||
|
||||
impl<T: IsTerminal + ?Sized> IsTerminal for &T {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
(**self).is_terminal()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: IsTerminal + ?Sized> IsTerminal for &mut T {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
(**self).is_terminal()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: IsTerminal + ?Sized> IsTerminal for Box<T> {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
(**self).is_terminal()
|
||||
}
|
||||
}
|
||||
|
||||
impl IsTerminal for std::io::Stdout {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
is_terminal_polyfill::IsTerminal::is_terminal(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl IsTerminal for std::io::StdoutLock<'_> {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
is_terminal_polyfill::IsTerminal::is_terminal(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl IsTerminal for std::io::Stderr {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
is_terminal_polyfill::IsTerminal::is_terminal(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl IsTerminal for std::io::StderrLock<'_> {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
is_terminal_polyfill::IsTerminal::is_terminal(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl IsTerminal for dyn std::io::Write {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl IsTerminal for dyn std::io::Write + Send {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl IsTerminal for dyn std::io::Write + Send + Sync {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl IsTerminal for Vec<u8> {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl IsTerminal for std::fs::File {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
is_terminal_polyfill::IsTerminal::is_terminal(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
impl IsTerminal for crate::Buffer {
|
||||
#[inline]
|
||||
fn is_terminal(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Lock a stream
|
||||
pub trait AsLockedWrite: private::Sealed {
|
||||
/// Locked writer type
|
||||
type Write<'w>: RawStream + 'w
|
||||
where
|
||||
Self: 'w;
|
||||
|
||||
/// Lock a stream
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_>;
|
||||
}
|
||||
|
||||
impl<T: AsLockedWrite + ?Sized> AsLockedWrite for &mut T {
|
||||
type Write<'w>
|
||||
= T::Write<'w>
|
||||
where
|
||||
Self: 'w;
|
||||
|
||||
#[inline]
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_> {
|
||||
(**self).as_locked_write()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsLockedWrite + ?Sized> AsLockedWrite for Box<T> {
|
||||
type Write<'w>
|
||||
= T::Write<'w>
|
||||
where
|
||||
Self: 'w;
|
||||
|
||||
#[inline]
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_> {
|
||||
(**self).as_locked_write()
|
||||
}
|
||||
}
|
||||
|
||||
impl AsLockedWrite for std::io::Stdout {
|
||||
type Write<'w> = std::io::StdoutLock<'w>;
|
||||
|
||||
#[inline]
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_> {
|
||||
self.lock()
|
||||
}
|
||||
}
|
||||
|
||||
impl AsLockedWrite for std::io::StdoutLock<'static> {
|
||||
type Write<'w> = &'w mut Self;
|
||||
|
||||
#[inline]
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl AsLockedWrite for std::io::Stderr {
|
||||
type Write<'w> = std::io::StderrLock<'w>;
|
||||
|
||||
#[inline]
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_> {
|
||||
self.lock()
|
||||
}
|
||||
}
|
||||
|
||||
impl AsLockedWrite for std::io::StderrLock<'static> {
|
||||
type Write<'w> = &'w mut Self;
|
||||
|
||||
#[inline]
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl AsLockedWrite for dyn std::io::Write {
|
||||
type Write<'w> = &'w mut Self;
|
||||
|
||||
#[inline]
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl AsLockedWrite for dyn std::io::Write + Send {
|
||||
type Write<'w> = &'w mut Self;
|
||||
|
||||
#[inline]
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl AsLockedWrite for dyn std::io::Write + Send + Sync {
|
||||
type Write<'w> = &'w mut Self;
|
||||
|
||||
#[inline]
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl AsLockedWrite for Vec<u8> {
|
||||
type Write<'w> = &'w mut Self;
|
||||
|
||||
#[inline]
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl AsLockedWrite for std::fs::File {
|
||||
type Write<'w> = &'w mut Self;
|
||||
|
||||
#[inline]
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
impl AsLockedWrite for crate::Buffer {
|
||||
type Write<'w> = &'w mut Self;
|
||||
|
||||
#[inline]
|
||||
fn as_locked_write(&mut self) -> Self::Write<'_> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
mod private {
|
||||
#[allow(unnameable_types)]
|
||||
pub trait Sealed {}
|
||||
|
||||
impl<T: Sealed + ?Sized> Sealed for &T {}
|
||||
impl<T: Sealed + ?Sized> Sealed for &mut T {}
|
||||
impl<T: Sealed + ?Sized> Sealed for Box<T> {}
|
||||
|
||||
impl Sealed for std::io::Stdout {}
|
||||
|
||||
impl Sealed for std::io::StdoutLock<'_> {}
|
||||
|
||||
impl Sealed for std::io::Stderr {}
|
||||
|
||||
impl Sealed for std::io::StderrLock<'_> {}
|
||||
|
||||
impl Sealed for dyn std::io::Write {}
|
||||
impl Sealed for dyn std::io::Write + Send {}
|
||||
impl Sealed for dyn std::io::Write + Send + Sync {}
|
||||
|
||||
impl Sealed for Vec<u8> {}
|
||||
|
||||
impl Sealed for std::fs::File {}
|
||||
|
||||
#[allow(deprecated)]
|
||||
impl Sealed for crate::Buffer {}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn assert_raw_stream<T: RawStream>()
|
||||
where
|
||||
crate::AutoStream<T>: std::io::Write,
|
||||
{
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test() {
|
||||
assert_raw_stream::<Box<dyn std::io::Write>>();
|
||||
assert_raw_stream::<Box<dyn std::io::Write + 'static>>();
|
||||
assert_raw_stream::<Box<dyn std::io::Write + Send>>();
|
||||
assert_raw_stream::<Box<dyn std::io::Write + Send + Sync>>();
|
||||
|
||||
assert_raw_stream::<&mut dyn std::io::Write>();
|
||||
assert_raw_stream::<&mut (dyn std::io::Write + 'static)>();
|
||||
assert_raw_stream::<&mut (dyn std::io::Write + Send)>();
|
||||
assert_raw_stream::<&mut (dyn std::io::Write + Send + Sync)>();
|
||||
|
||||
assert_raw_stream::<Vec<u8>>();
|
||||
assert_raw_stream::<&mut Vec<u8>>();
|
||||
|
||||
assert_raw_stream::<std::fs::File>();
|
||||
assert_raw_stream::<&mut std::fs::File>();
|
||||
}
|
||||
}
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
use crate::adapter::StripBytes;
|
||||
use crate::stream::AsLockedWrite;
|
||||
use crate::stream::IsTerminal;
|
||||
|
||||
/// Only pass printable data to the inner `Write`
|
||||
#[derive(Debug)]
|
||||
pub struct StripStream<S>
|
||||
where
|
||||
S: std::io::Write,
|
||||
{
|
||||
raw: S,
|
||||
state: StripBytes,
|
||||
}
|
||||
|
||||
impl<S> StripStream<S>
|
||||
where
|
||||
S: std::io::Write,
|
||||
{
|
||||
/// Only pass printable data to the inner `Write`
|
||||
#[inline]
|
||||
pub fn new(raw: S) -> Self {
|
||||
Self {
|
||||
raw,
|
||||
state: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the wrapped [`std::io::Write`]
|
||||
#[inline]
|
||||
pub fn into_inner(self) -> S {
|
||||
self.raw
|
||||
}
|
||||
|
||||
/// Get the wrapped [`std::io::Write`]
|
||||
#[inline]
|
||||
pub fn as_inner(&self) -> &S {
|
||||
&self.raw
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> StripStream<S>
|
||||
where
|
||||
S: std::io::Write,
|
||||
S: IsTerminal,
|
||||
{
|
||||
/// Returns `true` if the descriptor/handle refers to a terminal/tty.
|
||||
#[inline]
|
||||
pub fn is_terminal(&self) -> bool {
|
||||
self.raw.is_terminal()
|
||||
}
|
||||
}
|
||||
|
||||
impl StripStream<std::io::Stdout> {
|
||||
/// Get exclusive access to the `StripStream`
|
||||
///
|
||||
/// Why?
|
||||
/// - Faster performance when writing in a loop
|
||||
/// - Avoid other threads interleaving output with the current thread
|
||||
#[inline]
|
||||
pub fn lock(self) -> StripStream<std::io::StdoutLock<'static>> {
|
||||
StripStream {
|
||||
raw: self.raw.lock(),
|
||||
state: self.state,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StripStream<std::io::Stderr> {
|
||||
/// Get exclusive access to the `StripStream`
|
||||
///
|
||||
/// Why?
|
||||
/// - Faster performance when writing in a loop
|
||||
/// - Avoid other threads interleaving output with the current thread
|
||||
#[inline]
|
||||
pub fn lock(self) -> StripStream<std::io::StderrLock<'static>> {
|
||||
StripStream {
|
||||
raw: self.raw.lock(),
|
||||
state: self.state,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> std::io::Write for StripStream<S>
|
||||
where
|
||||
S: std::io::Write,
|
||||
S: AsLockedWrite,
|
||||
{
|
||||
// Must forward all calls to ensure locking happens appropriately
|
||||
#[inline]
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
write(&mut self.raw.as_locked_write(), &mut self.state, buf)
|
||||
}
|
||||
#[inline]
|
||||
fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result<usize> {
|
||||
let buf = bufs
|
||||
.iter()
|
||||
.find(|b| !b.is_empty())
|
||||
.map(|b| &**b)
|
||||
.unwrap_or(&[][..]);
|
||||
self.write(buf)
|
||||
}
|
||||
// is_write_vectored: nightly only
|
||||
#[inline]
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.raw.as_locked_write().flush()
|
||||
}
|
||||
#[inline]
|
||||
fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
|
||||
write_all(&mut self.raw.as_locked_write(), &mut self.state, buf)
|
||||
}
|
||||
// write_all_vectored: nightly only
|
||||
#[inline]
|
||||
fn write_fmt(&mut self, args: std::fmt::Arguments<'_>) -> std::io::Result<()> {
|
||||
write_fmt(&mut self.raw.as_locked_write(), &mut self.state, args)
|
||||
}
|
||||
}
|
||||
|
||||
fn write(
|
||||
raw: &mut dyn std::io::Write,
|
||||
state: &mut StripBytes,
|
||||
buf: &[u8],
|
||||
) -> std::io::Result<usize> {
|
||||
let initial_state = state.clone();
|
||||
|
||||
for printable in state.strip_next(buf) {
|
||||
let possible = printable.len();
|
||||
let written = raw.write(printable)?;
|
||||
if possible != written {
|
||||
let divergence = &printable[written..];
|
||||
let offset = offset_to(buf, divergence);
|
||||
let consumed = &buf[offset..];
|
||||
*state = initial_state;
|
||||
state.strip_next(consumed).last();
|
||||
return Ok(offset);
|
||||
}
|
||||
}
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn write_all(
|
||||
raw: &mut dyn std::io::Write,
|
||||
state: &mut StripBytes,
|
||||
buf: &[u8],
|
||||
) -> std::io::Result<()> {
|
||||
for printable in state.strip_next(buf) {
|
||||
raw.write_all(printable)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_fmt(
|
||||
raw: &mut dyn std::io::Write,
|
||||
state: &mut StripBytes,
|
||||
args: std::fmt::Arguments<'_>,
|
||||
) -> std::io::Result<()> {
|
||||
let write_all = |buf: &[u8]| write_all(raw, state, buf);
|
||||
crate::fmt::Adapter::new(write_all).write_fmt(args)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn offset_to(total: &[u8], subslice: &[u8]) -> usize {
|
||||
let total = total.as_ptr();
|
||||
let subslice = subslice.as_ptr();
|
||||
|
||||
debug_assert!(
|
||||
total <= subslice,
|
||||
"`Offset::offset_to` only accepts slices of `self`"
|
||||
);
|
||||
subslice as usize - total as usize
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use proptest::prelude::*;
|
||||
use std::io::Write as _;
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn write_all_no_escapes(s in "\\PC*") {
|
||||
let buffer = Vec::new();
|
||||
let mut stream = StripStream::new(buffer);
|
||||
stream.write_all(s.as_bytes()).unwrap();
|
||||
let buffer = stream.into_inner();
|
||||
let actual = std::str::from_utf8(buffer.as_ref()).unwrap();
|
||||
assert_eq!(s, actual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn write_byte_no_escapes(s in "\\PC*") {
|
||||
let buffer = Vec::new();
|
||||
let mut stream = StripStream::new(buffer);
|
||||
for byte in s.as_bytes() {
|
||||
stream.write_all(&[*byte]).unwrap();
|
||||
}
|
||||
let buffer = stream.into_inner();
|
||||
let actual = std::str::from_utf8(buffer.as_ref()).unwrap();
|
||||
assert_eq!(s, actual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn write_all_random(s in any::<Vec<u8>>()) {
|
||||
let buffer = Vec::new();
|
||||
let mut stream = StripStream::new(buffer);
|
||||
stream.write_all(s.as_slice()).unwrap();
|
||||
let buffer = stream.into_inner();
|
||||
if let Ok(actual) = std::str::from_utf8(buffer.as_ref()) {
|
||||
for char in actual.chars() {
|
||||
assert!(!char.is_ascii() || !char.is_control() || char.is_ascii_whitespace(), "{:?} -> {:?}: {:?}", String::from_utf8_lossy(&s), actual, char);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn write_byte_random(s in any::<Vec<u8>>()) {
|
||||
let buffer = Vec::new();
|
||||
let mut stream = StripStream::new(buffer);
|
||||
for byte in s.as_slice() {
|
||||
stream.write_all(&[*byte]).unwrap();
|
||||
}
|
||||
let buffer = stream.into_inner();
|
||||
if let Ok(actual) = std::str::from_utf8(buffer.as_ref()) {
|
||||
for char in actual.chars() {
|
||||
assert!(!char.is_ascii() || !char.is_control() || char.is_ascii_whitespace(), "{:?} -> {:?}: {:?}", String::from_utf8_lossy(&s), actual, char);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
use crate::adapter::WinconBytes;
|
||||
use crate::stream::AsLockedWrite;
|
||||
use crate::stream::IsTerminal;
|
||||
|
||||
/// Only pass printable data to the inner `Write`
|
||||
#[cfg(feature = "wincon")] // here mostly for documentation purposes
|
||||
#[derive(Debug)]
|
||||
pub struct WinconStream<S>
|
||||
where
|
||||
S: anstyle_wincon::WinconStream,
|
||||
{
|
||||
raw: S,
|
||||
// `WinconBytes` is especially large compared to other variants of `AutoStream`, so boxing it
|
||||
// here so `AutoStream` doesn't have to discard one allocation and create another one when
|
||||
// calling `AutoStream::lock`
|
||||
state: Box<WinconBytes>,
|
||||
}
|
||||
|
||||
impl<S> WinconStream<S>
|
||||
where
|
||||
S: anstyle_wincon::WinconStream,
|
||||
{
|
||||
/// Only pass printable data to the inner `Write`
|
||||
#[inline]
|
||||
pub fn new(raw: S) -> Self {
|
||||
Self {
|
||||
raw,
|
||||
state: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the wrapped [`anstyle_wincon::WinconStream`]
|
||||
#[inline]
|
||||
pub fn into_inner(self) -> S {
|
||||
self.raw
|
||||
}
|
||||
|
||||
/// Get the wrapped [`std::io::Write`]
|
||||
#[inline]
|
||||
pub fn as_inner(&self) -> &S {
|
||||
&self.raw
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> WinconStream<S>
|
||||
where
|
||||
S: anstyle_wincon::WinconStream,
|
||||
S: IsTerminal,
|
||||
{
|
||||
/// Returns `true` if the descriptor/handle refers to a terminal/tty.
|
||||
#[inline]
|
||||
pub fn is_terminal(&self) -> bool {
|
||||
self.raw.is_terminal()
|
||||
}
|
||||
}
|
||||
|
||||
impl WinconStream<std::io::Stdout> {
|
||||
/// Get exclusive access to the `WinconStream`
|
||||
///
|
||||
/// Why?
|
||||
/// - Faster performance when writing in a loop
|
||||
/// - Avoid other threads interleaving output with the current thread
|
||||
#[inline]
|
||||
pub fn lock(self) -> WinconStream<std::io::StdoutLock<'static>> {
|
||||
WinconStream {
|
||||
raw: self.raw.lock(),
|
||||
state: self.state,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WinconStream<std::io::Stderr> {
|
||||
/// Get exclusive access to the `WinconStream`
|
||||
///
|
||||
/// Why?
|
||||
/// - Faster performance when writing in a loop
|
||||
/// - Avoid other threads interleaving output with the current thread
|
||||
#[inline]
|
||||
pub fn lock(self) -> WinconStream<std::io::StderrLock<'static>> {
|
||||
WinconStream {
|
||||
raw: self.raw.lock(),
|
||||
state: self.state,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> std::io::Write for WinconStream<S>
|
||||
where
|
||||
S: anstyle_wincon::WinconStream,
|
||||
S: AsLockedWrite,
|
||||
{
|
||||
// Must forward all calls to ensure locking happens appropriately
|
||||
#[inline]
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
write(&mut self.raw.as_locked_write(), &mut self.state, buf)
|
||||
}
|
||||
#[inline]
|
||||
fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result<usize> {
|
||||
let buf = bufs
|
||||
.iter()
|
||||
.find(|b| !b.is_empty())
|
||||
.map(|b| &**b)
|
||||
.unwrap_or(&[][..]);
|
||||
self.write(buf)
|
||||
}
|
||||
// is_write_vectored: nightly only
|
||||
#[inline]
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.raw.as_locked_write().flush()
|
||||
}
|
||||
#[inline]
|
||||
fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
|
||||
write_all(&mut self.raw.as_locked_write(), &mut self.state, buf)
|
||||
}
|
||||
// write_all_vectored: nightly only
|
||||
#[inline]
|
||||
fn write_fmt(&mut self, args: std::fmt::Arguments<'_>) -> std::io::Result<()> {
|
||||
write_fmt(&mut self.raw.as_locked_write(), &mut self.state, args)
|
||||
}
|
||||
}
|
||||
|
||||
fn write(
|
||||
raw: &mut dyn anstyle_wincon::WinconStream,
|
||||
state: &mut WinconBytes,
|
||||
buf: &[u8],
|
||||
) -> std::io::Result<usize> {
|
||||
for (style, printable) in state.extract_next(buf) {
|
||||
let fg = style.get_fg_color().and_then(cap_wincon_color);
|
||||
let bg = style.get_bg_color().and_then(cap_wincon_color);
|
||||
let written = raw.write_colored(fg, bg, printable.as_bytes())?;
|
||||
let possible = printable.len();
|
||||
if possible != written {
|
||||
// HACK: Unsupported atm
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn write_all(
|
||||
raw: &mut dyn anstyle_wincon::WinconStream,
|
||||
state: &mut WinconBytes,
|
||||
buf: &[u8],
|
||||
) -> std::io::Result<()> {
|
||||
for (style, printable) in state.extract_next(buf) {
|
||||
let mut buf = printable.as_bytes();
|
||||
let fg = style.get_fg_color().and_then(cap_wincon_color);
|
||||
let bg = style.get_bg_color().and_then(cap_wincon_color);
|
||||
while !buf.is_empty() {
|
||||
match raw.write_colored(fg, bg, buf) {
|
||||
Ok(0) => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::WriteZero,
|
||||
"failed to write whole buffer",
|
||||
));
|
||||
}
|
||||
Ok(n) => buf = &buf[n..],
|
||||
Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_fmt(
|
||||
raw: &mut dyn anstyle_wincon::WinconStream,
|
||||
state: &mut WinconBytes,
|
||||
args: std::fmt::Arguments<'_>,
|
||||
) -> std::io::Result<()> {
|
||||
let write_all = |buf: &[u8]| write_all(raw, state, buf);
|
||||
crate::fmt::Adapter::new(write_all).write_fmt(args)
|
||||
}
|
||||
|
||||
fn cap_wincon_color(color: anstyle::Color) -> Option<anstyle::AnsiColor> {
|
||||
match color {
|
||||
anstyle::Color::Ansi(c) => Some(c),
|
||||
anstyle::Color::Ansi256(c) => c.into_ansi(),
|
||||
anstyle::Color::Rgb(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use proptest::prelude::*;
|
||||
use std::io::Write as _;
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn write_all_no_escapes(s in "\\PC*") {
|
||||
let buffer = Vec::new();
|
||||
let mut stream = WinconStream::new(buffer);
|
||||
stream.write_all(s.as_bytes()).unwrap();
|
||||
let buffer = stream.into_inner();
|
||||
let actual = std::str::from_utf8(buffer.as_ref()).unwrap();
|
||||
assert_eq!(s, actual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn write_byte_no_escapes(s in "\\PC*") {
|
||||
let buffer = Vec::new();
|
||||
let mut stream = WinconStream::new(buffer);
|
||||
for byte in s.as_bytes() {
|
||||
stream.write_all(&[*byte]).unwrap();
|
||||
}
|
||||
let buffer = stream.into_inner();
|
||||
let actual = std::str::from_utf8(buffer.as_ref()).unwrap();
|
||||
assert_eq!(s, actual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn write_all_random(s in any::<Vec<u8>>()) {
|
||||
let buffer = Vec::new();
|
||||
let mut stream = WinconStream::new(buffer);
|
||||
stream.write_all(s.as_slice()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253
|
||||
fn write_byte_random(s in any::<Vec<u8>>()) {
|
||||
let buffer = Vec::new();
|
||||
let mut stream = WinconStream::new(buffer);
|
||||
for byte in s.as_slice() {
|
||||
stream.write_all(&[*byte]).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user