console-rs / indicatif

A command line progress reporting library for Rust
MIT License
4.22k stars 238 forks source link

Machine-readable (JSON) output #525

Open akx opened 1 year ago

akx commented 1 year ago

I know this is a bit leftfield, maybe, but I have a project where I'd like to use Indicatif's TTY progress bars when human eyes are operating the application, but with an option to use JSON (NDJSON/jsonlines) output instead when working as a subprocess, and I'd like to do this without duplicating the ETA, etc. calculations and rate limiting since Indicatif is already doing a great job at that.

What would be a good approach for this?

Since ProgressStyle isn't a trait, it's not easy to pass in a JSON-formatting ProgressStyle from userland (or at least I couldn't figure it out); just passing in a JSON-esque template for a regular ProgressStyle isn't great since it doesn't do JSON encoding for strings – and even so, the TTY-related code (moving cursors and clearing progress bars and all that) wouldn't be necessary; you'd just always print a newline after a message.

To clarify, I'm envisioning something like ProgressBar::new_json(["pos", "len", "eta"]) outputting e.g.

{"pos": 1, "len": 100, "eta": 14.3}
{"pos": 39, "len": 100, "eta": 7.7}
{"pos": 100, "len": 100, "eta": 0}

(with maybe a complete marker afterwards? That's a detail anyway.)

If there's no great way to do this from userspace, would a PR implementing something like this be appreciated and/or approved? 😄