├── .github └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── build.rs ├── example-report.md ├── examples ├── custom_collector.rs ├── readme.rs └── simple.rs ├── src ├── collector.rs ├── collector │ └── directory_entries.rs ├── format │ ├── markdown.rs │ ├── mod.rs │ └── plaintext.rs ├── helper.rs ├── lib.rs └── report.rs ├── test-crates ├── README.md ├── bugreport-client-with-git-hash-feature │ ├── .gitignore │ ├── Cargo.toml │ ├── src │ │ └── main.rs │ └── tests │ │ └── integration_tests.rs ├── bugreport-client-without-git-hash-feature │ ├── .gitignore │ ├── Cargo.toml │ ├── src │ │ └── main.rs │ └── tests │ │ └── integration_tests.rs ├── bugreport-test-crate-utils │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ └── lib.rs └── run-all-tests.sh └── tests └── test_collector_directory_entries.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: 2 | workflow_dispatch: 3 | pull_request: 4 | push: 5 | branches: 6 | - master 7 | tags: 8 | - '*' 9 | 10 | name: Build 11 | 12 | jobs: 13 | check: 14 | name: Check 15 | runs-on: ubuntu-latest 16 | strategy: 17 | matrix: 18 | rust: 19 | - stable 20 | - 1.74.0 21 | steps: 22 | - uses: actions/checkout@v2 23 | - uses: actions-rs/toolchain@v1 24 | with: 25 | profile: minimal 26 | toolchain: ${{ matrix.rust }} 27 | override: true 28 | - uses: actions-rs/cargo@v1 29 | name: "cargo check" 30 | with: 31 | command: check 32 | 33 | test: 34 | name: Test Suite 35 | runs-on: ubuntu-latest 36 | strategy: 37 | matrix: 38 | rust: 39 | - stable 40 | - 1.74.0 41 | steps: 42 | - uses: actions/checkout@v2 43 | - uses: actions-rs/toolchain@v1 44 | with: 45 | profile: minimal 46 | toolchain: ${{ matrix.rust }} 47 | override: true 48 | - uses: actions-rs/cargo@v1 49 | name: "cargo test" 50 | with: 51 | command: test 52 | - uses: actions-rs/cargo@v1 53 | name: "cargo test (no default features)" 54 | with: 55 | command: test 56 | args: --tests --no-default-features 57 | - uses: actions-rs/cargo@v1 58 | name: "cargo test (all features)" 59 | with: 60 | command: test 61 | args: --all-features 62 | 63 | run: 64 | name: Run examples 65 | strategy: 66 | fail-fast: false 67 | matrix: 68 | job: 69 | # Ubuntu 22.04 70 | - { os: ubuntu-22.04 , target: x86_64-unknown-linux-gnu , use-cross: false } 71 | - { os: ubuntu-22.04 , target: x86_64-unknown-linux-musl , use-cross: true } 72 | - { os: ubuntu-22.04 , target: arm-unknown-linux-gnueabihf , use-cross: true } 73 | - { os: ubuntu-22.04 , target: aarch64-unknown-linux-gnu , use-cross: true } 74 | - { os: ubuntu-22.04 , target: i586-unknown-linux-gnu , use-cross: true } 75 | - { os: ubuntu-22.04 , target: i686-unknown-linux-gnu , use-cross: true } 76 | - { os: ubuntu-22.04 , target: i686-unknown-linux-musl , use-cross: true } 77 | # Ubuntu 20.04 78 | - { os: ubuntu-20.04 , target: x86_64-unknown-linux-gnu , use-cross: false } 79 | - { os: ubuntu-20.04 , target: x86_64-unknown-linux-musl , use-cross: true } 80 | - { os: ubuntu-20.04 , target: arm-unknown-linux-gnueabihf , use-cross: true } 81 | - { os: ubuntu-20.04 , target: aarch64-unknown-linux-gnu , use-cross: true } 82 | - { os: ubuntu-20.04 , target: i586-unknown-linux-gnu , use-cross: true } 83 | - { os: ubuntu-20.04 , target: i686-unknown-linux-gnu , use-cross: true } 84 | - { os: ubuntu-20.04 , target: i686-unknown-linux-musl , use-cross: true } 85 | # MacOS 14 86 | - { os: macos-14 , target: aarch64-apple-darwin , use-cross: false } 87 | # Macos 13 88 | - { os: macos-13 , target: x86_64-apple-darwin , use-cross: false } 89 | # Windows 2022 90 | - { os: windows-2022 , target: i686-pc-windows-msvc , use-cross: false } 91 | - { os: windows-2022 , target: x86_64-pc-windows-gnu , use-cross: false } 92 | - { os: windows-2022 , target: x86_64-pc-windows-msvc , use-cross: false } 93 | # Windows 2019 94 | - { os: windows-2019 , target: i686-pc-windows-msvc , use-cross: false } 95 | - { os: windows-2019 , target: x86_64-pc-windows-gnu , use-cross: false } 96 | - { os: windows-2019 , target: x86_64-pc-windows-msvc , use-cross: false } 97 | 98 | runs-on: ${{ matrix.job.os }} 99 | steps: 100 | - uses: actions/checkout@v2 101 | - uses: actions-rs/toolchain@v1 102 | with: 103 | profile: minimal 104 | toolchain: stable 105 | target: ${{ matrix.job.target }} 106 | override: true 107 | - uses: actions-rs/cargo@v1 108 | name: "example 'readme'" 109 | env: 110 | SIMPLE_VAR_1: "'test value' in environment variable" 111 | with: 112 | use-cross: ${{ matrix.job.use-cross }} 113 | command: run 114 | args: --target ${{ matrix.job.target }} --example=readme -- "'test value' on command line" "two" "three" 115 | - uses: actions-rs/cargo@v1 116 | name: "example 'simple'" 117 | env: 118 | SIMPLE_VAR_1: "'test value' in environment variable" 119 | with: 120 | use-cross: ${{ matrix.job.use-cross }} 121 | command: run 122 | args: --target ${{ matrix.job.target }} --example=simple -- "'test value' on command line" "two" "three" 123 | - uses: actions-rs/cargo@v1 124 | name: "example 'custom_collector'" 125 | with: 126 | use-cross: ${{ matrix.job.use-cross }} 127 | command: run 128 | args: --target ${{ matrix.job.target }} --example=custom_collector -- "'test value' on command line" "two" "three" 129 | - name: "test-crates tests" 130 | run: ./test-crates/run-all-tests.sh 131 | 132 | fmt: 133 | name: Rustfmt 134 | runs-on: ubuntu-latest 135 | steps: 136 | - uses: actions/checkout@v2 137 | - uses: actions-rs/toolchain@v1 138 | with: 139 | profile: minimal 140 | toolchain: 1.74.0 141 | override: true 142 | - run: rustup component add rustfmt 143 | - uses: actions-rs/cargo@v1 144 | name: "cargo fmt" 145 | with: 146 | command: fmt 147 | args: --all -- --check 148 | 149 | clippy: 150 | name: Clippy 151 | runs-on: ubuntu-latest 152 | steps: 153 | - uses: actions/checkout@v2 154 | - uses: actions-rs/toolchain@v1 155 | with: 156 | profile: minimal 157 | toolchain: 1.74.0 158 | override: true 159 | - run: rustup component add clippy 160 | - uses: actions-rs/cargo@v1 161 | name: "cargo clippy" 162 | with: 163 | command: clippy 164 | args: -- -D warnings 165 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bugreport" 3 | description = "Collect system and environment information for bug reports" 4 | categories = ["command-line-interface"] 5 | homepage = "https://github.com/sharkdp/bugreport" 6 | repository = "https://github.com/sharkdp/bugreport" 7 | keywords = [ 8 | "bugreport", 9 | "diagnostics", 10 | "cross-platform", 11 | "cli", 12 | "terminal" 13 | ] 14 | license = "MIT/Apache-2.0" 15 | authors = ["David Peter "] 16 | edition = "2018" 17 | version = "0.5.0" 18 | 19 | [features] 20 | default = ["collector_operating_system", "git_hash", "format_markdown"] 21 | 22 | collector_operating_system = ["dep:sysinfo"] 23 | 24 | git_hash = ["git-version"] 25 | 26 | format_markdown = [] 27 | format_plaintext = [] 28 | 29 | [dependencies] 30 | sysinfo = { version = "0.33.1", optional = true } 31 | git-version = { version = "0.3", optional = true } 32 | shell-escape = "0.1" 33 | 34 | [dev-dependencies] 35 | pretty_assertions = "1.1.0" 36 | tempfile = "3.3.0" 37 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any person obtaining a copy 2 | of this software and associated documentation files (the "Software"), to deal 3 | in the Software without restriction, including without limitation the rights 4 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 5 | copies of the Software, and to permit persons to whom the Software is 6 | furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all 9 | copies or substantial portions of the Software. 10 | 11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 13 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 14 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 15 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 16 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 17 | SOFTWARE. 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bugreport 2 | 3 | [![Continuous integration](https://github.com/sharkdp/bugreport/workflows/Build/badge.svg)](https://github.com/sharkdp/bugreport/actions) [![Crates.io](https://img.shields.io/crates/v/bugreport.svg)](https://crates.io/crates/bugreport) 4 | [![Documentation](https://docs.rs/bugreport/badge.svg)](https://docs.rs/bugreport) 5 | 6 | `bugreport` is a Rust library that helps application developers to automatically collect 7 | information about the system and the environment that users can send along with a bug 8 | report (similar to `git bugreport` or `ffmpeg … -report`). 9 | 10 | **Note**: This library is in an early stage and the API may change in the future. 11 | 12 | ## Example 13 | 14 | The following code 15 | ```rust 16 | use bugreport::{bugreport, collector::*, format::Markdown}; 17 | 18 | fn main() { 19 | bugreport!() 20 | .info(SoftwareVersion::default()) 21 | .info(OperatingSystem::default()) 22 | .info(CommandLine::default()) 23 | .info(EnvironmentVariables::list(&["SHELL", "EDITOR"])) 24 | .info(CommandOutput::new("Python version", "python", &["-V"])) 25 | .info(CompileTimeInformation::default()) 26 | .print::(); 27 | } 28 | ``` 29 | generates bug report information that [looks like this](example-report.md). 30 | 31 | 32 | ## Collectors 33 | 34 | - [x] Crate information (name, version, git hash) 35 | - [x] Operating system (type, name, version) 36 | - [x] Command line (including all arguments) 37 | - [x] Environment variables (e.g. `SHELL`, `PATH`, …) 38 | - [x] File contents (e.g. config files) 39 | - [x] Directory contents 40 | - [x] Command output (e.g. `bash --version`) 41 | - [x] Compile time information (profile, target, architecture, cpu features, etc.) 42 | - [ ] Current working directory 43 | - [ ] Date and time 44 | - [x] User defined collectors 45 | 46 | ## Features 47 | 48 | - [x] Markdown export 49 | - [ ] Open report output in editor (instead of printing to stdout, see `git bugreport`) 50 | - [ ] Ask user for permission to gather information? 51 | - [ ] Automatic anonymization of information? (e.g.: remove `/home/username` from paths) 52 | - [ ] JSON export (?) 53 | 54 | ## Use cases / prior art 55 | 56 | - `ffmpeg`s `-report` option 57 | - Interesting: "Setting the environment variable FFREPORT to any value has the same effect." 58 | - see also: https://ffmpeg.org/bugreports.html 59 | - `git bugreport` 60 | - https://git-scm.com/docs/git-bugreport 61 | - git version --build-options 62 | - `grails bugreport` 63 | - http://docs.grails.org/3.1.1/ref/Command%20Line/bug-report.html 64 | 65 | # Related crates 66 | 67 | Other crates that might be useful: 68 | 69 | - [`human-panic`](https://crates.io/crates/human-panic) - Make panic messages nice for humans to read. 70 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Re-export variables that are only available at build.rs-time, but not 3 | // at compile time. 4 | for var in &[ 5 | "PROFILE", 6 | "TARGET", 7 | "CARGO_CFG_TARGET_FAMILY", 8 | "CARGO_CFG_TARGET_OS", 9 | "CARGO_CFG_TARGET_ARCH", 10 | "CARGO_CFG_TARGET_POINTER_WIDTH", 11 | "CARGO_CFG_TARGET_ENDIAN", 12 | "CARGO_CFG_TARGET_FEATURE", 13 | "HOST", 14 | ] { 15 | println!( 16 | "cargo:rustc-env=BUGREPORT_{}={}", 17 | var, 18 | std::env::var(var).unwrap_or_else(|_| "unknown".into()) 19 | ); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /example-report.md: -------------------------------------------------------------------------------- 1 | #### Software version 2 | 3 | bugreport 0.4.0 (4687617) 4 | 5 | #### Operating system 6 | 7 | - OS: Linux (Ubuntu 24.04) 8 | - Kernel: 6.8.0-48-generic 9 | 10 | #### Command-line 11 | 12 | ```bash 13 | /home/shark/.cargo-target/debug/examples/readme '"test value" on command line' two three 14 | ``` 15 | 16 | #### Environment variables 17 | 18 | ```bash 19 | SHELL=/usr/bin/zsh 20 | EDITOR=vim 21 | ``` 22 | 23 | #### Python version 24 | 25 | ``` 26 | > python -V 27 | Python 3.9.3 28 | ``` 29 | 30 | #### Compile time information 31 | 32 | - Profile: debug 33 | - Target triple: x86_64-unknown-linux-gnu 34 | - Family: unix 35 | - OS: linux 36 | - Architecture: x86_64 37 | - Pointer width: 64 38 | - Endian: little 39 | - CPU features: fxsr,sse,sse2 40 | - Host: x86_64-unknown-linux-gnu 41 | -------------------------------------------------------------------------------- /examples/custom_collector.rs: -------------------------------------------------------------------------------- 1 | use std::result::Result; 2 | 3 | use bugreport::{bugreport, collector::*, format::Markdown, report::ReportEntry, CrateInfo}; 4 | 5 | struct MyCollector {} 6 | 7 | impl Collector for MyCollector { 8 | fn description(&self) -> &str { 9 | "My collector" 10 | } 11 | 12 | fn collect(&mut self, _: &CrateInfo) -> Result { 13 | Ok(ReportEntry::Text("custom information".into())) 14 | } 15 | } 16 | 17 | fn main() { 18 | bugreport!() 19 | .info(SoftwareVersion::default()) 20 | .info(MyCollector {}) 21 | .print::(); 22 | } 23 | -------------------------------------------------------------------------------- /examples/readme.rs: -------------------------------------------------------------------------------- 1 | // Update the code example in README.md whenever this example is changed. 2 | 3 | use bugreport::{bugreport, collector::*, format::Markdown}; 4 | 5 | fn main() { 6 | bugreport!() 7 | .info(SoftwareVersion::default()) 8 | .info(OperatingSystem::default()) 9 | .info(CommandLine::default()) 10 | .info(EnvironmentVariables::list(&["SHELL", "EDITOR"])) 11 | .info(CommandOutput::new("Python version", "python", &["-V"])) 12 | .info(CompileTimeInformation::default()) 13 | .print::(); 14 | } 15 | -------------------------------------------------------------------------------- /examples/simple.rs: -------------------------------------------------------------------------------- 1 | use bugreport::{bugreport, collector::*, format::Markdown}; 2 | 3 | fn main() { 4 | bugreport!() 5 | .info(SoftwareVersion::default()) 6 | .info(OperatingSystem::default()) 7 | .info(CommandLine::default()) 8 | .info(EnvironmentVariables::list(&[ 9 | "SHELL", 10 | "PATH", 11 | "SIMPLE_VAR_1", 12 | "SIMPLE_VAR_2", 13 | ])) 14 | .info(CommandOutput::new("System information", "uname", &["-a"])) 15 | .info(FileContent::new("Load average", "/proc/loadavg")) 16 | .info(CompileTimeInformation::default()) 17 | .print::(); 18 | } 19 | -------------------------------------------------------------------------------- /src/collector.rs: -------------------------------------------------------------------------------- 1 | //! Contains all builtin information collectors and the [`Collector`] trait to implement your own. 2 | 3 | use std::borrow::Cow; 4 | use std::ffi::{OsStr, OsString}; 5 | use std::fmt::Write; 6 | use std::fs; 7 | use std::path::{Path, PathBuf}; 8 | use std::process::Command; 9 | 10 | use super::CrateInfo; 11 | use super::Result; 12 | 13 | use crate::helper::StringExt; 14 | use crate::report::{Code, ReportEntry}; 15 | 16 | mod directory_entries; 17 | pub use directory_entries::DirectoryEntries; 18 | 19 | /// Error that appeared while collecting bug report information. 20 | #[derive(Debug)] 21 | pub enum CollectionError { 22 | CouldNotRetrieve(String), 23 | } 24 | 25 | impl CollectionError { 26 | pub(crate) fn to_entry(&self) -> ReportEntry { 27 | use CollectionError::*; 28 | 29 | match self { 30 | CouldNotRetrieve(reason) => ReportEntry::Text(reason.clone()), 31 | } 32 | } 33 | } 34 | 35 | /// Implement this trait to define customized information collectors. 36 | pub trait Collector { 37 | fn description(&self) -> &str; 38 | fn collect(&mut self, crate_info: &CrateInfo) -> Result; 39 | } 40 | 41 | /// The name of your crate and the current version. 42 | #[derive(Default)] 43 | pub struct SoftwareVersion { 44 | version: Option, 45 | } 46 | 47 | impl SoftwareVersion { 48 | pub fn custom>(version: S) -> Self { 49 | Self { 50 | version: Some(version.as_ref().into()), 51 | } 52 | } 53 | } 54 | 55 | impl Collector for SoftwareVersion { 56 | fn description(&self) -> &str { 57 | "Software version" 58 | } 59 | 60 | fn collect(&mut self, crate_info: &CrateInfo) -> Result { 61 | let git_hash_suffix = match crate_info.git_hash { 62 | Some(git_hash) => format!(" ({})", git_hash), 63 | None => String::new(), 64 | }; 65 | 66 | Ok(ReportEntry::Text(format!( 67 | "{} {}{}", 68 | crate_info.pkg_name, 69 | self.version.as_deref().unwrap_or(crate_info.pkg_version), 70 | git_hash_suffix, 71 | ))) 72 | } 73 | } 74 | 75 | /// Compile-time information such as the profile (release/debug) and the target triple. 76 | #[derive(Default)] 77 | pub struct CompileTimeInformation {} 78 | 79 | impl Collector for CompileTimeInformation { 80 | fn description(&self) -> &str { 81 | "Compile time information" 82 | } 83 | 84 | fn collect(&mut self, _: &CrateInfo) -> Result { 85 | Ok(ReportEntry::List(vec![ 86 | ReportEntry::Text(format!("Profile: {}", env!("BUGREPORT_PROFILE"))), 87 | ReportEntry::Text(format!("Target triple: {}", env!("BUGREPORT_TARGET"))), 88 | ReportEntry::Text(format!( 89 | "Family: {}", 90 | env!("BUGREPORT_CARGO_CFG_TARGET_FAMILY") 91 | )), 92 | ReportEntry::Text(format!("OS: {}", env!("BUGREPORT_CARGO_CFG_TARGET_OS"))), 93 | ReportEntry::Text(format!( 94 | "Architecture: {}", 95 | env!("BUGREPORT_CARGO_CFG_TARGET_ARCH") 96 | )), 97 | ReportEntry::Text(format!( 98 | "Pointer width: {}", 99 | env!("BUGREPORT_CARGO_CFG_TARGET_POINTER_WIDTH") 100 | )), 101 | ReportEntry::Text(format!( 102 | "Endian: {}", 103 | env!("BUGREPORT_CARGO_CFG_TARGET_ENDIAN") 104 | )), 105 | ReportEntry::Text(format!( 106 | "CPU features: {}", 107 | env!("BUGREPORT_CARGO_CFG_TARGET_FEATURE") 108 | )), 109 | ReportEntry::Text(format!("Host: {}", env!("BUGREPORT_HOST"))), 110 | ])) 111 | } 112 | } 113 | 114 | /// The full command-line: executable name and arguments to the program. 115 | #[derive(Default)] 116 | pub struct CommandLine {} 117 | 118 | impl Collector for CommandLine { 119 | fn description(&self) -> &str { 120 | "Command-line" 121 | } 122 | 123 | fn collect(&mut self, _: &CrateInfo) -> Result { 124 | let mut result = String::new(); 125 | 126 | for arg in std::env::args_os() { 127 | result += &shell_escape::escape(arg.to_string_lossy()); 128 | result += " "; 129 | } 130 | 131 | Ok(ReportEntry::Code(Code { 132 | language: Some("bash".into()), 133 | code: result, 134 | })) 135 | } 136 | } 137 | 138 | /// The operating system (type and version). 139 | #[cfg(feature = "collector_operating_system")] 140 | #[derive(Default)] 141 | pub struct OperatingSystem {} 142 | 143 | #[cfg(feature = "collector_operating_system")] 144 | impl Collector for OperatingSystem { 145 | fn description(&self) -> &str { 146 | "Operating system" 147 | } 148 | 149 | fn collect(&mut self, _: &CrateInfo) -> Result { 150 | Ok(ReportEntry::List(vec![ 151 | ReportEntry::Text(format!( 152 | "OS: {}", 153 | sysinfo::System::long_os_version().unwrap_or_else(|| "Unknown".to_owned()), 154 | )), 155 | ReportEntry::Text(format!( 156 | "Kernel: {}", 157 | sysinfo::System::kernel_version().unwrap_or_else(|| "Unknown".to_owned()), 158 | )), 159 | ])) 160 | } 161 | } 162 | 163 | /// The values of the specified environment variables (if set). 164 | pub struct EnvironmentVariables { 165 | list: Vec, 166 | } 167 | 168 | impl EnvironmentVariables { 169 | pub fn list>(list: &[S]) -> Self { 170 | Self { 171 | list: list.iter().map(|s| s.as_ref().to_os_string()).collect(), 172 | } 173 | } 174 | } 175 | 176 | impl Collector for EnvironmentVariables { 177 | fn description(&self) -> &str { 178 | "Environment variables" 179 | } 180 | 181 | fn collect(&mut self, _: &CrateInfo) -> Result { 182 | let mut result = String::new(); 183 | 184 | for var in &self.list { 185 | let value = std::env::var_os(var).map(|value| value.to_string_lossy().into_owned()); 186 | let value: Option = 187 | value.map(|v| shell_escape::escape(Cow::Borrowed(&v)).into()); 188 | 189 | let _ = writeln!( 190 | result, 191 | "{}={}", 192 | var.to_string_lossy(), 193 | value.unwrap_or_else(|| "".into()) 194 | ); 195 | } 196 | result.pop(); 197 | 198 | Ok(ReportEntry::Code(Code { 199 | language: Some("bash".into()), 200 | code: result, 201 | })) 202 | } 203 | } 204 | 205 | /// The stdout and stderr output (+ exit code) of a custom command. 206 | pub struct CommandOutput<'a> { 207 | title: &'a str, 208 | cmd: OsString, 209 | cmd_args: Vec, 210 | } 211 | 212 | impl<'a> CommandOutput<'a> { 213 | pub fn new(title: &'a str, cmd: T, args: &[S]) -> Self 214 | where 215 | T: AsRef, 216 | S: AsRef, 217 | { 218 | let mut cmd_args: Vec = Vec::new(); 219 | for a in args { 220 | cmd_args.push(a.into()); 221 | } 222 | 223 | CommandOutput { 224 | title, 225 | cmd: cmd.as_ref().to_owned(), 226 | cmd_args, 227 | } 228 | } 229 | } 230 | 231 | impl<'a> Collector for CommandOutput<'a> { 232 | fn description(&self) -> &str { 233 | self.title 234 | } 235 | 236 | fn collect(&mut self, _: &CrateInfo) -> Result { 237 | let mut result = String::new(); 238 | 239 | result += "> "; 240 | result += &self.cmd.to_string_lossy(); 241 | result += " "; 242 | for arg in &self.cmd_args { 243 | result += &shell_escape::escape(arg.to_string_lossy()); 244 | result += " "; 245 | } 246 | 247 | result += "\n"; 248 | 249 | let output = Command::new(&self.cmd) 250 | .args(&self.cmd_args) 251 | .output() 252 | .map_err(|e| { 253 | CollectionError::CouldNotRetrieve(format!( 254 | "Could not run command '{}': {}", 255 | self.cmd.to_string_lossy(), 256 | e 257 | )) 258 | })?; 259 | 260 | let utf8_decoding_error = |_| { 261 | CollectionError::CouldNotRetrieve(format!( 262 | "Error while running command '{}': output is not valid UTF-8.", 263 | self.cmd.to_string_lossy() 264 | )) 265 | }; 266 | 267 | let stdout = String::from_utf8(output.stdout).map_err(utf8_decoding_error)?; 268 | let stderr = String::from_utf8(output.stderr).map_err(utf8_decoding_error)?; 269 | 270 | result += &stdout; 271 | result += &stderr; 272 | 273 | result.trim_end_inplace(); 274 | 275 | let mut concat = vec![ReportEntry::Code(Code { 276 | language: None, 277 | code: result, 278 | })]; 279 | 280 | if !output.status.success() { 281 | concat.push(ReportEntry::Text(format!( 282 | "Command failed{}.", 283 | output 284 | .status 285 | .code() 286 | .map_or("".into(), |c| format!(" with exit code {}", c)) 287 | ))); 288 | } 289 | 290 | Ok(ReportEntry::Concat(concat)) 291 | } 292 | } 293 | 294 | /// The full content of a text file. 295 | pub struct FileContent<'a> { 296 | title: &'a str, 297 | path: PathBuf, 298 | } 299 | 300 | impl<'a> FileContent<'a> { 301 | pub fn new>(title: &'a str, path: P) -> Self { 302 | Self { 303 | title, 304 | path: path.as_ref().to_path_buf(), 305 | } 306 | } 307 | } 308 | 309 | impl<'a> Collector for FileContent<'a> { 310 | fn description(&self) -> &str { 311 | self.title 312 | } 313 | 314 | fn collect(&mut self, _: &CrateInfo) -> Result { 315 | let mut result = fs::read_to_string(&self.path).map_err(|e| { 316 | CollectionError::CouldNotRetrieve(format!( 317 | "Could not read contents of '{}': {}.", 318 | self.path.to_string_lossy(), 319 | e 320 | )) 321 | })?; 322 | 323 | result.trim_end_inplace(); 324 | 325 | Ok(ReportEntry::Code(Code { 326 | language: None, 327 | code: result, 328 | })) 329 | } 330 | } 331 | -------------------------------------------------------------------------------- /src/collector/directory_entries.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Write; 2 | use std::fs::{self, DirEntry}; 3 | use std::io::ErrorKind; 4 | use std::path::{Path, PathBuf}; 5 | 6 | use crate::{report::ReportEntry, Collector, CrateInfo, Result}; 7 | 8 | use super::CollectionError; 9 | 10 | /// List information about entries in a directory. 11 | /// 12 | /// Limitations: 13 | /// * Is not recursive 14 | /// * Does not handle symbolic links 15 | /// * Only sizes of files are printed and not e.g. time of last modification 16 | /// 17 | /// # Example 18 | /// 19 | /// ```md 20 | /// #### File and dir 21 | /// 22 | /// - file.txt, 14 bytes 23 | /// - some_dir/ 24 | /// 25 | /// ``` 26 | pub struct DirectoryEntries { 27 | title: String, 28 | path: PathBuf, 29 | } 30 | 31 | impl<'a> DirectoryEntries { 32 | pub fn new>(title: &'a str, path: P) -> Self { 33 | Self { 34 | title: title.into(), 35 | path: path.as_ref().to_path_buf(), 36 | } 37 | } 38 | } 39 | 40 | impl Collector for DirectoryEntries { 41 | fn description(&self) -> &str { 42 | &self.title 43 | } 44 | 45 | fn collect(&mut self, _: &CrateInfo) -> Result { 46 | let path_str = &self.path.to_string_lossy(); 47 | 48 | let mut entries = fs::read_dir(&self.path) 49 | .map_err(|e| read_dir_error_to_report_entry(e, path_str))? 50 | .map(|e| match e { 51 | Ok(dir_entry) => dir_entry_to_report_entry(dir_entry), 52 | Err(e) => format!("Error: {}", e), 53 | }) 54 | .collect::>(); 55 | 56 | // For stable ordering 57 | entries.sort(); 58 | 59 | if entries.is_empty() { 60 | Ok(ReportEntry::Text(format!("'{}' is empty", path_str))) 61 | } else { 62 | Ok(ReportEntry::List( 63 | entries.into_iter().map(ReportEntry::Text).collect(), 64 | )) 65 | } 66 | } 67 | } 68 | 69 | fn read_dir_error_to_report_entry(error: std::io::Error, path_str: &str) -> CollectionError { 70 | CollectionError::CouldNotRetrieve(if error.kind() == ErrorKind::NotFound { 71 | format!("'{}' not found", path_str) 72 | } else { 73 | format!("'{}' not read: {}", path_str, error) 74 | }) 75 | } 76 | 77 | fn dir_entry_to_report_entry(dir_entry: DirEntry) -> String { 78 | let mut text = String::new(); 79 | 80 | text.push_str(&dir_entry.file_name().to_string_lossy()); 81 | 82 | if let Ok(metadata) = dir_entry.metadata() { 83 | if metadata.is_file() { 84 | let _ = write!(text, ", {} bytes", metadata.len()); 85 | } else if metadata.is_dir() { 86 | text.push(std::path::MAIN_SEPARATOR); 87 | } 88 | } 89 | 90 | text 91 | } 92 | -------------------------------------------------------------------------------- /src/format/markdown.rs: -------------------------------------------------------------------------------- 1 | use super::Format; 2 | use crate::report::ReportEntry; 3 | 4 | #[derive(Default)] 5 | pub struct Markdown {} 6 | 7 | impl Format for Markdown { 8 | fn format_section(&mut self, title: &str) -> String { 9 | format!("#### {}\n\n", title) 10 | } 11 | 12 | fn format_entry(&mut self, entry: &ReportEntry) -> String { 13 | use ReportEntry::*; 14 | 15 | match entry { 16 | Text(content) => format!("{}\n", content), 17 | Code(c) => format!( 18 | "```{}\n{}\n```\n", 19 | c.language.as_deref().unwrap_or(""), 20 | c.code 21 | ), 22 | List(entries) => { 23 | let mut result = String::new(); 24 | for entry in entries { 25 | result += "- "; 26 | result += &self.format_entry(entry); 27 | } 28 | result 29 | } 30 | Concat(entries) => { 31 | let mut result = String::new(); 32 | for entry in entries { 33 | result += &self.format_entry(entry); 34 | } 35 | result 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/format/mod.rs: -------------------------------------------------------------------------------- 1 | //! Different formats for printing the report. 2 | 3 | use crate::report::ReportEntry; 4 | 5 | #[cfg(feature = "format_markdown")] 6 | mod markdown; 7 | #[cfg(feature = "format_plaintext")] 8 | mod plaintext; 9 | 10 | #[cfg(feature = "format_markdown")] 11 | pub use markdown::Markdown; 12 | #[cfg(feature = "format_plaintext")] 13 | pub use plaintext::Plaintext; 14 | 15 | pub trait Format: Default { 16 | fn format_section(&mut self, title: &str) -> String; 17 | fn format_entry(&mut self, entry: &ReportEntry) -> String; 18 | } 19 | -------------------------------------------------------------------------------- /src/format/plaintext.rs: -------------------------------------------------------------------------------- 1 | use super::Format; 2 | use crate::report::ReportEntry; 3 | 4 | #[derive(Default)] 5 | pub struct Plaintext {} 6 | 7 | impl Format for Plaintext { 8 | fn format_section(&mut self, title: &str) -> String { 9 | format!("{:-^1$}\n", title, 48) 10 | } 11 | 12 | fn format_entry(&mut self, entry: &ReportEntry) -> String { 13 | use ReportEntry::*; 14 | 15 | match entry { 16 | Text(content) => format!("{}\n", content), 17 | Code(c) => format!("{}\n", c.code), 18 | List(entries) => { 19 | let mut result = String::new(); 20 | for entry in entries { 21 | result += "- "; 22 | result += &self.format_entry(entry); 23 | } 24 | result 25 | } 26 | Concat(entries) => { 27 | let mut result = String::new(); 28 | for entry in entries { 29 | result += &self.format_entry(entry); 30 | } 31 | result 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/helper.rs: -------------------------------------------------------------------------------- 1 | pub(crate) trait StringExt { 2 | fn trim_end_inplace(&mut self); 3 | } 4 | 5 | impl StringExt for String { 6 | fn trim_end_inplace(&mut self) { 7 | self.truncate(self.trim_end().len()); 8 | } 9 | } 10 | 11 | #[test] 12 | fn test_trim_end_inplace() { 13 | let mut s = String::from("test string \n\n"); 14 | s.trim_end_inplace(); 15 | 16 | assert_eq!(s, "test string"); 17 | } 18 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! `bugreport` is a library that helps application developers to automatically collect 2 | //! information about the system and the environment that users can send along with a bug 3 | //! report (similar to `git bugreport` or `ffmpeg … -report`). 4 | //! 5 | //! Usage example: 6 | //! ``` 7 | //! use bugreport::{bugreport, collector::*, format::Markdown}; 8 | //! 9 | //! bugreport!() 10 | //! .info(SoftwareVersion::default()) 11 | //! .info(OperatingSystem::default()) 12 | //! .info(CommandLine::default()) 13 | //! .info(EnvironmentVariables::list(&["SHELL", "EDITOR"])) 14 | //! .info(CommandOutput::new("Python version", "python", &["--version"])) 15 | //! .info(CompileTimeInformation::default()) 16 | //! .print::(); 17 | //! ``` 18 | 19 | use std::result; 20 | 21 | pub mod collector; 22 | pub mod format; 23 | mod helper; 24 | pub mod report; 25 | 26 | use collector::{CollectionError, Collector}; 27 | use format::Format; 28 | use report::{Report, ReportSection}; 29 | 30 | pub(crate) type Result = result::Result; 31 | 32 | #[doc(hidden)] 33 | pub struct CrateInfo<'a> { 34 | pkg_name: &'a str, 35 | pkg_version: &'a str, 36 | git_hash: Option<&'a str>, 37 | } 38 | 39 | /// The main struct for collecting bug report information. 40 | /// 41 | /// Use the [`bugreport`] macro to create one. 42 | pub struct BugReport<'a> { 43 | info: CrateInfo<'a>, 44 | collectors: Vec>, 45 | } 46 | 47 | impl<'a> BugReport<'a> { 48 | #[doc(hidden)] 49 | pub fn from_name_and_version(pkg_name: &'a str, pkg_version: &'a str) -> Self { 50 | BugReport { 51 | info: CrateInfo { 52 | pkg_name, 53 | pkg_version, 54 | git_hash: None, 55 | }, 56 | collectors: vec![], 57 | } 58 | } 59 | 60 | #[doc(hidden)] 61 | pub fn set_git_hash(&mut self, git_hash: Option<&'a str>) { 62 | self.info.git_hash = git_hash; 63 | } 64 | 65 | /// Add a [`Collector`] to the bug report. 66 | pub fn info(mut self, collector: C) -> Self { 67 | self.collectors.push(Box::new(collector)); 68 | self 69 | } 70 | 71 | fn generate(&mut self) -> Report { 72 | let mut sections = vec![]; 73 | 74 | for collector in &mut self.collectors { 75 | let entry = collector 76 | .collect(&self.info) 77 | .unwrap_or_else(|e| e.to_entry()); 78 | sections.push(ReportSection { 79 | title: collector.description(), 80 | entry, 81 | }); 82 | } 83 | 84 | Report { sections } 85 | } 86 | 87 | /// Assemble the bug report information using the given format. 88 | pub fn format(&mut self) -> String { 89 | let mut format = F::default(); 90 | self.generate().format_as(&mut format) 91 | } 92 | 93 | /// Print the bug report information using the given format. 94 | pub fn print(&mut self) { 95 | println!("{}", self.format::()); 96 | } 97 | } 98 | 99 | /// Re-export so dependent project does not have to manually depend on git-version crate 100 | #[cfg(feature = "git_hash")] 101 | pub use git_version::git_version; 102 | 103 | #[cfg(feature = "git_hash")] 104 | #[doc(hidden)] 105 | #[macro_export] 106 | macro_rules! bugreport_set_git_hash { 107 | ($br:ident) => {{ 108 | let hash = bugreport::git_version!(fallback = ""); 109 | if !hash.is_empty() { 110 | $br.set_git_hash(Some(hash)); 111 | } 112 | }}; 113 | } 114 | 115 | #[cfg(not(feature = "git_hash"))] 116 | #[doc(hidden)] 117 | #[macro_export] 118 | macro_rules! bugreport_set_git_hash { 119 | ($br:ident) => {}; 120 | } 121 | 122 | /// Generate a new [`BugReport`] object. 123 | #[macro_export] 124 | macro_rules! bugreport { 125 | () => {{ 126 | let mut br = bugreport::BugReport::from_name_and_version( 127 | env!("CARGO_PKG_NAME"), 128 | env!("CARGO_PKG_VERSION"), 129 | ); 130 | bugreport::bugreport_set_git_hash!(br); 131 | br 132 | }}; 133 | } 134 | 135 | #[cfg(test)] 136 | mod tests { 137 | #[test] 138 | #[cfg(feature = "format_markdown")] 139 | fn basic() { 140 | use super::BugReport; 141 | use crate::collector::*; 142 | use crate::format::Markdown; 143 | 144 | std::env::set_var("BUGREPORT_TEST", "42"); 145 | 146 | let report = BugReport::from_name_and_version("dummy", "0.1") 147 | .info(EnvironmentVariables::list(&["BUGREPORT_TEST"])) 148 | .format::(); 149 | 150 | assert_eq!( 151 | report, 152 | "#### Environment variables\n\ 153 | \n\ 154 | ```bash\n\ 155 | BUGREPORT_TEST=42\n\ 156 | ```\n\n" 157 | ); 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/report.rs: -------------------------------------------------------------------------------- 1 | //! Defines the document structure of the report. Only needed for custom collectors. 2 | 3 | use crate::format::Format; 4 | 5 | #[derive(Debug)] 6 | pub struct Code { 7 | pub language: Option, 8 | pub code: String, 9 | } 10 | 11 | #[derive(Debug)] 12 | pub enum ReportEntry { 13 | Text(String), 14 | Code(Code), 15 | List(Vec), 16 | Concat(Vec), 17 | } 18 | 19 | #[derive(Debug)] 20 | pub(crate) struct ReportSection<'a> { 21 | pub(crate) title: &'a str, 22 | pub(crate) entry: ReportEntry, 23 | } 24 | 25 | impl ReportEntry {} 26 | 27 | #[derive(Debug)] 28 | pub(crate) struct Report<'a> { 29 | pub(crate) sections: Vec>, 30 | } 31 | 32 | impl<'a> Report<'a> { 33 | pub fn format_as(&self, format: &mut impl Format) -> String { 34 | let mut result = String::new(); 35 | for section in &self.sections { 36 | result += &format.format_section(section.title); 37 | result += &format.format_entry(§ion.entry); 38 | result += "\n"; 39 | } 40 | 41 | result 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /test-crates/README.md: -------------------------------------------------------------------------------- 1 | This directory contains crates used to test `bugreport`. 2 | 3 | It is insufficient to test bugreport with regular crate test facilities, due to 4 | how bugreport is implemented. 5 | 6 | Since bugreport uses a `bugreport!()` macro that is evaluated in the context of 7 | a dependent crate, it is important to test evaluation of that macro in an 8 | external create. Otherwise the test will not detect problems such as having 9 | `#[cfg(feature = "git_hash")]` inside the `bugreport!()` macro. Since the macro 10 | is evaluated in the context of the dependent crate, that feature will not be 11 | defined in that context. 12 | -------------------------------------------------------------------------------- /test-crates/bugreport-client-with-git-hash-feature/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /test-crates/bugreport-client-with-git-hash-feature/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bugreport-client-with-git-hash-feature" 3 | description = "To test bugreport!() macro evaluation in a separate crate with git_hash." 4 | version = "0.1.0" 5 | authors = ["Martin Nordholts "] 6 | edition = "2018" 7 | 8 | [dependencies] 9 | bugreport = { path = "../..", default-features = false, features = ["git_hash", "format_markdown"] } 10 | bugreport-test-crate-utils = { path = "../bugreport-test-crate-utils" } 11 | -------------------------------------------------------------------------------- /test-crates/bugreport-client-with-git-hash-feature/src/main.rs: -------------------------------------------------------------------------------- 1 | use bugreport::{bugreport, collector::*, format::Markdown}; 2 | 3 | fn main() { 4 | bugreport!() 5 | .info(SoftwareVersion::default()) 6 | .print::(); 7 | } 8 | -------------------------------------------------------------------------------- /test-crates/bugreport-client-with-git-hash-feature/tests/integration_tests.rs: -------------------------------------------------------------------------------- 1 | use bugreport_test_crate_utils::assert_bin_stdout; 2 | 3 | #[test] 4 | fn with_git_repo() { 5 | assert_bin_stdout( 6 | "bugreport-client-with-git-hash-feature", 7 | r"#### Software version 8 | 9 | bugreport-client-with-git-hash-feature 0\.1\.0 \([0-9a-f]{7,}(-modified)?\) 10 | 11 | 12 | ", 13 | ); 14 | } 15 | 16 | // NOTE: You must only run this test with GIT_DIR set to 17 | // something at build time that is not a git repo 18 | #[test] 19 | fn without_git_repo() { 20 | assert_bin_stdout( 21 | "bugreport-client-with-git-hash-feature", 22 | r"#### Software version 23 | 24 | bugreport-client-with-git-hash-feature 0\.1\.0 25 | 26 | 27 | ", 28 | ); 29 | } 30 | -------------------------------------------------------------------------------- /test-crates/bugreport-client-without-git-hash-feature/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /test-crates/bugreport-client-without-git-hash-feature/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bugreport-client-without-git-hash-feature" 3 | description = "To test bugreport!() macro evaluation in a separate crate without git_hash." 4 | version = "0.1.0" 5 | authors = ["Martin Nordholts "] 6 | edition = "2018" 7 | 8 | [dependencies] 9 | bugreport = { path = "../..", default-features = false, features = ["format_markdown"] } 10 | bugreport-test-crate-utils = { path = "../bugreport-test-crate-utils" } 11 | -------------------------------------------------------------------------------- /test-crates/bugreport-client-without-git-hash-feature/src/main.rs: -------------------------------------------------------------------------------- 1 | use bugreport::{bugreport, collector::*, format::Markdown}; 2 | 3 | fn main() { 4 | bugreport!() 5 | .info(SoftwareVersion::default()) 6 | .print::(); 7 | } 8 | -------------------------------------------------------------------------------- /test-crates/bugreport-client-without-git-hash-feature/tests/integration_tests.rs: -------------------------------------------------------------------------------- 1 | use bugreport_test_crate_utils::assert_bin_stdout; 2 | 3 | #[test] 4 | fn with_git_repo() { 5 | assert_bin_stdout( 6 | "bugreport-client-without-git-hash-feature", 7 | r"#### Software version 8 | 9 | bugreport-client-without-git-hash-feature 0\.1\.0 10 | 11 | 12 | ", 13 | ); 14 | } 15 | 16 | // NOTE: You must only run this test with GIT_DIR set to 17 | // something at build time that is not a git repo 18 | #[test] 19 | fn without_git_repo() { 20 | assert_bin_stdout( 21 | "bugreport-client-without-git-hash-feature", 22 | r"#### Software version 23 | 24 | bugreport-client-without-git-hash-feature 0\.1\.0 25 | 26 | 27 | ", 28 | ); 29 | } 30 | -------------------------------------------------------------------------------- /test-crates/bugreport-test-crate-utils/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /test-crates/bugreport-test-crate-utils/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bugreport-test-crate-utils" 3 | version = "0.1.0" 4 | authors = ["Martin Nordholts "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | assert_cmd = "1.0" 9 | predicates = { version = "1.0", default-features = false, features = ["regex", "normalize-line-endings"] } 10 | -------------------------------------------------------------------------------- /test-crates/bugreport-test-crate-utils/src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::process::Command as StdCommand; 2 | 3 | use predicates::prelude::*; 4 | 5 | use assert_cmd::cargo::CommandCargoExt; 6 | use assert_cmd::Command; 7 | 8 | pub fn assert_bin_stdout(bin: &str, regex: &str) { 9 | Command::from_std(StdCommand::cargo_bin(bin).unwrap()) 10 | .assert() 11 | .stdout(predicates::str::is_match(regex).unwrap().normalize()); 12 | } 13 | -------------------------------------------------------------------------------- /test-crates/run-all-tests.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -o errexit -o nounset -o pipefail 4 | 5 | script_path="$(pwd)/$(dirname ${BASH_SOURCE})" 6 | 7 | test_crates=" 8 | bugreport-client-with-git-hash-feature 9 | bugreport-client-without-git-hash-feature 10 | " 11 | 12 | for test_crate in ${test_crates}; do 13 | cd ${script_path}/${test_crate} 14 | 15 | # Test with a git repo (our own) 16 | unset GIT_DIR 17 | cargo clean -p ${test_crate} 18 | cargo test with_git_repo 19 | 20 | # Test without a git repo 21 | export GIT_DIR=this-is-not-a-git-repo 22 | cargo clean -p ${test_crate} 23 | cargo test without_git_repo 24 | done 25 | -------------------------------------------------------------------------------- /tests/test_collector_directory_entries.rs: -------------------------------------------------------------------------------- 1 | #![cfg(feature = "format_markdown")] 2 | 3 | use std::path::PathBuf; 4 | 5 | use pretty_assertions::assert_eq; 6 | use tempfile::tempdir; 7 | 8 | use bugreport::{bugreport, collector::DirectoryEntries, format::Markdown}; 9 | 10 | #[test] 11 | fn dir_not_found() { 12 | let actual = bugreport!() 13 | .info(DirectoryEntries::new("No dir", "this-dir-does-not-exist")) 14 | .format::(); 15 | 16 | let expected = "#### No dir 17 | 18 | 'this-dir-does-not-exist' not found 19 | 20 | "; 21 | 22 | assert_eq!(expected, actual); 23 | } 24 | 25 | #[test] 26 | fn dir_is_empty() -> Result<(), std::io::Error> { 27 | let empty_dir = tempdir()?; 28 | let empty_dir_path = empty_dir.path(); 29 | 30 | let actual = bugreport!() 31 | .info(DirectoryEntries::new("Empty dir", empty_dir_path)) 32 | .format::(); 33 | 34 | let expected = format!( 35 | "#### Empty dir 36 | 37 | '{}' is empty 38 | 39 | ", 40 | empty_dir_path.to_string_lossy() 41 | ); 42 | 43 | assert_eq!(expected, actual); 44 | 45 | Ok(()) 46 | } 47 | 48 | #[test] 49 | fn dir_exists() -> Result<(), std::io::Error> { 50 | let dir = tempdir()?; 51 | let dir_path = dir.path(); 52 | 53 | // Put a file in the dir 54 | let mut some_file = PathBuf::from(dir_path); 55 | some_file.push("file.txt"); 56 | std::fs::write(some_file, "This is a file")?; 57 | 58 | // Put a dir in the dir 59 | let mut some_dir = PathBuf::from(dir_path); 60 | some_dir.push("some_dir"); 61 | std::fs::create_dir(some_dir)?; 62 | 63 | let actual = bugreport!() 64 | .info(DirectoryEntries::new("File and dir", dir_path)) 65 | .format::(); 66 | 67 | #[allow(unused_mut)] 68 | let mut expected = String::from( 69 | "#### File and dir 70 | 71 | - file.txt, 14 bytes 72 | - some_dir/ 73 | 74 | ", 75 | ); 76 | 77 | #[cfg(windows)] 78 | { 79 | expected = expected.replace("some_dir/", "some_dir\\"); 80 | } 81 | 82 | assert_eq!(expected, actual); 83 | 84 | Ok(()) 85 | } 86 | 87 | #[test] 88 | fn new() { 89 | DirectoryEntries::new("a", "/a"); 90 | // Not possible yet: DirectoryEntries::new(String::from("b"), PathBuf::from("/b")); 91 | DirectoryEntries::new(&String::from("c"), &PathBuf::from("/c")); 92 | new_with_title_from_local_variable(); 93 | } 94 | 95 | fn new_with_title_from_local_variable() -> DirectoryEntries { 96 | let local_variable = String::from("pretend this is dynamically constructed"); 97 | DirectoryEntries::new(&local_variable, "/path") 98 | } 99 | --------------------------------------------------------------------------------