├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples └── usage.rs ├── pictures ├── full.png └── minimal.png ├── src └── lib.rs └── tests ├── data └── theme_control.txt └── themes.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: Continuous integration 4 | 5 | jobs: 6 | check: 7 | name: Check 8 | runs-on: ubuntu-latest 9 | strategy: 10 | matrix: 11 | rust: 12 | - stable 13 | steps: 14 | - uses: actions/checkout@v1 15 | - uses: actions-rs/toolchain@v1 16 | with: 17 | toolchain: ${{ matrix.rust }} 18 | override: true 19 | - uses: actions-rs/cargo@v1 20 | with: 21 | command: check 22 | 23 | test: 24 | name: Test Suite 25 | runs-on: ubuntu-latest 26 | strategy: 27 | matrix: 28 | rust: 29 | - stable 30 | - nightly 31 | steps: 32 | - uses: actions/checkout@v1 33 | - uses: actions-rs/toolchain@v1 34 | with: 35 | toolchain: ${{ matrix.rust }} 36 | override: true 37 | - uses: actions-rs/cargo@v1 38 | with: 39 | command: test 40 | # - uses: actions-rs/cargo@v1 41 | # with: 42 | # command: test 43 | # args: --no-default-features 44 | 45 | fmt: 46 | name: Rustfmt 47 | runs-on: ubuntu-latest 48 | strategy: 49 | matrix: 50 | rust: 51 | - stable 52 | steps: 53 | - uses: actions/checkout@v1 54 | - uses: actions-rs/toolchain@v1 55 | with: 56 | toolchain: ${{ matrix.rust }} 57 | override: true 58 | - run: rustup component add rustfmt 59 | - uses: actions-rs/cargo@v1 60 | with: 61 | command: fmt 62 | args: --all -- --check 63 | 64 | clippy: 65 | name: Clippy 66 | runs-on: ubuntu-latest 67 | strategy: 68 | matrix: 69 | rust: 70 | - stable 71 | steps: 72 | - uses: actions/checkout@v1 73 | - uses: actions-rs/toolchain@v1 74 | with: 75 | toolchain: ${{ matrix.rust }} 76 | override: true 77 | - run: rustup component add clippy 78 | - uses: actions-rs/cargo@v1 79 | with: 80 | command: clippy 81 | args: -- -D warnings 82 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | 8 | 9 | ## [Unreleased] - ReleaseDate 10 | 11 | ## [0.2.0] - 2022-01-12 12 | ### Changed 13 | - Updated dependency versions to match latest tracing versions 14 | 15 | ## [0.1.6] - 2020-12-02 16 | ### Fixed 17 | - Ignore all io errors when resolving source files instead of only file not 18 | found errors 19 | 20 | ## [v0.1.5] - 2020-12-01 21 | ### Added 22 | - Support custom color themes for spantrace format 23 | 24 | 25 | [Unreleased]: https://github.com/yaahc/color-spantrace/compare/v0.2.0...HEAD 26 | [0.2.0]: https://github.com/yaahc/color-spantrace/compare/v0.1.6...v0.2.0 27 | [0.1.6]: https://github.com/yaahc/color-spantrace/compare/v0.1.5...v0.1.6 28 | [v0.1.5]: https://github.com/yaahc/color-spantrace/releases/tag/v0.1.5 29 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "color-spantrace" 3 | version = "0.2.0" 4 | authors = ["Jane Lusby "] 5 | edition = "2018" 6 | license = "MIT OR Apache-2.0" 7 | description = "A pretty printer for tracing_error::SpanTrace based on color-backtrace" 8 | repository = "https://github.com/yaahc/color-spantrace" 9 | documentation = "https://docs.rs/color-spantrace" 10 | readme = "README.md" 11 | 12 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 13 | 14 | [dependencies] 15 | tracing-error = "0.2.0" 16 | tracing-core = "0.1.21" 17 | owo-colors = "3.2.0" 18 | once_cell = "1.4.1" 19 | 20 | [dev-dependencies] 21 | tracing-subscriber = "0.3.4" 22 | tracing = "0.1.29" 23 | ansi-parser = "0.8" # used for testing color schemes 24 | 25 | [package.metadata.docs.rs] 26 | all-features = true 27 | rustdoc-args = ["--cfg", "docsrs"] 28 | 29 | [package.metadata.release] 30 | dev-version = false 31 | 32 | [[package.metadata.release.pre-release-replacements]] 33 | file = "CHANGELOG.md" 34 | search = "Unreleased" 35 | replace="{{version}}" 36 | 37 | [[package.metadata.release.pre-release-replacements]] 38 | file = "src/lib.rs" 39 | search = "#!\\[doc\\(html_root_url.*" 40 | replace = "#![doc(html_root_url = \"https://docs.rs/{{crate_name}}/{{version}}\")]" 41 | exactly = 1 42 | 43 | [[package.metadata.release.pre-release-replacements]] 44 | file = "CHANGELOG.md" 45 | search = "\\.\\.\\.HEAD" 46 | replace="...{{tag_name}}" 47 | exactly = 1 48 | 49 | [[package.metadata.release.pre-release-replacements]] 50 | file = "CHANGELOG.md" 51 | search = "ReleaseDate" 52 | replace="{{date}}" 53 | 54 | [[package.metadata.release.pre-release-replacements]] 55 | file="CHANGELOG.md" 56 | search="" 57 | replace="\n\n## [Unreleased] - ReleaseDate" 58 | exactly=1 59 | 60 | [[package.metadata.release.pre-release-replacements]] 61 | file="CHANGELOG.md" 62 | search="" 63 | replace="\n[Unreleased]: https://github.com/yaahc/{{crate_name}}/compare/{{tag_name}}...HEAD" 64 | exactly=1 65 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #### The code has been moved into a monorepo at https://github.com/eyre-rs/eyre/tree/master/color-spantrace 2 | -------------------------------------------------------------------------------- /examples/usage.rs: -------------------------------------------------------------------------------- 1 | use tracing::instrument; 2 | use tracing_error::{ErrorLayer, SpanTrace}; 3 | use tracing_subscriber::{prelude::*, registry::Registry}; 4 | 5 | #[instrument] 6 | fn main() { 7 | Registry::default().with(ErrorLayer::default()).init(); 8 | 9 | let span_trace = one(42); 10 | println!("{}", color_spantrace::colorize(&span_trace)); 11 | } 12 | 13 | #[instrument] 14 | fn one(i: u32) -> SpanTrace { 15 | two() 16 | } 17 | 18 | #[instrument] 19 | fn two() -> SpanTrace { 20 | SpanTrace::capture() 21 | } 22 | -------------------------------------------------------------------------------- /pictures/full.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eyre-rs/color-spantrace/a0adb7b5899c082632763f0708c34358f860d14e/pictures/full.png -------------------------------------------------------------------------------- /pictures/minimal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eyre-rs/color-spantrace/a0adb7b5899c082632763f0708c34358f860d14e/pictures/minimal.png -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A rust library for colorizing [`tracing_error::SpanTrace`] objects in the style 2 | //! of [`color-backtrace`]. 3 | //! 4 | //! ## Setup 5 | //! 6 | //! Add the following to your `Cargo.toml`: 7 | //! 8 | //! ```toml 9 | //! [dependencies] 10 | //! color-spantrace = "0.2" 11 | //! tracing = "0.1" 12 | //! tracing-error = "0.2" 13 | //! tracing-subscriber = "0.3" 14 | //! ``` 15 | //! 16 | //! Setup a tracing subscriber with an `ErrorLayer`: 17 | //! 18 | //! ```rust 19 | //! use tracing_error::ErrorLayer; 20 | //! use tracing_subscriber::{prelude::*, registry::Registry}; 21 | //! 22 | //! Registry::default().with(ErrorLayer::default()).init(); 23 | //! ``` 24 | //! 25 | //! Create spans and enter them: 26 | //! 27 | //! ```rust 28 | //! use tracing::instrument; 29 | //! use tracing_error::SpanTrace; 30 | //! 31 | //! #[instrument] 32 | //! fn foo() -> SpanTrace { 33 | //! SpanTrace::capture() 34 | //! } 35 | //! ``` 36 | //! 37 | //! And finally colorize the `SpanTrace`: 38 | //! 39 | //! ```rust 40 | //! use tracing_error::SpanTrace; 41 | //! 42 | //! let span_trace = SpanTrace::capture(); 43 | //! println!("{}", color_spantrace::colorize(&span_trace)); 44 | //! ``` 45 | //! 46 | //! ## Output Format 47 | //! 48 | //! Running `examples/usage.rs` from the `color-spantrace` repo produces the following output: 49 | //! 50 | //!
 cargo run --example usage
 51 | //!     Finished dev [unoptimized + debuginfo] target(s) in 0.04s
 52 | //!      Running `target/debug/examples/usage`
 53 | //! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ SPANTRACE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 54 | //!
 55 | //!  0: usage::two
 56 | //!     at examples/usage.rs:18
 57 | //!  1: usage::one with i=42
 58 | //!     at examples/usage.rs:13
