Skip to content

Commit

Permalink
Merge pull request #2 from marcoradocchia/1-read-from-stdin
Browse files Browse the repository at this point in the history
Added feature closing #1
  • Loading branch information
marcoradocchia authored Jul 18, 2022
2 parents 3d96864 + cfcf355 commit d70ccac
Show file tree
Hide file tree
Showing 7 changed files with 85 additions and 24 deletions.
11 changes: 9 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
# Changelog

## [unreleased]
## [0.2.0] - 2022-07-18

### Added

- Feature to read string to encode from standard input, which allows to pipe
commands to `qr-rs` (closing issue #1).
- `border` CLI option to specify border size.
- `error-correction-level` CLI option to specify QR *error-correction-level*.
- `error-correction-level` CLI option to specify QR *error-correction-level* as
one of the following values:
- **low**;
- **medium**;
- **quartile**;
- **high**.

## [0.1.0] - 2022-07-15

Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
[package]
name = "qr-rs"
version = "0.1.0"
version = "0.2.0"
authors = ["Marco Radocchia <[email protected]"]
edition = "2021"
rust-version = "1.62.0"
description = "Encode URLs or text into QR codes."
description = "A CLI utility to encode URLs or text into QR codes in various formats and colors."
readme = "README.md"
repository = "https://github.com/marcoradocchia/qr-rs"
license = "GPL-3.0-only"
Expand Down
39 changes: 29 additions & 10 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,25 +73,44 @@ paru -S qr-rs-bin
[^1]: Currently only `x86_64`

## Usage

```
qr-rs 0.1.0
qr-rs 0.2.0
Marco Radocchia <[email protected]>
Encode URLs or text into QR codes.
A CLI utility to encode URLs or text into QR codes in various formats and colors.
USAGE:
qr [OPTIONS] <STRING>
qr [OPTIONS] [STRING]
ARGS:
<STRING> String to encode
OPTIONS:
-b, --bg <BG> Foreground color (hex code) [default: #FFF]
-f, --fg <FG> Background color (hex code) [default: #000]
-h, --help Print help information
-o, --output <OUTPUT> Output file (supported file extensions: jpeg, jpg, png, svg); omit to
print QR code to console
-s, --scale <SCALE> Scale factor (raster image output only) [default: 25]
-V, --version Print version information
-b, --bg <BG>
Foreground color (hex code) [default: #FFF]
-B, --border <BORDER>
Border size (expressed in unit blocks) [default: 1]
--error-correction-level <ERROR_CORRECTION_LEVEL>
QR error orrection level [default: medium] [possible values: low, medium, quartile,
high]
-f, --fg <FG>
Background color (hex code) [default: #000]
-h, --help
Print help information
-o, --output <OUTPUT>
Output file (supported file extensions: jpeg, jpg, png, svg); omit to print QR code to
console
-s, --scale <SCALE>
Scale factor (raster image output only) [default: 25]
-V, --version
Print version information
```

## Changelog
Expand Down
4 changes: 2 additions & 2 deletions src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub use clap::Parser;
use qrcodegen::QrCodeEcc;
use std::path::PathBuf;

/// Encode URLs or text into QR codes.
/// A CLI utility to encode URLs or text into QR codes in various formats and colors.
#[derive(Parser, Debug)]
#[clap(
author = "Marco Radocchia <[email protected]>",
Expand Down Expand Up @@ -72,5 +72,5 @@ pub struct Args {

/// String to encode.
#[clap(value_parser)]
pub string: String,
pub string: Option<String>,
}
43 changes: 37 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ use dialoguer::{theme::ColorfulTheme, Confirm};
use error::{Error, ErrorKind, Warning};
use image::{ImageBuffer, RgbImage};
use qrcodegen::QrCode;
use std::{fmt::Write as _, fs, io::Write, path::Path, process};
use std::{
fmt::Write as _,
fs,
io::{self, Read, Write},
path::Path,
process,
};
use utils::hex_to_rgb;

/// QR code.
Expand All @@ -42,7 +48,7 @@ impl Qr {
fn new(data: QrCode, border: u8) -> Self {
Self {
data,
border: border.into()
border: border.into(),
}
}
}
Expand Down Expand Up @@ -144,20 +150,45 @@ impl QrOutput for Qr {
Ok(())
}

/// Print QR code to standard output.
fn console(&self) {
for y in -self.border..self.data.size() + self.border {
for x in -self.border..self.data.size() + self.border {
print!("{0}{0}", if self.data.get_module(x, y) { '█' } else { ' ' });
print!(
"{0}{0}",
if self.data.get_module(x, y) {
'█'
} else {
' '
}
);
}
println!();
}
}
}

/// Runs the program & catches errors.
fn run(args: &Args) -> Result<(), ErrorKind> {
fn run(args: Args) -> Result<(), ErrorKind> {
// If string to encode is not passed in as CLI argument, check stdin for piped string.
let string = args.string.unwrap_or_else(|| {
if atty::is(atty::Stream::Stdin) {
clap::Command::new("qr [OPTIONS] [STRING]")
.error(
clap::ErrorKind::MissingRequiredArgument,
"Missing input string.\n\n\
\tEither provide it as a CLI argument or pipe it in from standard input.",
)
.exit();
} else {
let mut string = String::new();
io::stdin().lock().read_to_string(&mut string).unwrap();
string.trim_end().to_string()
}
});

// Generate QR code.
let qr = match QrCode::encode_text(&args.string, args.error_correction_level) {
let qr = match QrCode::encode_text(&string, args.error_correction_level) {
Ok(data) => Qr::new(data, args.border),
Err(err) => return Err(ErrorKind::Error(Error::QrCodeErr(err.to_string()))),
};
Expand Down Expand Up @@ -200,7 +231,7 @@ fn run(args: &Args) -> Result<(), ErrorKind> {

/// Main function: calls run function and prints errors.
fn main() {
if let Err(e) = run(&Args::parse()) {
if let Err(e) = run(Args::parse()) {
e.colorize().unwrap();
process::exit(1);
}
Expand Down
6 changes: 5 additions & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ pub fn parse_error_correction_level(ecl: &str) -> Result<QrCodeEcc, String> {
})
}

/// This conversion assumes the HEX string as valid color and returns corresponding RGB value.
/// Convert HEX color code to RGB values
///
/// # Note
///
/// This function assumes `hex` parameter being a valid HEX color code.
pub fn hex_to_rgb(hex: &str) -> [u8; 3] {
let mut hex = hex.strip_prefix('#').unwrap().to_string();
if hex.len() == 3 {
Expand Down

0 comments on commit d70ccac

Please sign in to comment.