An open API service indexing awesome lists of open source software.

https://github.com/alexjackson1/take_bytes

A lightweight Rust utility for classic Unix-style CLIs
https://github.com/alexjackson1/take_bytes

clap-rs rust unix

Last synced: 8 days ago
JSON representation

A lightweight Rust utility for classic Unix-style CLIs

Awesome Lists containing this project

README

          

# take_bytes

A lightweight Rust utility for reading input from stdin or a file path, designed for seamless integration with [clap](https://github.com/clap-rs/clap)'s derive API.

## Features

- **Simple API**: Just parse `"-"` for stdin or any path for file input
- **Clap Integration**: Implements `FromStr` for direct use as a clap argument type
- **Zero Configuration**: Works out of the box with sensible defaults
- **Lightweight**: Minimal dependencies

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
take_bytes = "0.1"
```

The `clap` feature is enabled by default. To use without clap:

```toml
[dependencies]
take_bytes = { version = "0.1", default-features = false }
```

## Usage

### With Clap

```rust
use clap::Parser;
use take_bytes::TakeBytes;

#[derive(Parser)]
struct Cli {
/// Input file or "-" for stdin
#[arg(default_value = "-")]
input: TakeBytes,
}

fn main() -> Result<(), Box> {
let cli = Cli::parse();

// Read as bytes
let bytes = cli.input.try_into_bytes()?;
println!("Read {} bytes", bytes.len());

Ok(())
}
```

### Programmatic Use

```rust
use take_bytes::TakeBytes;
use std::path::PathBuf;

// Read from stdin
let stdin_input = TakeBytes::stdin();

// Read from a file
let file_input = TakeBytes::file(PathBuf::from("input.txt"));

// Parse from string (like clap does)
let input: TakeBytes = "-".parse()?;
```

### Helper Functions

```rust
use take_bytes::{TakeBytes, read_as_bytes, decode_utf8_string};

let input: TakeBytes = "file.txt".parse()?;

// Read as raw bytes
let bytes = read_as_bytes(input)?;

// Or decode as UTF-8 string
let input: TakeBytes = "file.txt".parse()?;
let text = decode_utf8_string(input)?;
```

## Examples

The classic Unix pattern of accepting input from either a file or stdin:

```bash
# Read from a file
myapp input.txt

# Read from stdin
cat input.txt | myapp -

# Read from stdin (default)
echo "hello" | myapp
```

## License

MIT License - see [LICENSE](LICENSE) for details.