59 | //! 60 | //! [`tracing_error::SpanTrace`]: https://docs.rs/tracing-error/*/tracing_error/struct.SpanTrace.html 61 | //! [`color-backtrace`]: https://github.com/athre0z/color-backtrace 62 | #![doc(html_root_url = "https://docs.rs/color-spantrace/0.2.0")] 63 | #![warn( 64 | missing_debug_implementations, 65 | missing_docs, 66 | rustdoc::missing_doc_code_examples, 67 | rust_2018_idioms, 68 | unreachable_pub, 69 | bad_style, 70 | dead_code, 71 | improper_ctypes, 72 | non_shorthand_field_patterns, 73 | no_mangle_generic_items, 74 | overflowing_literals, 75 | path_statements, 76 | patterns_in_fns_without_body, 77 | unconditional_recursion, 78 | unused, 79 | unused_allocation, 80 | unused_comparisons, 81 | unused_parens, 82 | while_true 83 | )] 84 | use once_cell::sync::OnceCell; 85 | use owo_colors::{style, Style}; 86 | use std::env; 87 | use std::fmt; 88 | use std::fs::File; 89 | use std::io::{BufRead, BufReader}; 90 | use tracing_error::SpanTrace; 91 | 92 | static THEME: OnceCell = OnceCell::new(); 93 | 94 | /// A struct that represents theme that is used by `color_spantrace` 95 | #[derive(Debug, Copy, Clone, Default)] 96 | pub struct Theme { 97 | file: Style, 98 | line_number: Style, 99 | target: Style, 100 | fields: Style, 101 | active_line: Style, 102 | } 103 | 104 | impl Theme { 105 | /// Create blank theme 106 | pub fn new() -> Self { 107 | Self::default() 108 | } 109 | 110 | /// A theme for a dark background. This is the default 111 | pub fn dark() -> Self { 112 | Self { 113 | file: style().purple(), 114 | line_number: style().purple(), 115 | active_line: style().white().bold(), 116 | target: style().bright_red(), 117 | fields: style().bright_cyan(), 118 | } 119 | } 120 | 121 | // XXX same as with `light` in `color_eyre` 122 | /// A theme for a light background 123 | pub fn light() -> Self { 124 | Self { 125 | file: style().purple(), 126 | line_number: style().purple(), 127 | target: style().red(), 128 | fields: style().blue(), 129 | active_line: style().bold(), 130 | } 131 | } 132 | 133 | /// Styles printed paths 134 | pub fn file(mut self, style: Style) -> Self { 135 | self.file = style; 136 | self 137 | } 138 | 139 | /// Styles the line number of a file 140 | pub fn line_number(mut self, style: Style) -> Self { 141 | self.line_number = style; 142 | self 143 | } 144 | 145 | /// Styles the target (i.e. the module and function name, and so on) 146 | pub fn target(mut self, style: Style) -> Self { 147 | self.target = style; 148 | self 149 | } 150 | 151 | /// Styles fields associated with a the `tracing::Span`. 152 | pub fn fields(mut self, style: Style) -> Self { 153 | self.fields = style; 154 | self 155 | } 156 | 157 | /// Styles the selected line of displayed code 158 | pub fn active_line(mut self, style: Style) -> Self { 159 | self.active_line = style; 160 | self 161 | } 162 | } 163 | 164 | /// An error returned by `set_theme` if a global theme was already set 165 | #[derive(Debug)] 166 | pub struct InstallThemeError; 167 | 168 | impl fmt::Display for InstallThemeError { 169 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 170 | f.write_str("could not set the provided `Theme` globally as another was already set") 171 | } 172 | } 173 | 174 | impl std::error::Error for InstallThemeError {} 175 | 176 | /// Sets the global theme. 177 | /// 178 | /// # Details 179 | /// 180 | /// This can only be set once and otherwise fails. 181 | /// 182 | /// **Note:** `colorize` sets the global theme implicitly, if it was not set already. So calling `colorize` and then `set_theme` fails 183 | pub fn set_theme(theme: Theme) -> Result<(), InstallThemeError> { 184 | THEME.set(theme).map_err(|_| InstallThemeError) 185 | } 186 | 187 | /// Display a [`SpanTrace`] with colors and source 188 | /// 189 | /// This function returns an `impl Display` type which can be then used in place of the original 190 | /// SpanTrace when writing it too the screen or buffer. 191 | /// 192 | /// # Example 193 | /// 194 | /// ```rust 195 | /// use tracing_error::SpanTrace; 196 | /// 197 | /// let span_trace = SpanTrace::capture(); 198 | /// println!("{}", color_spantrace::colorize(&span_trace)); 199 | /// ``` 200 | /// 201 | /// **Note:** `colorize` sets the global theme implicitly, if it was not set already. So calling `colorize` and then `set_theme` fails 202 | /// 203 | /// [`SpanTrace`]: https://docs.rs/tracing-error/*/tracing_error/struct.SpanTrace.html 204 | pub fn colorize(span_trace: &SpanTrace) -> impl fmt::Display + '_ { 205 | let theme = *THEME.get_or_init(Theme::dark); 206 | ColorSpanTrace { span_trace, theme } 207 | } 208 | 209 | struct ColorSpanTrace<'a> { 210 | span_trace: &'a SpanTrace, 211 | theme: Theme, 212 | } 213 | 214 | macro_rules! try_bool { 215 | ($e:expr, $dest:ident) => {{ 216 | let ret = $e.unwrap_or_else(|e| $dest = Err(e)); 217 | 218 | if $dest.is_err() { 219 | return false; 220 | } 221 | 222 | ret 223 | }}; 224 | } 225 | 226 | struct Frame<'a> { 227 | metadata: &'a tracing_core::Metadata<'static>, 228 | fields: &'a str, 229 | theme: Theme, 230 | } 231 | 232 | /// Defines how verbose the backtrace is supposed to be. 233 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] 234 | enum Verbosity { 235 | /// Print a small message including the panic payload and the panic location. 236 | Minimal, 237 | /// Everything in `Minimal` and additionally print a backtrace. 238 | Medium, 239 | /// Everything in `Medium` plus source snippets for all backtrace locations. 240 | Full, 241 | } 242 | 243 | impl Verbosity { 244 | fn lib_from_env() -> Self { 245 | Self::convert_env( 246 | env::var("RUST_LIB_BACKTRACE") 247 | .or_else(|_| env::var("RUST_BACKTRACE")) 248 | .ok(), 249 | ) 250 | } 251 | 252 | fn convert_env(env: Option) -> Self { 253 | match env { 254 | Some(ref x) if x == "full" => Verbosity::Full, 255 | Some(_) => Verbosity::Medium, 256 | None => Verbosity::Minimal, 257 | } 258 | } 259 | } 260 | 261 | impl Frame<'_> { 262 | fn print(&self, i: u32, f: &mut fmt::Formatter<'_>) -> fmt::Result { 263 | self.print_header(i, f)?; 264 | self.print_fields(f)?; 265 | self.print_source_location(f)?; 266 | Ok(()) 267 | } 268 | 269 | fn print_header(&self, i: u32, f: &mut fmt::Formatter<'_>) -> fmt::Result { 270 | write!( 271 | f, 272 | "{:>2}: {}{}{}", 273 | i, 274 | self.theme.target.style(self.metadata.target()), 275 | self.theme.target.style("::"), 276 | self.theme.target.style(self.metadata.name()), 277 | ) 278 | } 279 | 280 | fn print_fields(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 281 | if !self.fields.is_empty() { 282 | write!(f, " with {}", self.theme.fields.style(self.fields))?; 283 | } 284 | 285 | Ok(()) 286 | } 287 | 288 | fn print_source_location(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 289 | if let Some(file) = self.metadata.file() { 290 | let lineno = self 291 | .metadata 292 | .line() 293 | .map_or("".to_owned(), |x| x.to_string()); 294 | write!( 295 | f, 296 | "\n at {}:{}", 297 | self.theme.file.style(file), 298 | self.theme.line_number.style(lineno), 299 | )?; 300 | } else { 301 | write!(f, "\n at ")?; 302 | } 303 | 304 | Ok(()) 305 | } 306 | 307 | fn print_source_if_avail(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 308 | let (lineno, filename) = match (self.metadata.line(), self.metadata.file()) { 309 | (Some(a), Some(b)) => (a, b), 310 | // Without a line number and file name, we can't sensibly proceed. 311 | _ => return Ok(()), 312 | }; 313 | 314 | let file = match File::open(filename) { 315 | Ok(file) => file, 316 | // ignore io errors and just don't print the source 317 | Err(_) => return Ok(()), 318 | }; 319 | 320 | use std::fmt::Write; 321 | 322 | // Extract relevant lines. 323 | let reader = BufReader::new(file); 324 | let start_line = lineno - 2.min(lineno - 1); 325 | let surrounding_src = reader.lines().skip(start_line as usize - 1).take(5); 326 | let mut buf = String::new(); 327 | for (line, cur_line_no) in surrounding_src.zip(start_line..) { 328 | if cur_line_no == lineno { 329 | write!( 330 | &mut buf, 331 | "{:>8} > {}", 332 | cur_line_no.to_string(), 333 | line.unwrap() 334 | )?; 335 | write!(f, "\n{}", self.theme.active_line.style(&buf))?; 336 | buf.clear(); 337 | } else { 338 | write!(f, "\n{:>8} │ {}", cur_line_no, line.unwrap())?; 339 | } 340 | } 341 | 342 | Ok(()) 343 | } 344 | } 345 | 346 | impl fmt::Display for ColorSpanTrace<'_> { 347 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 348 | let mut err = Ok(()); 349 | let mut span = 0; 350 | 351 | writeln!(f, "{:━^80}\n", " SPANTRACE ")?; 352 | self.span_trace.with_spans(|metadata, fields| { 353 | let frame = Frame { 354 | metadata, 355 | fields, 356 | theme: self.theme, 357 | }; 358 | 359 | if span > 0 { 360 | try_bool!(write!(f, "\n",), err); 361 | } 362 | 363 | try_bool!(frame.print(span, f), err); 364 | 365 | if Verbosity::lib_from_env() == Verbosity::Full { 366 | try_bool!(frame.print_source_if_avail(f), err); 367 | } 368 | 369 | span += 1; 370 | true 371 | }); 372 | 373 | err 374 | } 375 | } 376 | -------------------------------------------------------------------------------- /tests/data/theme_control.txt: -------------------------------------------------------------------------------- 1 | ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ SPANTRACE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2 | 3 | 0: themes::test_capture with x=42 4 | at tests/themes.rs:42 5 | 40 │ use tracing_subscriber::{prelude::*, registry::Registry}; 6 | 41 │ 7 |  42 > #[instrument] 8 | 43 │ fn test_capture(x: u8) -> SpanTrace { 9 | 44 │ #[allow(clippy::if_same_then_else)] -------------------------------------------------------------------------------- /tests/themes.rs: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | # How this test works: 4 | 5 | 1) generate a spantrace with `test_capture` 6 | 7 | 2) convert the spantrace to a string 8 | 9 | 3) load stored spantrace control to compare to spantrace string (stored in the path of `control_file_path` below) 10 | 11 | 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) 12 | 13 | 5) extract ANSI escaping sequences (of control and current spantrace) 14 | 15 | 6) compare if the current spantrace and the control contains the same ANSI escape sequences 16 | 17 | 7) If not, fail and show the full strings of the control and the current spantrace 18 | 19 | # Re-generating the control 20 | 21 | If the control spantrace is lost and/or it needs to be re-generated, do the following: 22 | 23 | 1) Checkout the `color_spantrace` version from Git that you want to test against 24 | 25 | 3) Add this test file to '/tests' 26 | 27 | 4) If `control_file_path` exist, delete it 28 | 29 | 5) If you now run this test, it will generate a test control file in the current working directory 30 | 31 | 6) copy this file to `control_file_path` (see instructions that are shown) 32 | 33 | */ 34 | 35 | use ansi_parser::{AnsiParser, AnsiSequence, Output}; 36 | use std::{fs, path::Path}; 37 | use tracing::instrument; 38 | use tracing_error::ErrorLayer; 39 | use tracing_error::SpanTrace; 40 | use tracing_subscriber::{prelude::*, registry::Registry}; 41 | 42 | #[instrument] 43 | fn test_capture(x: u8) -> SpanTrace { 44 | #[allow(clippy::if_same_then_else)] 45 | if x == 42 { 46 | SpanTrace::capture() 47 | } else { 48 | SpanTrace::capture() 49 | } 50 | } 51 | 52 | #[test] 53 | fn test_backwards_compatibility() { 54 | std::env::set_var("RUST_LIB_BACKTRACE", "full"); 55 | Registry::default().with(ErrorLayer::default()).init(); 56 | 57 | let spantrace = test_capture(42); 58 | let colored_spantrace = format!("{}", color_spantrace::colorize(&spantrace)); 59 | 60 | let control_file_name = "theme_control.txt"; 61 | let control_file_path = ["tests/data/", control_file_name].concat(); 62 | 63 | // 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. 64 | 65 | if !Path::new(&control_file_path).is_file() { 66 | std::fs::write(control_file_name, &colored_spantrace) 67 | .expect("\n\nError saving `colored_spanntrace` to a file"); 68 | 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); 69 | } 70 | 71 | // `unwrap` should never fail with files generated by this test 72 | let colored_spantrace_control = 73 | String::from_utf8(fs::read(control_file_path).unwrap()).unwrap(); 74 | 75 | fn get_ansi(s: &str) -> impl Iterator + '_ { 76 | s.ansi_parse().filter_map(|x| { 77 | if let Output::Escape(ansi) = x { 78 | Some(ansi) 79 | } else { 80 | None 81 | } 82 | }) 83 | } 84 | 85 | let colored_spantrace_ansi = get_ansi(&colored_spantrace); 86 | let colored_spantrace_control_ansi = get_ansi(&colored_spantrace_control); 87 | 88 | assert!( 89 | colored_spantrace_ansi.eq(colored_spantrace_control_ansi), 90 | "\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 91 | // `\x1b[0m` clears previous ANSI escape sequences 92 | ); 93 | } 94 | --------------------------------------------------------------------------------