Git Product home page Git Product logo

narrate's Introduction

narrate

Crates.io msrv 1.61.1 tests Documentation license

This library provides CLI application error and status reporting utilities. The coloured output formatting aims to be similar to Cargo. Error type is a wrapper around anyhow, with optional help messages.

Features

  • User facing status messages and error reporting
  • Wrap any error with additional context
  • Optional help messages for errors
  • Set of standard CLI errors with exit codes conforming to sysexits.h
  • Convenience Result type
  • Replace/integrate with anyhow

How to use

  • Use narrate::Result<T> as a return type of any fallible function.

    Within the function, use ? to propagate any error that implements the std::error::Error trait. Same as anyhow::Result<T>.

    use narrate::Result;
    
    fn get_user() -> Result<User> {
        let json = std::fs::read_to_string("user.json")?;
        let user: User = serde_json::from_str(&json)?;
        Ok(user)
    }
  • Wrap an error with more context by importing the narrate::ErrorWrap trait. Similar to anyhow::Context, this can give your users more information as to why an error happened.

    use narrate::{CliError, ErrorWrap, Result};
    
    fn run() -> Result<()> {
        ...
        // wrap with contextual information
        data.acquire().wrap("unable to acquire data")?;
    
        // wrap with another error
        config.load().wrap(CliError::Config)?;
    
        // wrap with lazily evaulated string or error
        config.load().wrap_with(|| format!("cannot load {}", path))?;
    
        // wrap with help information
        create_dir()
          .wrap("project directory already exists")
          .add_help("Try using cargo init")?;
        ...
    }
    error: project directory already exists
    cause: Is a directory (os error 20)
    
    Try using cargo init
  • Use the narrate::ExitCode trait to get the sysexits.h conforming exit code from a narrate::Error. By default this is just 70 (software error), but using an apropriate CliError will change this.

  • narrate::CliError collection of typical command line errors. Use them to add context to deeper application errors. Use their exit_code to conform to sysexits.h.

    use narrate::{CliError, ErrorWrap, ExitCode, Result};
    
    fn main() {
        let res = run();
    
        if let Err(ref err) = res {
            std::process::exit(err.exit_code());
        }
    }
    
    fn run() -> Result<()> {
        will_error().wrap(CliError::OsErr)?
        Ok(())
    }
  • Report errors to the command line with either report::err or report::err_full for the complete error chain.

    use narrate::{CliError, Error, report};
    
    fn main() {
        let res = run();
    
        if let Err(ref err) = res {
            report::err_full(&err);
            std::process::exit(err.exit_code());
        }
    }
    
    fn run() -> Result<()> {
        ...
        let config: Config = serde_json::from_str(&json)
            .wrap("bad config file `/app/config.toml`")
            .wrap(CliError::Config)
            .add_help("see https://docs.example.rs/config for more help")?;
        ...
    }

    report::err_full output

  • Report application status to the command line with report::status. Modeled on the output from Cargo.

    use colored::Color;
    use narrate::report;
    
    fn main() {
        report::status("Created", "new project `spacetime`", Color::Green);
    }

    report::status output

Please view the API Docs and examples for more information.

FAQ

Should I use narrate instead of anyhow or eyre?

Anyhow is a great tool for handling errors in your CLI app, but it doesn't come with its own reporting, common set of errors, or the ability to add separate help messages.

Eyre and its companion crates offer fine-grained error reporting and is far more customizable than narrate - which is opinionated in copying Cargo's style. If you don't need that much control, narrate provides a simpler alternative. Plus the added benefit of reporting statuses, not just errors.

Can I just pretty print my anyhow errors?

If you just use the report Cargo feature flag, you can access the report module and thus the anyhow_err and anyhow_err_full functions.

# Cargo.toml
[dependencies]
narrate = { version = "0.4.0", default-features = false, features = ["report"] }
// main.rs
use narrate::report;

fn main() {
    if let Err(err) => run() {
        report::anyhow_err_full(err);    
    }
}

fn run() -> anyhow::Result<()> {
  ...
}

Contributing

Thank you very much for considering to contribute to this project!

We welcome any form of contribution:

  • New issues (feature requests, bug reports, questions, ideas, ...)
  • Pull requests (documentation improvements, code improvements, new features, ...)

Note: Before you take the time to open a pull request, please open an issue first.

See CONTRIBUTING.md for details.

License

narrate is distributed under the terms of both the MIT license and the Apache License (Version 2.0).

See LICENSE-APACHE and LICENSE-MIT for details.

narrate's People

Contributors

sonro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

narrate's Issues

Report status macros

Format report messages to standard colors.

  • success!: green
  • info!: blue
  • warning!: orange

4 varients:

varient output note
success!("hello") "success: hello"
info!("{}", msg) "info: msg string"
warning!("title", "hello") "title: hello" 'title' would be orange
success!("title", "{}", msg") "title: msg string" 'title' would be green

Compile error when using `narrate::{bail, error_from}` without specifying `anyhow` as dependency

Bug Report

Using narrate::{bail, error_from} in a project that doesn't specify anyhow as a dependency separately (regardless of if the anyhow feature of narrate is used) unconditionally triggers a compile error. (AFAIK this is a bug, as documentation doesn't specify that anyhow must also be a dependency.)

Example

Cargo.toml

[package]
name = "example"
version = "0.1.0"
edition = "2021"

[dependencies]
narrate = { version = "0.4.1", features = ["anyhow"] }
# The above line could also have simply been:
# narrate = "0.4.1"

src/main.rs

fn main() -> narrate::Result<()> {
    narrate::bail!("this should compile");
}

cargo build

See the triggered compiler error:

error[E0433]: failed to resolve: use of undeclared crate or module `anyhow`
 --> src/main.rs:2:5
  |
2 |     narrate::bail!("this should compile");
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ use of undeclared crate or module `anyhow`
  |
  = note: this error originates in the macro `$crate::error_from` which comes from the expansion of the macro `narrate::bail` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0433`.
error: could not compile `main` (bin "main") due to previous error

Cause

It seems that this issue stems from narrate not unconditionally requiring anyhow as a non-optional dependency. My best guess is that this was introduced in bdba927. This seems related to #4.

Remedy

In the meantime while awaiting a fix, adding anyhow as a dependency in Cargo.toml prevents the compile error.

Notes

Otherwise, narrate is a great library that does exactly what I was looking for!

Move anyhow integration behind a feature flag

BREAKING CHANGE

Hide Error::downcast and Error::from_anyhow behind an "anyhow" feature flag. These are currently the only public APIs using anyhow types. Moreover only publicly re-export anyhow crate behind the feature flag.

This allows the default API to keep the implementation separate from the user and the "anyhow" feature-set to allow conversion between the two types.

Tune up readme

Rewrite readme to be more in line with how this particular library should be used. At the moment it is missing several parts of the API

Feature flags

  • report
  • error
  • cli-error
  • default: report, error, cli-error

Relevant examples

  • Integration with anyhow
  • Reporting statuses
  • Reporting errors
  • Standalone error library
  • ExitCode implementation
  • CliError usage

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.