This repository has been archived by the owner on Dec 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
Introduce a glorious new cli arg splitter #29
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
use std::fmt; | ||
use std::process::Output; | ||
|
||
use difference::Changeset; | ||
|
||
use errors::*; | ||
use diff; | ||
|
||
#[derive(Debug, Clone)] | ||
pub struct OutputAssertion<T> { | ||
pub expect: String, | ||
pub fuzzy: bool, | ||
pub kind: T, | ||
} | ||
|
||
impl<T: OutputType> OutputAssertion<T> { | ||
fn matches_fuzzy(&self, got: &str) -> Result<()> { | ||
if !got.contains(&self.expect) { | ||
bail!(ErrorKind::OutputMismatch( | ||
self.kind.to_string(), | ||
vec!["Foo".to_string()], | ||
self.expect.clone(), | ||
got.into(), | ||
)); | ||
} | ||
|
||
Ok(()) | ||
} | ||
|
||
fn matches_exact(&self, got: &str) -> Result<()> { | ||
let differences = Changeset::new(self.expect.trim(), got.trim(), "\n"); | ||
|
||
if differences.distance > 0 { | ||
let nice_diff = diff::render(&differences)?; | ||
bail!(ErrorKind::ExactOutputMismatch( | ||
self.kind.to_string(), | ||
vec!["Foo".to_string()], | ||
nice_diff | ||
)); | ||
} | ||
|
||
Ok(()) | ||
} | ||
|
||
pub fn execute(&self, output: &Output) -> Result<()> { | ||
let observed = String::from_utf8_lossy(self.kind.select(output)); | ||
|
||
if self.fuzzy { | ||
self.matches_fuzzy(&observed) | ||
} else { | ||
self.matches_exact(&observed) | ||
} | ||
} | ||
} | ||
|
||
|
||
pub trait OutputType: fmt::Display { | ||
fn select<'a>(&self, o: &'a Output) -> &'a [u8]; | ||
} | ||
|
||
|
||
#[derive(Debug, Clone, Copy)] | ||
pub struct StdOut; | ||
|
||
impl fmt::Display for StdOut { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
write!(f, "stdout") | ||
} | ||
} | ||
|
||
impl OutputType for StdOut { | ||
fn select<'a>(&self, o: &'a Output) -> &'a [u8] { | ||
&o.stdout | ||
} | ||
} | ||
|
||
|
||
#[derive(Debug, Clone, Copy)] | ||
pub struct StdErr; | ||
|
||
impl fmt::Display for StdErr { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
write!(f, "stderr") | ||
} | ||
} | ||
|
||
impl OutputType for StdErr { | ||
fn select<'a>(&self, o: &'a Output) -> &'a [u8] { | ||
&o.stderr | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
pub trait ToCmd<'a> { | ||
fn to_cmd(&'a self) -> Vec<String>; | ||
} | ||
|
||
impl<'a> ToCmd<'a> for str { | ||
fn to_cmd(&'a self) -> Vec<String> { | ||
let mut args = Vec::new(); | ||
let mut current_arg = String::new(); | ||
let mut in_quote = Vec::new(); | ||
|
||
for c in self.chars() { | ||
if in_quote.is_empty() && c.is_whitespace() { | ||
args.push(current_arg); | ||
current_arg = String::new(); | ||
continue; | ||
} | ||
|
||
current_arg.push(c); | ||
|
||
if c == '"' || c == '\'' { | ||
if in_quote.last() == Some(&c) { | ||
in_quote.pop(); | ||
} else { | ||
in_quote.push(c); | ||
} | ||
} | ||
} | ||
|
||
if !current_arg.is_empty() { | ||
args.push(current_arg); | ||
} | ||
|
||
args | ||
} | ||
} | ||
|
||
impl<'a, 'b, T> ToCmd<'a> for T where | ||
&'a T: AsRef<[&'b str]>, | ||
T: 'a, | ||
{ | ||
fn to_cmd(&'a self) -> Vec<String> { | ||
self.as_ref().into_iter().map(|x| x.to_string()).collect() | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod test { | ||
use super::ToCmd; | ||
|
||
#[test] | ||
fn slices() { | ||
assert_eq!( | ||
ToCmd::to_cmd(&["echo", "42"]), | ||
vec!["echo", "42"] | ||
); | ||
} | ||
|
||
#[test] | ||
fn simple() { | ||
assert_eq!( | ||
"echo 42".to_cmd(), | ||
vec!["echo", "42"] | ||
); | ||
assert_eq!( | ||
r#"echo "42""#.to_cmd(), | ||
vec!["echo", "\"42\""] | ||
); | ||
assert_eq!( | ||
r#"echo '42'"#.to_cmd(), | ||
vec!["echo", "\'42\'"] | ||
); | ||
assert_eq!( | ||
r#"echo '42 is the answer'"#.to_cmd(), | ||
vec!["echo", "\'42 is the answer\'"] | ||
); | ||
} | ||
|
||
#[test] | ||
fn real_world() { | ||
assert_eq!( | ||
r#"cargo run --bin whatever -- --input="Lorem ipsum" -f"#.to_cmd(), | ||
vec!["cargo", "run", "--bin", "whatever", "--", "--input=\"Lorem ipsum\"", "-f"] | ||
); | ||
} | ||
|
||
#[test] | ||
fn nested_quotes() { | ||
assert_eq!( | ||
r#"echo "lorem ipsum 'dolor' sit amet""#.to_cmd(), | ||
vec!["echo", "\"lorem ipsum 'dolor' sit amet\""] | ||
); | ||
|
||
assert_eq!( | ||
r#"echo "lorem ipsum ('dolor "doloris" septetur') sit amet""#.to_cmd(), | ||
vec!["echo", "\"lorem ipsum ('dolor \"doloris\" septetur') sit amet\""] | ||
); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ich glaube es gibt Randfälle, in denen sich das noch unerwartet verhalten könnte. Ich spiele mal Advocatus Diaboli:
Bei echo ist das unkritisch, bei anderen Befehlen könnte es schon problematisch sein, wenn Argument 3 plötzlich an Position 4 steht, etc. Vielleicht kann man sich hier auch irgendein fuzzy-testing überlegen? Das macht es natürlich alles sehr sehr kompliziert. Wichtig wäre aber, dass es sich vorhersehbar verhält.
M.E. wäre folgende Invariante sehr erstrebenswert:
"..."
ein gültiger Rust String ist (...
sind Platzhalter), dann solltestringify!("...").to_cmd()]
gleich["..."].to_cmd()
sein.Ich kenne die
stringify!
Methode nicht im Detail, vermute aber, dass auf einen String angewendet,JSON::from_str(stringify!("..."))
weitestgehend die Identität sein sollte. Auf dieser Annahme basiert ja die aktuelle Makro-Logik. Auch hier wäre vielleicht mal eine genauere Recherche oder Fuzzy Testing sinnvoll. :-)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great test case! I was so focused on getting other stuff that I think I actually went a bit overboard with this: We don't really have to deal with nested quotes at all – just recognize and ignore escaped quotes, right?
I've also just seen this crate, but I think it's more complex than we need here. I don't want to emulate shell syntax itself, just split some args :)
I think I can add quickcheck to test the invariant, but I'm not sure
JSON::from_str(stringify!("..."))
is that reliable. We'll see :)