Skip to content

Commit

Permalink
New sq command to quote input
Browse files Browse the repository at this point in the history
  • Loading branch information
allenap committed Jul 17, 2024
1 parent 60a88b7 commit 2d8b933
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
[workspace]
members = ["cli", "."]

[package]
authors = ["Gavin Panella <gavin@allenap.me>"]
categories = ["encoding", "filesystem"]
Expand Down
15 changes: 15 additions & 0 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "shell-quote-cli"
version = "0.1.0"
edition = "2021"

[[bin]]
path = "src/main.rs"
name = "sq"

[dependencies]
shell-quote = { path = ".." }

[dependencies.clap]
version = "=4.5.9"
features = ["derive", "env", "wrap_help"]
36 changes: 36 additions & 0 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use std::io::{self, IsTerminal, Read, Write};

use shell_quote::{Bash, Fish, Sh};

mod options;

fn main() -> Result<(), Box<dyn std::error::Error>> {
let options = <options::Options as clap::Parser>::parse();
let quoted: Vec<u8> = if options.command.is_empty() && !io::stdin().is_terminal() {
let mut buf = Vec::new();
io::stdin().read_to_end(&mut buf)?;
match options.shell {
options::Shell::Bash => Bash::quote_vec(&buf),
options::Shell::Fish => Fish::quote_vec(&buf),
options::Shell::Sh => Sh::quote_vec(&buf),
}
} else {
options
.command
.iter()
.fold(Vec::<u8>::new(), |mut acc, arg| {
if !acc.is_empty() {
acc.push(b' ');
}
match options.shell {
options::Shell::Bash => Bash::quote_into_vec(arg, &mut acc),
options::Shell::Fish => Fish::quote_into_vec(arg, &mut acc),
options::Shell::Sh => Sh::quote_into_vec(arg, &mut acc),
};
acc
})
};
io::stdout().write_all(&quoted)?;

Ok(())
}
35 changes: 35 additions & 0 deletions cli/src/options.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use std::ffi::OsString;

use clap::{command, Parser, ValueEnum, ValueHint};

#[derive(Parser, Debug)]
#[command(
author, version, about, long_about = None, max_term_width = 80,
)]
pub struct Options {
#[arg(
short = 's',
long = "shell",
help = "The shell for which to quote arguments.",
value_hint = ValueHint::ExecutablePath,
value_enum,
env = "SHELL",
)]
pub shell: Shell,

#[arg(
help = "The arguments to quote. When none are provided, reads from stdin.",
trailing_var_arg = true,
allow_hyphen_values = true
)]
pub command: Vec<OsString>,
}

#[derive(Debug, Clone, ValueEnum)]
pub enum Shell {
#[value(alias = "zsh")]
Bash,
Fish,
#[value(alias = "dash")]
Sh,
}

0 comments on commit 2d8b933

Please sign in to comment.