exitfailure-0.5.1/.clog.toml010064400007650000024000000002331330175525300141560ustar0000000000000000[clog] repository = "https://github.com/tismith/exitfailure" changelog = "CHANGELOG.md" from-latest-tag = true [sections] Documentation = ["doc", "docs"] exitfailure-0.5.1/.gitignore010064400007650000024000000000371327572157000142560ustar0000000000000000 /target **/*.rs.bk Cargo.lock exitfailure-0.5.1/.travis.yml010064400007650000024000000024551332574120100143720ustar0000000000000000language: rust cache: cargo env: # required for allow_failures os: - linux - osx rust: - stable - beta - nightly - 1.26.0 #oldest supported release matrix: fast_finish: true allow_failures: #- env: NAME='cargo-travis' #- rust: nightly include: - rust: nightly env: NAME='cargo-clippy' before_script: - rustup component add rustfmt-preview - rustup component add clippy-preview script: - cargo fmt --all -- --check - cargo clippy - env: NAME='cargo-travis' sudo: required # travis-ci/travis-ci#9061 before_script: - cargo install cargo-update || echo "cargo-update already installed" - cargo install cargo-travis || echo "cargo-travis already installed" - cargo install-update -a script: - | export RUST_BACKTRACE=1 && cargo build --verbose && cargo coverage --verbose && bash <(curl -s https://codecov.io/bash) -s target/kcov addons: # required for kcov apt: packages: - libcurl4-openssl-dev - libelf-dev - libdw-dev - binutils-dev - cmake script: | export RUST_BACKTRACE=1 && cargo build --verbose && cargo test --verbose && cargo doc --no-deps --verbose exitfailure-0.5.1/appveyor.yml010064400007650000024000000102041332575511000146440ustar0000000000000000# Appveyor configuration template for Rust using rustup for Rust installation # https://github.com/starkat99/appveyor-rust ## Operating System (VM environment) ## # Rust needs at least Visual Studio 2013 Appveyor OS for MSVC targets. os: Visual Studio 2015 ## Build Matrix ## # This configuration will setup a build for each channel & target combination (12 windows # combinations in all). # # There are 3 channels: stable, beta, and nightly. # # Alternatively, the full version may be specified for the channel to build using that specific # version (e.g. channel: 1.5.0) # # The values for target are the set of windows Rust build targets. Each value is of the form # # ARCH-pc-windows-TOOLCHAIN # # Where ARCH is the target architecture, either x86_64 or i686, and TOOLCHAIN is the linker # toolchain to use, either msvc or gnu. See https://www.rust-lang.org/downloads.html#win-foot for # a description of the toolchain differences. # See https://github.com/rust-lang-nursery/rustup.rs/#toolchain-specification for description of # toolchains and host triples. # # Comment out channel/target combos you do not wish to build in CI. # # You may use the `cargoflags` and `RUSTFLAGS` variables to set additional flags for cargo commands # and rustc, respectively. For instance, you can uncomment the cargoflags lines in the nightly # channels to enable unstable features when building for nightly. Or you could add additional # matrix entries to test different combinations of features. environment: matrix: ### MSVC Toolchains ### # Stable 64-bit MSVC - channel: stable target: x86_64-pc-windows-msvc # Stable 32-bit MSVC - channel: stable target: i686-pc-windows-msvc # Beta 64-bit MSVC - channel: beta target: x86_64-pc-windows-msvc # Beta 32-bit MSVC - channel: beta target: i686-pc-windows-msvc # Nightly 64-bit MSVC - channel: nightly target: x86_64-pc-windows-msvc #cargoflags: --features "unstable" # Nightly 32-bit MSVC - channel: nightly target: i686-pc-windows-msvc #cargoflags: --features "unstable" ### GNU Toolchains ### # Stable 64-bit GNU - channel: stable target: x86_64-pc-windows-gnu # Stable 32-bit GNU - channel: stable target: i686-pc-windows-gnu # Beta 64-bit GNU - channel: beta target: x86_64-pc-windows-gnu # Beta 32-bit GNU - channel: beta target: i686-pc-windows-gnu # Nightly 64-bit GNU - channel: nightly target: x86_64-pc-windows-gnu #cargoflags: --features "unstable" # Nightly 32-bit GNU - channel: nightly target: i686-pc-windows-gnu #cargoflags: --features "unstable" ### Allowed failures ### # See Appveyor documentation for specific details. In short, place any channel or targets you wish # to allow build failures on (usually nightly at least is a wise choice). This will prevent a build # or test failure in the matching channels/targets from failing the entire build. #matrix: # allow_failures: # - channel: nightly # If you only care about stable channel build failures, uncomment the following line: #- channel: beta ## Install Script ## # This is the most important part of the Appveyor configuration. This installs the version of Rust # specified by the 'channel' and 'target' environment variables from the build matrix. This uses # rustup to install Rust. # # For simple configurations, instead of using the build matrix, you can simply set the # default-toolchain and default-host manually here. install: - appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe - rustup-init -yv --default-toolchain %channel% --default-host %target% - set PATH=%PATH%;%USERPROFILE%\.cargo\bin - rustc -vV - cargo -vV ## Build Script ## # 'cargo test' takes care of building for us, so disable Appveyor's build stage. This prevents # the "directory does not contain a project or solution file" error. build: false # Uses 'cargo test' to run tests and build. Alternatively, the project may call compiled programs #directly or perform other testing commands. Rust will automatically be placed in the PATH # environment variable. test_script: - cargo test --verbose %cargoflags% exitfailure-0.5.1/Cargo.toml.orig010064400007650000024000000013231333101534200151360ustar0000000000000000[package] name = "exitfailure" version = "0.5.1" authors = ["Toby Smith "] license = "MIT OR Apache-2.0" readme = "README.md" repository = "https://github.com/tismith/exitfailure" description = "A basic newtype wrappers for use with ? in main" categories = ["command-line-interface"] keywords = ["newtype", "failure", "error", "command-line", "cli"] [dependencies] failure = "0.1.2" [dev-dependencies] assert_cmd = "0.9.0" predicates = "0.9.0" [badges] travis-ci = { repository = "tismith/exitfailure", branch = "master" } appveyor = { repository = "tismith/exitfailure", branch = "master", service = "github" } codecov = { repository = "tismith/exitfailure", branch = "master", service = "github" } exitfailure-0.5.1/Cargo.toml0000644000000024050000000000000114160ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "exitfailure" version = "0.5.1" authors = ["Toby Smith "] description = "A basic newtype wrappers for use with ? in main" readme = "README.md" keywords = ["newtype", "failure", "error", "command-line", "cli"] categories = ["command-line-interface"] license = "MIT OR Apache-2.0" repository = "https://github.com/tismith/exitfailure" [dependencies.failure] version = "0.1.2" [dev-dependencies.assert_cmd] version = "0.9.0" [dev-dependencies.predicates] version = "0.9.0" [badges.appveyor] branch = "master" repository = "tismith/exitfailure" service = "github" [badges.codecov] branch = "master" repository = "tismith/exitfailure" service = "github" [badges.travis-ci] branch = "master" repository = "tismith/exitfailure" exitfailure-0.5.1/CHANGELOG.md010064400007650000024000000040751333101534200140670ustar0000000000000000 ## 0.5.1 (2018-08-03) #### Bug Fixes * Make backtrace work with nonzero values of RUST_BACKTRACE ([1f551d92](https://github.com/tismith/exitfailure/commit/1f551d92313da81316cf989f3750e831a1d66cc7)) #### Features * Make use of new failure 0.1.2 iterators ([78c02a8a](https://github.com/tismith/exitfailure/commit/78c02a8af17d209033d87bc1a01064e13e1907fe)) ## 0.5.0 (2018-07-27) #### Documentation * Update documentation for ExitDisplay ([06872181](https://github.com/tismith/exitfailure/commit/06872181c458cc1091329de43b2f80cae4582128)) #### Features * Add ExitDisplay for using Display, not Debug in error messages ([2ac1ea2e](https://github.com/tismith/exitfailure/commit/2ac1ea2e1059cbf82e931020853279eb968a6877)) ## 0.4.1 (2018-06-18) #### Bug Fixes * Insert a \n between cause and backtrace ([81e345f8](https://github.com/tismith/exitfailure/commit/81e345f8f0e6ef163ff2a164c6c72fc33116393e)) ## 0.4.0 (2018-06-14) #### Documentation * update README for backtrace support ([f7e06e39](https://github.com/tismith/exitfailure/commit/f7e06e39742443e0127456c4b8f161f5e5e5e2f3)) * update docs for backtrace support ([8e47e84a](https://github.com/tismith/exitfailure/commit/8e47e84a8e0d9db0f67ae50e7650ac436f14913e)) #### Features * add bracktrace output (w. RUST_BACKTRACE=1) ([b3111c31](https://github.com/tismith/exitfailure/commit/b3111c31a238baf2f85f4ff8a4ab9a47e5d3e975)) ## 0.3.0 (2018-05-30) #### Features * transition to dual apache/mit license ([5ec7f772](https://github.com/tismith/exitfailure/commit/5ec7f77215c7cd2ee8866fd908d596df7c9ea1d5)) ## 0.2.3 (2018-05-25) #### Documentation * Fix links and typos ([d6ff44dd](https://github.com/tismith/exitfailure/commit/d6ff44dd10fac5acc28d2504c4345d8dce9c3593)) ## 0.2.2 (2018-05-24) #### Features * add a From instance for failure::Context ([7fea9e2d](https://github.com/tismith/exitfailure/commit/7fea9e2d063065c570f4a84c4395838790e8b0ae)) exitfailure-0.5.1/CONTRIBUTING.md010064400007650000024000000021761331116217200145110ustar0000000000000000### Commit Messages I use a [conventional](https://github.com/ajoslin/conventional-changelog/blob/a5505865ff3dd710cf757f50530e73ef0ca641da/conventions/angular.md) changelog format so I can update my changelog automatically using [clog](https://github.com/clog-tool/clog-cli) * Please format your commit subject line using the following format: `TYPE(COMPONENT): MESSAGE` where `TYPE` is one of the following: - `feat` - A new feature of an existing API - `perf` - A performance improvement - `fix` - A bug fix - `docs` - Changes to documentation only - `test` - Changes to the testing framework or tests only - `refactor` - Code functionality doesn't change, but underlying structure may - `style` - Stylistic changes only, no functionality changes - `wip` - A work in progress commit (Should typically be `git rebase`'ed away) - `build` - Changes to the build system - `chore` - Catch all or things that have to do with the build system, etc * The `COMPONENT` is optional, and may be a single file, directory, or logical component. Parenthesis can be omitted if you are opting not to use the `COMPONENT`. exitfailure-0.5.1/examples/context.rs010064400007650000024000000011561332652176100161360ustar0000000000000000// Copyright (c) 2018 Toby Smith // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate exitfailure; extern crate failure; use exitfailure::ExitFailure; use failure::ResultExt; fn main() -> Result<(), ExitFailure> { let error = Err(failure::err_msg("root cause failure")); Ok(error.context("this is some context".to_string())?) } exitfailure-0.5.1/examples/display.rs010064400007650000024000000003211333016723500161050ustar0000000000000000extern crate exitfailure; use exitfailure::ExitDisplay; fn main() -> Result<(), ExitDisplay> { Ok(some_fn()?) } fn some_fn() -> Result<(), String> { Err("this is an error message".into()) } exitfailure-0.5.1/examples/example.rs010064400007650000024000000012611332652176100161020ustar0000000000000000// Copyright (c) 2018 Toby Smith // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate exitfailure; extern crate failure; use exitfailure::ExitFailure; use failure::ResultExt; fn main() -> Result<(), ExitFailure> { Ok(some_fn()?) } fn some_fn() -> Result<(), failure::Error> { let error = Err(failure::err_msg("root cause failure")); Ok(error.context("this is some context".to_string())?) } exitfailure-0.5.1/LICENSE-APACHE010064400007650000024000000261371330340020100141740ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. exitfailure-0.5.1/LICENSE-MIT010064400007650000024000000020531327647752700137350ustar0000000000000000MIT License Copyright (c) 2018 Toby Smith Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. exitfailure-0.5.1/README.md010064400007650000024000000046241332652176100135500ustar0000000000000000# exitfailure - convenient newtype wrappers for using ? in main() [![Build Status](https://travis-ci.org/tismith/exitfailure.svg?branch=master)](https://travis-ci.org/tismith/exitfailure) [![Build status](https://ci.appveyor.com/api/projects/status/2xhxwps2swlj3git/branch/master?svg=true)](https://ci.appveyor.com/project/tismith/exitfailure/branch/master) [![codecov](https://codecov.io/gh/tismith/exitfailure/branch/master/graph/badge.svg)](https://codecov.io/gh/tismith/exitfailure) [![](http://meritbadge.herokuapp.com/exitfailure)](https://crates.io/crates/exitfailure) `exitfailure` provides some newtype wrappers to help with using ? in `main()`. It is intended to be used with rust 1.26 and above's "? in main()" feature (see the [tracking issue here](https://github.com/rust-lang/rust/issues/43301)). The primary items exported by this library are: - `ExitFailure`: a wrapper around `failure::Error` to allow ? printing from main to present a nicer error message, including any available context and backtrace. - `ExitDisplay`: a wrapper around `E: std::fmt::Display` to allow the error message from main to use `Display` and not `Debug`. For more information, including more details on the types, please see the [API Documentation](https://docs.rs/exitfailure/). Example: ```rust #[macro use] extern crate failure; extern crate exitfailure; use failure::ResultExt; use exitfailure::ExitFailure; fn main() -> Result<(), ExitFailure> { Ok(some_fn()?) } fn some_fn() -> Result<(), failure::Error> { let error = Err(failure::err_msg("root cause failure")); Ok(error.context("this is some context".to_string())?) } ``` This will print, when executed: ```ignore Error: this is some context Info: caused by root cause failure ``` If the environment variable RUST_BACKTRACE=1 is set, then the printing will include whatever backtrace information is provided by the `failure::Error` that is being wrapped. ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. exitfailure-0.5.1/src/lib.rs010064400007650000024000000075271333101502600141650ustar0000000000000000// Copyright (c) 2018 Toby Smith // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny( missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unreachable_pub, unsafe_code, unstable_features, unused_extern_crates, unused_import_braces, unused_qualifications, variant_size_differences )] //! Some newtype wrappers to help with using ? in main() //! //! The primary items exported by this library are: //! //! - `ExitFailure`: a wrapper around `failure::Error` to allow ? printing from main //! to present a nicer error message, including any available context and backtrace. //! //! - `ExitDisplay`: a wrapper around `E: std::fmt::Display` to allow the error message //! from main to use `Display` and not `Debug` //! //! Basically, these types should only ever be used in the return type for //! `main()` //! extern crate failure; /// The newtype wrapper around `failure::Error` /// /// ```rust,should_panic /// # extern crate failure; /// # extern crate exitfailure; /// # use failure::ResultExt; /// # use exitfailure::ExitFailure; /// fn main() -> Result<(), ExitFailure> { /// Ok(some_fn()?) /// } /// /// fn some_fn() -> Result<(), failure::Error> { /// let error = Err(failure::err_msg("root cause failure")); /// Ok(error.context("this is some context".to_string())?) /// } /// ``` pub struct ExitFailure(failure::Error); /// Prints a list of causes for this Error, along with any backtrace /// information collected by the Error (if RUST_BACKTRACE=1). impl std::fmt::Debug for ExitFailure { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let fail = self.0.as_fail(); write!(f, "{}", fail)?; for cause in fail.iter_causes() { write!(f, "\nInfo: caused by {}", cause)?; } if let Ok(x) = std::env::var("RUST_BACKTRACE") { if x != "0" { write!(f, "\n{}", self.0.backtrace())? } } Ok(()) } } impl> From for ExitFailure { fn from(t: T) -> Self { ExitFailure(t.into()) } } /// A newtype wrapper around `E: std::fmt::Display` /// /// ```rust,should_panic /// # extern crate exitfailure; /// # use exitfailure::ExitDisplay; /// fn main() -> Result<(), ExitDisplay> { /// Ok(some_fn()?) /// } /// /// fn some_fn() -> Result<(), String> { /// Err("some error".into()) /// } /// ``` pub struct ExitDisplay(E); /// Prints the underlying error type, using `Display` and not `Debug`. impl std::fmt::Debug for ExitDisplay { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } impl From for ExitDisplay { fn from(e: E) -> Self { ExitDisplay(e) } } #[cfg(test)] mod test { use super::*; use std::fmt::Write; #[test] fn test_exitfailure() { let mut buffer = String::new(); let error = failure::err_msg("some failure").context("some context"); let exitfailure: ExitFailure = error.into(); write!(buffer, "{:?}", exitfailure).unwrap(); assert!(buffer.contains("some failure")); assert!(buffer.contains("some context")); } #[test] fn test_exitdisplay() { let mut buffer = String::new(); let error = "some error".to_string(); let exitdisplay: ExitDisplay = error.into(); write!(buffer, "{:?}", exitdisplay).unwrap(); assert_eq!(buffer, "some error"); } } exitfailure-0.5.1/tests/test.rs010064400007650000024000000035751333101502600147500ustar0000000000000000// Copyright (c) 2018 Toby Smith // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate assert_cmd; extern crate predicates; use assert_cmd::prelude::*; use predicates::prelude::*; fn get_cwd() -> String { std::env::current_dir() .unwrap() .to_str() .unwrap() .to_string() } macro_rules! test_body { ($name:expr, $matcher:expr) => { let bin = format!("{}/target/debug/examples/{}", get_cwd(), $name); let pred = predicates::str::contains($matcher).from_utf8(); std::process::Command::new(&bin) .assert() .failure() .stderr(pred); }; ($name:expr) => { test_body!( $name, "Error: this is some context\nInfo: caused by root cause failure" ) }; } #[test] fn test_example() { test_body!("example"); } #[test] fn test_context() { test_body!("context"); } #[test] fn test_display() { test_body!("display", "Error: this is an error message"); } #[test] fn test_no_backtrace() { let bin = format!("{}/target/debug/examples/example", get_cwd()); let pred = predicates::str::contains("stack backtrace").from_utf8(); std::process::Command::new(&bin) .env_remove("RUST_BACKTRACE") .assert() .failure() .stderr(pred.not()); } #[test] fn test_backtrace() { let bin = format!("{}/target/debug/examples/example", get_cwd()); let pred = predicates::str::contains("stack backtrace").from_utf8(); std::process::Command::new(&bin) .env("RUST_BACKTRACE", "1") .assert() .failure() .stderr(pred); }