mirror of
https://github.com/eyre-rs/eyre.git
synced 2025-09-29 22:11:55 +00:00
Add 'color-spantrace/' from commit '1a52aac2b55a05efc64807f06b91414550805af8'
git-subtree-dir: color-spantrace git-subtree-mainline: a443fd444ecfe8ac7f0d9a33b3f8e8d125eedbff git-subtree-split: 1a52aac2b55a05efc64807f06b91414550805af8
This commit is contained in:
commit
b40a66d493
81
color-spantrace/.github/workflows/ci.yml
vendored
Normal file
81
color-spantrace/.github/workflows/ci.yml
vendored
Normal file
@ -0,0 +1,81 @@
|
||||
on: [push, pull_request]
|
||||
|
||||
name: Continuous integration
|
||||
|
||||
jobs:
|
||||
check:
|
||||
name: Check
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
rust:
|
||||
- stable
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
override: true
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: check
|
||||
|
||||
test:
|
||||
name: Test Suite
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
rust:
|
||||
- stable
|
||||
- nightly
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
override: true
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: test
|
||||
# - uses: actions-rs/cargo@v1
|
||||
# with:
|
||||
# command: test
|
||||
# args: --no-default-features
|
||||
|
||||
fmt:
|
||||
name: Rustfmt
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
rust:
|
||||
- stable
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
override: true
|
||||
- run: rustup component add rustfmt
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: fmt
|
||||
args: --all -- --check
|
||||
|
||||
clippy:
|
||||
name: Clippy
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
rust:
|
||||
- stable
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
override: true
|
||||
- run: rustup component add clippy
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: clippy
|
||||
args: -- -D warnings
|
2
color-spantrace/.gitignore
vendored
Normal file
2
color-spantrace/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
/target
|
||||
Cargo.lock
|
28
color-spantrace/CHANGELOG.md
Normal file
28
color-spantrace/CHANGELOG.md
Normal file
@ -0,0 +1,28 @@
|
||||
# Changelog
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
<!-- next-header -->
|
||||
|
||||
## [Unreleased] - ReleaseDate
|
||||
|
||||
## [0.2.0] - 2022-01-12
|
||||
### Changed
|
||||
- Updated dependency versions to match latest tracing versions
|
||||
|
||||
## [0.1.6] - 2020-12-02
|
||||
### Fixed
|
||||
- Ignore all io errors when resolving source files instead of only file not
|
||||
found errors
|
||||
|
||||
## [v0.1.5] - 2020-12-01
|
||||
### Added
|
||||
- Support custom color themes for spantrace format
|
||||
|
||||
<!-- next-url -->
|
||||
[Unreleased]: https://github.com/yaahc/color-spantrace/compare/v0.2.0...HEAD
|
||||
[0.2.0]: https://github.com/yaahc/color-spantrace/compare/v0.1.6...v0.2.0
|
||||
[0.1.6]: https://github.com/yaahc/color-spantrace/compare/v0.1.5...v0.1.6
|
||||
[v0.1.5]: https://github.com/yaahc/color-spantrace/releases/tag/v0.1.5
|
64
color-spantrace/Cargo.toml
Normal file
64
color-spantrace/Cargo.toml
Normal file
@ -0,0 +1,64 @@
|
||||
[package]
|
||||
name = "color-spantrace"
|
||||
version = "0.2.0"
|
||||
authors = ["Jane Lusby <jlusby@yaah.dev>"]
|
||||
edition = "2018"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "A pretty printer for tracing_error::SpanTrace based on color-backtrace"
|
||||
repository = "https://github.com/yaahc/color-spantrace"
|
||||
documentation = "https://docs.rs/color-spantrace"
|
||||
readme = "README.md"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
tracing-error = "0.2.0"
|
||||
tracing-core = "0.1.21"
|
||||
owo-colors = "3.2.0"
|
||||
once_cell = "1.4.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tracing-subscriber = "0.3.4"
|
||||
tracing = "0.1.29"
|
||||
ansi-parser = "0.8" # used for testing color schemes
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[package.metadata.release]
|
||||
dev-version = false
|
||||
|
||||
[[package.metadata.release.pre-release-replacements]]
|
||||
file = "CHANGELOG.md"
|
||||
search = "Unreleased"
|
||||
replace="{{version}}"
|
||||
|
||||
[[package.metadata.release.pre-release-replacements]]
|
||||
file = "src/lib.rs"
|
||||
search = "#!\\[doc\\(html_root_url.*"
|
||||
replace = "#![doc(html_root_url = \"https://docs.rs/{{crate_name}}/{{version}}\")]"
|
||||
exactly = 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}}"
|
||||
|
||||
[[package.metadata.release.pre-release-replacements]]
|
||||
file="CHANGELOG.md"
|
||||
search="<!-- next-header -->"
|
||||
replace="<!-- next-header -->\n\n## [Unreleased] - ReleaseDate"
|
||||
exactly=1
|
||||
|
||||
[[package.metadata.release.pre-release-replacements]]
|
||||
file="CHANGELOG.md"
|
||||
search="<!-- next-url -->"
|
||||
replace="<!-- next-url -->\n[Unreleased]: https://github.com/yaahc/{{crate_name}}/compare/{{tag_name}}...HEAD"
|
||||
exactly=1
|
202
color-spantrace/LICENSE-APACHE
Normal file
202
color-spantrace/LICENSE-APACHE
Normal file
@ -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.
|
23
color-spantrace/LICENSE-MIT
Normal file
23
color-spantrace/LICENSE-MIT
Normal file
@ -0,0 +1,23 @@
|
||||
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.
|
110
color-spantrace/README.md
Normal file
110
color-spantrace/README.md
Normal file
@ -0,0 +1,110 @@
|
||||
color-spantrace
|
||||
===============
|
||||
|
||||
[![Build Status][actions-badge]][actions-url]
|
||||
[](https://crates.io/crates/color-spantrace)
|
||||
[](https://docs.rs/color-spantrace)
|
||||
|
||||
[actions-badge]: https://github.com/yaahc/color-spantrace/workflows/Continuous%20integration/badge.svg
|
||||
[actions-url]: https://github.com/yaahc/color-spantrace/actions?query=workflow%3A%22Continuous+integration%22
|
||||
|
||||
A rust library for colorizing [`tracing_error::SpanTrace`] objects in the style
|
||||
of [`color-backtrace`].
|
||||
|
||||
## Setup
|
||||
|
||||
Add the following to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
color-spantrace = "0.2"
|
||||
tracing = "0.1"
|
||||
tracing-error = "0.2"
|
||||
tracing-subscriber = "0.3"
|
||||
```
|
||||
|
||||
Setup a tracing subscriber with an `ErrorLayer`:
|
||||
|
||||
```rust
|
||||
use tracing_error::ErrorLayer;
|
||||
use tracing_subscriber::{prelude::*, registry::Registry};
|
||||
|
||||
Registry::default().with(ErrorLayer::default()).init();
|
||||
```
|
||||
|
||||
Create spans and enter them:
|
||||
|
||||
```rust
|
||||
use tracing::instrument;
|
||||
use tracing_error::SpanTrace;
|
||||
|
||||
#[instrument]
|
||||
fn foo() -> SpanTrace {
|
||||
SpanTrace::capture()
|
||||
}
|
||||
```
|
||||
|
||||
And finally colorize the `SpanTrace`:
|
||||
|
||||
```rust
|
||||
use tracing_error::SpanTrace;
|
||||
|
||||
let span_trace = SpanTrace::capture();
|
||||
println!("{}", color_spantrace::colorize(&span_trace));
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
This example is taken from `examples/usage.rs`:
|
||||
|
||||
```rust
|
||||
use tracing::instrument;
|
||||
use tracing_error::{ErrorLayer, SpanTrace};
|
||||
use tracing_subscriber::{prelude::*, registry::Registry};
|
||||
|
||||
#[instrument]
|
||||
fn main() {
|
||||
Registry::default().with(ErrorLayer::default()).init();
|
||||
|
||||
let span_trace = one(42);
|
||||
println!("{}", color_spantrace::colorize(&span_trace));
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
fn one(i: u32) -> SpanTrace {
|
||||
two()
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
fn two() -> SpanTrace {
|
||||
SpanTrace::capture()
|
||||
}
|
||||
```
|
||||
|
||||
This creates the following output
|
||||
|
||||
### Minimal Format
|
||||
|
||||

|
||||
|
||||
### Full Format
|
||||
|
||||

|
||||
|
||||
#### License
|
||||
|
||||
<sup>
|
||||
Licensed under either of <a href="LICENSE-APACHE">Apache License, Version
|
||||
2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option.
|
||||
</sup>
|
||||
|
||||
<br>
|
||||
|
||||
<sub>
|
||||
Unless you explicitly state otherwise, any contribution intentionally submitted
|
||||
for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
|
||||
be dual licensed as above, without any additional terms or conditions.
|
||||
</sub>
|
||||
|
||||
[`tracing_error::SpanTrace`]: https://docs.rs/tracing-error/*/tracing_error/struct.SpanTrace.html
|
||||
[`color-backtrace`]: https://github.com/athre0z/color-backtrace
|
21
color-spantrace/examples/usage.rs
Normal file
21
color-spantrace/examples/usage.rs
Normal file
@ -0,0 +1,21 @@
|
||||
use tracing::instrument;
|
||||
use tracing_error::{ErrorLayer, SpanTrace};
|
||||
use tracing_subscriber::{prelude::*, registry::Registry};
|
||||
|
||||
#[instrument]
|
||||
fn main() {
|
||||
Registry::default().with(ErrorLayer::default()).init();
|
||||
|
||||
let span_trace = one(42);
|
||||
println!("{}", color_spantrace::colorize(&span_trace));
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
fn one(i: u32) -> SpanTrace {
|
||||
two()
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
fn two() -> SpanTrace {
|
||||
SpanTrace::capture()
|
||||
}
|
BIN
color-spantrace/pictures/full.png
Normal file
BIN
color-spantrace/pictures/full.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 113 KiB |
BIN
color-spantrace/pictures/minimal.png
Normal file
BIN
color-spantrace/pictures/minimal.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 72 KiB |
377
color-spantrace/src/lib.rs
Normal file
377
color-spantrace/src/lib.rs
Normal file
@ -0,0 +1,377 @@
|
||||
//! A rust library for colorizing [`tracing_error::SpanTrace`] objects in the style
|
||||
//! of [`color-backtrace`].
|
||||
//!
|
||||
//! ## Setup
|
||||
//!
|
||||
//! Add the following to your `Cargo.toml`:
|
||||
//!
|
||||
//! ```toml
|
||||
//! [dependencies]
|
||||
//! color-spantrace = "0.2"
|
||||
//! tracing = "0.1"
|
||||
//! tracing-error = "0.2"
|
||||
//! tracing-subscriber = "0.3"
|
||||
//! ```
|
||||
//!
|
||||
//! Setup a tracing subscriber with an `ErrorLayer`:
|
||||
//!
|
||||
//! ```rust
|
||||
//! use tracing_error::ErrorLayer;
|
||||
//! use tracing_subscriber::{prelude::*, registry::Registry};
|
||||
//!
|
||||
//! Registry::default().with(ErrorLayer::default()).init();
|
||||
//! ```
|
||||
//!
|
||||
//! Create spans and enter them:
|
||||
//!
|
||||
//! ```rust
|
||||
//! use tracing::instrument;
|
||||
//! use tracing_error::SpanTrace;
|
||||
//!
|
||||
//! #[instrument]
|
||||
//! fn foo() -> SpanTrace {
|
||||
//! SpanTrace::capture()
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! And finally colorize the `SpanTrace`:
|
||||
//!
|
||||
//! ```rust
|
||||
//! use tracing_error::SpanTrace;
|
||||
//!
|
||||
//! let span_trace = SpanTrace::capture();
|
||||
//! println!("{}", color_spantrace::colorize(&span_trace));
|
||||
//! ```
|
||||
//!
|
||||
//! ## Output Format
|
||||
//!
|
||||
//! Running `examples/usage.rs` from the `color-spantrace` repo produces the following output:
|
||||
//!
|
||||
//! <pre><font color="#4E9A06"><b>❯</b></font> cargo run --example usage
|
||||
//! <font color="#4E9A06"><b> Finished</b></font> dev [unoptimized + debuginfo] target(s) in 0.04s
|
||||
//! <font color="#4E9A06"><b> Running</b></font> `target/debug/examples/usage`
|
||||
//! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ SPANTRACE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
//!
|
||||
//! 0: <font color="#F15D22">usage::two</font>
|
||||
//! at <font color="#75507B">examples/usage.rs</font>:<font color="#75507B">18</font>
|
||||
//! 1: <font color="#F15D22">usage::one</font> with <font color="#34E2E2">i=42</font>
|
||||
//! at <font color="#75507B">examples/usage.rs</font>:<font color="#75507B">13</font></pre>
|
||||
//!
|
||||
//! [`tracing_error::SpanTrace`]: https://docs.rs/tracing-error/*/tracing_error/struct.SpanTrace.html
|
||||
//! [`color-backtrace`]: https://github.com/athre0z/color-backtrace
|
||||
#![doc(html_root_url = "https://docs.rs/color-spantrace/0.2.0")]
|
||||
#![warn(
|
||||
missing_debug_implementations,
|
||||
missing_docs,
|
||||
rustdoc::missing_doc_code_examples,
|
||||
rust_2018_idioms,
|
||||
unreachable_pub,
|
||||
bad_style,
|
||||
const_err,
|
||||
dead_code,
|
||||
improper_ctypes,
|
||||
non_shorthand_field_patterns,
|
||||
no_mangle_generic_items,
|
||||
overflowing_literals,
|
||||
path_statements,
|
||||
patterns_in_fns_without_body,
|
||||
private_in_public,
|
||||
unconditional_recursion,
|
||||
unused,
|
||||
unused_allocation,
|
||||
unused_comparisons,
|
||||
unused_parens,
|
||||
while_true
|
||||
)]
|
||||
use once_cell::sync::OnceCell;
|
||||
use owo_colors::{style, Style};
|
||||
use std::env;
|
||||
use std::fmt;
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use tracing_error::SpanTrace;
|
||||
|
||||
static THEME: OnceCell<Theme> = OnceCell::new();
|
||||
|
||||
/// A struct that represents theme that is used by `color_spantrace`
|
||||
#[derive(Debug, Copy, Clone, Default)]
|
||||
pub struct Theme {
|
||||
file: Style,
|
||||
line_number: Style,
|
||||
target: Style,
|
||||
fields: Style,
|
||||
active_line: Style,
|
||||
}
|
||||
|
||||
impl Theme {
|
||||
/// Create blank theme
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// A theme for a dark background. This is the default
|
||||
pub fn dark() -> Self {
|
||||
Self {
|
||||
file: style().purple(),
|
||||
line_number: style().purple(),
|
||||
active_line: style().white().bold(),
|
||||
target: style().bright_red(),
|
||||
fields: style().bright_cyan(),
|
||||
}
|
||||
}
|
||||
|
||||
// XXX same as with `light` in `color_eyre`
|
||||
/// A theme for a light background
|
||||
pub fn light() -> Self {
|
||||
Self {
|
||||
file: style().purple(),
|
||||
line_number: style().purple(),
|
||||
target: style().red(),
|
||||
fields: style().blue(),
|
||||
active_line: style().bold(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Styles printed paths
|
||||
pub fn file(mut self, style: Style) -> Self {
|
||||
self.file = style;
|
||||
self
|
||||
}
|
||||
|
||||
/// Styles the line number of a file
|
||||
pub fn line_number(mut self, style: Style) -> Self {
|
||||
self.line_number = style;
|
||||
self
|
||||
}
|
||||
|
||||
/// Styles the target (i.e. the module and function name, and so on)
|
||||
pub fn target(mut self, style: Style) -> Self {
|
||||
self.target = style;
|
||||
self
|
||||
}
|
||||
|
||||
/// Styles fields associated with a the `tracing::Span`.
|
||||
pub fn fields(mut self, style: Style) -> Self {
|
||||
self.fields = style;
|
||||
self
|
||||
}
|
||||
|
||||
/// Styles the selected line of displayed code
|
||||
pub fn active_line(mut self, style: Style) -> Self {
|
||||
self.active_line = style;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// An error returned by `set_theme` if a global theme was already set
|
||||
#[derive(Debug)]
|
||||
pub struct InstallThemeError;
|
||||
|
||||
impl fmt::Display for InstallThemeError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("could not set the provided `Theme` globally as another was already set")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InstallThemeError {}
|
||||
|
||||
/// Sets the global theme.
|
||||
///
|
||||
/// # Details
|
||||
///
|
||||
/// This can only be set once and otherwise fails.
|
||||
///
|
||||
/// **Note:** `colorize` sets the global theme implicitly, if it was not set already. So calling `colorize` and then `set_theme` fails
|
||||
pub fn set_theme(theme: Theme) -> Result<(), InstallThemeError> {
|
||||
THEME.set(theme).map_err(|_| InstallThemeError)
|
||||
}
|
||||
|
||||
/// Display a [`SpanTrace`] with colors and source
|
||||
///
|
||||
/// This function returns an `impl Display` type which can be then used in place of the original
|
||||
/// SpanTrace when writing it too the screen or buffer.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use tracing_error::SpanTrace;
|
||||
///
|
||||
/// let span_trace = SpanTrace::capture();
|
||||
/// println!("{}", color_spantrace::colorize(&span_trace));
|
||||
/// ```
|
||||
///
|
||||
/// **Note:** `colorize` sets the global theme implicitly, if it was not set already. So calling `colorize` and then `set_theme` fails
|
||||
///
|
||||
/// [`SpanTrace`]: https://docs.rs/tracing-error/*/tracing_error/struct.SpanTrace.html
|
||||
pub fn colorize(span_trace: &SpanTrace) -> impl fmt::Display + '_ {
|
||||
let theme = *THEME.get_or_init(Theme::dark);
|
||||
ColorSpanTrace { span_trace, theme }
|
||||
}
|
||||
|
||||
struct ColorSpanTrace<'a> {
|
||||
span_trace: &'a SpanTrace,
|
||||
theme: Theme,
|
||||
}
|
||||
|
||||
macro_rules! try_bool {
|
||||
($e:expr, $dest:ident) => {{
|
||||
let ret = $e.unwrap_or_else(|e| $dest = Err(e));
|
||||
|
||||
if $dest.is_err() {
|
||||
return false;
|
||||
}
|
||||
|
||||
ret
|
||||
}};
|
||||
}
|
||||
|
||||
struct Frame<'a> {
|
||||
metadata: &'a tracing_core::Metadata<'static>,
|
||||
fields: &'a str,
|
||||
theme: Theme,
|
||||
}
|
||||
|
||||
/// Defines how verbose the backtrace is supposed to be.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum Verbosity {
|
||||
/// Print a small message including the panic payload and the panic location.
|
||||
Minimal,
|
||||
/// Everything in `Minimal` and additionally print a backtrace.
|
||||
Medium,
|
||||
/// Everything in `Medium` plus source snippets for all backtrace locations.
|
||||
Full,
|
||||
}
|
||||
|
||||
impl Verbosity {
|
||||
fn lib_from_env() -> Self {
|
||||
Self::convert_env(
|
||||
env::var("RUST_LIB_BACKTRACE")
|
||||
.or_else(|_| env::var("RUST_BACKTRACE"))
|
||||
.ok(),
|
||||
)
|
||||
}
|
||||
|
||||
fn convert_env(env: Option<String>) -> Self {
|
||||
match env {
|
||||
Some(ref x) if x == "full" => Verbosity::Full,
|
||||
Some(_) => Verbosity::Medium,
|
||||
None => Verbosity::Minimal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Frame<'_> {
|
||||
fn print(&self, i: u32, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.print_header(i, f)?;
|
||||
self.print_fields(f)?;
|
||||
self.print_source_location(f)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_header(&self, i: u32, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{:>2}: {}{}{}",
|
||||
i,
|
||||
self.theme.target.style(self.metadata.target()),
|
||||
self.theme.target.style("::"),
|
||||
self.theme.target.style(self.metadata.name()),
|
||||
)
|
||||
}
|
||||
|
||||
fn print_fields(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if !self.fields.is_empty() {
|
||||
write!(f, " with {}", self.theme.fields.style(self.fields))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_source_location(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if let Some(file) = self.metadata.file() {
|
||||
let lineno = self
|
||||
.metadata
|
||||
.line()
|
||||
.map_or("<unknown line>".to_owned(), |x| x.to_string());
|
||||
write!(
|
||||
f,
|
||||
"\n at {}:{}",
|
||||
self.theme.file.style(file),
|
||||
self.theme.line_number.style(lineno),
|
||||
)?;
|
||||
} else {
|
||||
write!(f, "\n at <unknown source file>")?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_source_if_avail(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let (lineno, filename) = match (self.metadata.line(), self.metadata.file()) {
|
||||
(Some(a), Some(b)) => (a, b),
|
||||
// Without a line number and file name, we can't sensibly proceed.
|
||||
_ => return Ok(()),
|
||||
};
|
||||
|
||||
let file = match File::open(filename) {
|
||||
Ok(file) => file,
|
||||
// ignore io errors and just don't print the source
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
|
||||
use std::fmt::Write;
|
||||
|
||||
// Extract relevant lines.
|
||||
let reader = BufReader::new(file);
|
||||
let start_line = lineno - 2.min(lineno - 1);
|
||||
let surrounding_src = reader.lines().skip(start_line as usize - 1).take(5);
|
||||
let mut buf = String::new();
|
||||
for (line, cur_line_no) in surrounding_src.zip(start_line..) {
|
||||
if cur_line_no == lineno {
|
||||
write!(
|
||||
&mut buf,
|
||||
"{:>8} > {}",
|
||||
cur_line_no.to_string(),
|
||||
line.unwrap()
|
||||
)?;
|
||||
write!(f, "\n{}", self.theme.active_line.style(&buf))?;
|
||||
buf.clear();
|
||||
} else {
|
||||
write!(f, "\n{:>8} │ {}", cur_line_no, line.unwrap())?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ColorSpanTrace<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let mut err = Ok(());
|
||||
let mut span = 0;
|
||||
|
||||
writeln!(f, "{:━^80}\n", " SPANTRACE ")?;
|
||||
self.span_trace.with_spans(|metadata, fields| {
|
||||
let frame = Frame {
|
||||
metadata,
|
||||
fields,
|
||||
theme: self.theme,
|
||||
};
|
||||
|
||||
if span > 0 {
|
||||
try_bool!(write!(f, "\n",), err);
|
||||
}
|
||||
|
||||
try_bool!(frame.print(span, f), err);
|
||||
|
||||
if Verbosity::lib_from_env() == Verbosity::Full {
|
||||
try_bool!(frame.print_source_if_avail(f), err);
|
||||
}
|
||||
|
||||
span += 1;
|
||||
true
|
||||
});
|
||||
|
||||
err
|
||||
}
|
||||
}
|
9
color-spantrace/tests/data/theme_control.txt
Normal file
9
color-spantrace/tests/data/theme_control.txt
Normal file
@ -0,0 +1,9 @@
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ SPANTRACE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
0: [91mthemes[0m[91m::[0m[91mtest_capture[0m with [96mx=42[0m
|
||||
at [35mtests/themes.rs[0m:[35m42[0m
|
||||
40 │ use tracing_subscriber::{prelude::*, registry::Registry};
|
||||
41 │
|
||||
[37;1m 42 > #[instrument][0m
|
||||
43 │ fn test_capture(x: u8) -> SpanTrace {
|
||||
44 │ #[allow(clippy::if_same_then_else)]
|
93
color-spantrace/tests/themes.rs
Normal file
93
color-spantrace/tests/themes.rs
Normal file
@ -0,0 +1,93 @@
|
||||
/*
|
||||
|
||||
# How this test works:
|
||||
|
||||
1) generate a spantrace with `test_capture`
|
||||
|
||||
2) convert the spantrace to a string
|
||||
|
||||
3) load stored spantrace control to compare to spantrace string (stored in the path of `control_file_path` below)
|
||||
|
||||
4) if `control_file_path` doesn't exist, generate corresponding file in the current working directory and request the user to fix the issue (see below)
|
||||
|
||||
5) extract ANSI escaping sequences (of control and current spantrace)
|
||||
|
||||
6) compare if the current spantrace and the control contains the same ANSI escape sequences
|
||||
|
||||
7) If not, fail and show the full strings of the control and the current spantrace
|
||||
|
||||
# Re-generating the control
|
||||
|
||||
If the control spantrace is lost and/or it needs to be re-generated, do the following:
|
||||
|
||||
1) Checkout the `color_spantrace` version from Git that you want to test against
|
||||
|
||||
3) Add this test file to '/tests'
|
||||
|
||||
4) If `control_file_path` exist, delete it
|
||||
|
||||
5) If you now run this test, it will generate a test control file in the current working directory
|
||||
|
||||
6) copy this file to `control_file_path` (see instructions that are shown)
|
||||
|
||||
*/
|
||||
|
||||
use ansi_parser::{AnsiParser, AnsiSequence, Output};
|
||||
use std::{fs, path::Path};
|
||||
use tracing::instrument;
|
||||
use tracing_error::ErrorLayer;
|
||||
use tracing_error::SpanTrace;
|
||||
use tracing_subscriber::{prelude::*, registry::Registry};
|
||||
|
||||
#[instrument]
|
||||
fn test_capture(x: u8) -> SpanTrace {
|
||||
#[allow(clippy::if_same_then_else)]
|
||||
if x == 42 {
|
||||
SpanTrace::capture()
|
||||
} else {
|
||||
SpanTrace::capture()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_backwards_compatibility() {
|
||||
std::env::set_var("RUST_LIB_BACKTRACE", "full");
|
||||
Registry::default().with(ErrorLayer::default()).init();
|
||||
|
||||
let spantrace = test_capture(42);
|
||||
let colored_spantrace = format!("{}", color_spantrace::colorize(&spantrace));
|
||||
|
||||
let control_file_name = "theme_control.txt";
|
||||
let control_file_path = ["tests/data/", control_file_name].concat();
|
||||
|
||||
// If `control_file_path` is missing, save corresponding file to current working directory, and panic with the request to move these files to `control_file_path`, and to commit them to Git. Being explicit (instead of saving directly to `control_file_path` to make sure `control_file_path` is committed to Git. These files anyway should never be missing.
|
||||
|
||||
if !Path::new(&control_file_path).is_file() {
|
||||
std::fs::write(control_file_name, &colored_spantrace)
|
||||
.expect("\n\nError saving `colored_spanntrace` to a file");
|
||||
panic!("Required test data missing! Fix this, by moving '{}' to '{}', and commit it to Git.\n\nNote: '{0}' was just generated in the current working directory.\n\n", control_file_name, control_file_path);
|
||||
}
|
||||
|
||||
// `unwrap` should never fail with files generated by this test
|
||||
let colored_spantrace_control =
|
||||
String::from_utf8(fs::read(control_file_path).unwrap()).unwrap();
|
||||
|
||||
fn get_ansi(s: &str) -> impl Iterator<Item = AnsiSequence> + '_ {
|
||||
s.ansi_parse().filter_map(|x| {
|
||||
if let Output::Escape(ansi) = x {
|
||||
Some(ansi)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
let colored_spantrace_ansi = get_ansi(&colored_spantrace);
|
||||
let colored_spantrace_control_ansi = get_ansi(&colored_spantrace_control);
|
||||
|
||||
assert!(
|
||||
colored_spantrace_ansi.eq(colored_spantrace_control_ansi),
|
||||
"\x1b[0mANSI escape sequences are not identical to control!\n\nCONTROL:\n\n{}\n\n\n\n{:?}\n\nCURRENT:\n\n{}\n\n\n\n{:?}\n\n", &colored_spantrace_control, &colored_spantrace_control, &colored_spantrace, &colored_spantrace
|
||||
// `\x1b[0m` clears previous ANSI escape sequences
|
||||
);
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user