Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
eastack committed Jun 24, 2024
0 parents commit af09cf2
Show file tree
Hide file tree
Showing 5 changed files with 335 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/target
254 changes: 254 additions & 0 deletions Cargo.lock

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

11 changes: 11 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "percent"
description = "A CLI tool for Percent Encoding and Decoding"
version = "0.1.0"
edition = "2021"


[dependencies]
clap = { version = "4.5.7", features = ["derive"] }
clap_complete = "4.5.6"
urlencoding = "2.1.3"
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Percent

A CLI tool for Percent Encoding and Decoding
66 changes: 66 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
use std::io::{self, BufRead};

use clap::{command, Command, CommandFactory, Parser, Subcommand};
use clap_complete::{generate, Generator, Shell};
use urlencoding::{decode, encode};

#[derive(Parser)]
#[command(version, about)]
struct Cli {
#[command(subcommand)]
command: Commands,
}

#[derive(Subcommand)]
enum Commands {
/// Percent Encode
Encode {
/// Raw content to be percent encoded. If not provided, reads from stdin.
decoded: Option<String>,
},
/// Percent Decode
Decode {
/// Encoded content to be percent decoded. If not provided, reads from stdin.
encoded: Option<String>,
},
/// Generate shell completion.
Completion { shell: Shell },
}

fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
}

fn read_from_stdin() -> String {
let mut handle = io::stdin().lock();
let mut buffer = String::new();
handle
.read_line(&mut buffer)
.expect("Failed to read line from stdin");
// remove tailing newline
buffer.pop();
buffer
}

fn main() {
let cli = Cli::parse();

match cli.command {
Commands::Encode { decoded } => {
let decoded = decoded.unwrap_or_else(read_from_stdin);
let encoded = encode(&decoded);
print!("{encoded}");
}
Commands::Decode { encoded } => {
let encoded = encoded.unwrap_or_else(read_from_stdin);
match decode(&encoded) {
Ok(decoded) => print!("{decoded}"),
Err(e) => eprintln!("Failed to decode input: {e}"),
}
}
Commands::Completion { shell } => {
let mut cmd = Cli::command();
print_completions(shell, &mut cmd);
}
}
}

0 comments on commit af09cf2

Please sign in to comment.